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 |
|---|---|---|---|---|---|
1,893,955 | >
> What is the angle between the hour and minute hands of a clock at 6:05?
>
>
>
I have tried this
Hour Hand:
12 hour = 360°
1 hr = 30°
Total Hour above the Clock is $\frac{73}2$ hours
In Minute Hand:
1 Hour = 360°
1 minutes = 6°
Total Minutes covered by $6\times 5= 30$
$\frac{73}{2} \cdot30-30=345^\circ$ Is it Correct? | 2016/08/16 | [
"https://math.stackexchange.com/questions/1893955",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/359877/"
] | Think of it this way: five minutes after six, the minute hand is $\frac1{12}$ of the circle ahead from 12, while the hour hand has advanced $\frac1{12}$ of the way towards 7 from 6, or $\frac1{144}$ of the circle ahead. The initial angle between the two hands is $\frac12$ of the circle, so the solution is
$$\frac12-\frac1{12}+\frac1{144}=\frac{61}{144}=152.5^\circ$$ | Your approach is correct, but the hour is $6+\frac{5}{60}=\frac{73}{12}$, not $\frac{73}{2}$.
This yields an angle of $\frac{73}{12}\cdot30^\circ$ for the hour hand, and $6^\circ\cdot 5=30^\circ$ for the minute hand.
Thus the end result is $\frac{73}{12}\cdot30^\circ-30^\circ=152.5^\circ$ |
1,893,955 | >
> What is the angle between the hour and minute hands of a clock at 6:05?
>
>
>
I have tried this
Hour Hand:
12 hour = 360°
1 hr = 30°
Total Hour above the Clock is $\frac{73}2$ hours
In Minute Hand:
1 Hour = 360°
1 minutes = 6°
Total Minutes covered by $6\times 5= 30$
$\frac{73}{2} \cdot30-30=345^\circ$ Is it Correct? | 2016/08/16 | [
"https://math.stackexchange.com/questions/1893955",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/359877/"
] | The hours hand revolves $360°/(12\cdot60)=0.5°$ per minute and the minutes hand $360°/60=6°$ per minute, so that the angle increases by $5.5°$ per minute.
Hence working modulo $360°$, $$(6\cdot60+5)\cdot5.5°=2007.5°\equiv-152.5°=-152°30'.$$
The negative sign is because the hours hand is ahead. | Let $\alpha$ be the angle in degrees of the hour hand, measured with reference to $12$ and $\beta$ be the angle in degrees of the minute hand measured with reference to $12$.
At 6:05, the minute hand has moved $\frac{1}{12}$ of the way around the clock. Thus, $\beta=\frac{360^{\circ}}{12}=30^{\circ}$.
The hour hand has moved $\frac{1}{12}$ of the way from $6$ to $7$. In other words, $\frac{1}{12}\cdot\frac{1}{12}=\frac{1}{144}$ of the way from the $6$. Thus, $\alpha=180+\frac{360}{144}=182.5^{\circ}$.
Therefore, the angle between the two hands is $\alpha-\beta=182.5^{\circ}-30^{\circ}=152.5^{\circ}$. |
1,893,955 | >
> What is the angle between the hour and minute hands of a clock at 6:05?
>
>
>
I have tried this
Hour Hand:
12 hour = 360°
1 hr = 30°
Total Hour above the Clock is $\frac{73}2$ hours
In Minute Hand:
1 Hour = 360°
1 minutes = 6°
Total Minutes covered by $6\times 5= 30$
$\frac{73}{2} \cdot30-30=345^\circ$ Is it Correct? | 2016/08/16 | [
"https://math.stackexchange.com/questions/1893955",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/359877/"
] | Think of it this way: five minutes after six, the minute hand is $\frac1{12}$ of the circle ahead from 12, while the hour hand has advanced $\frac1{12}$ of the way towards 7 from 6, or $\frac1{144}$ of the circle ahead. The initial angle between the two hands is $\frac12$ of the circle, so the solution is
$$\frac12-\frac1{12}+\frac1{144}=\frac{61}{144}=152.5^\circ$$ | >
> Here is how much the hour hand travels per hour, minute, second:
>
>
> * Per Hour:
> $$\text{H}=\frac{360^{\circ}}{12\space\text{hours}}=30^{\circ}\text{/}\space\text{hour}$$
> * Per Minute:
> $$\text{M}=\frac{\text{H}^{\circ}}{60\space\text{minutes}}=\left(\frac{1}{2}\right)^{\circ}\text{/}\space\text{minute}$$
> * Per Second:
> $$\text{S}=\frac{\text{M}^{\circ}}{60\space\text{seconds}}=\left(\frac{1}{120}\right)^{\circ}\text{/}\space\text{second}$$
>
>
>
---
So, when it is $6:05$, we get:
$$6\cdot30^{\circ}+5\cdot\left(\frac{1}{2}\right)^{\circ}=182.5^{\circ}$$
But, for the 'minute hand' we got $30^{\circ}$ too much, so:
$$\text{angle}=182.5^{\circ}-30^{\circ}=152.5^{\circ}$$ |
37,425,502 | I've created a form using PHP in which the user has to click on a radio button before clicking on the button to submit the form. It looks as follows:
```
<form name="films" action="showing.php" method="post">
<table id="filmtable">
<tr><th>Title</th><th>Length</th><th>Description</th><th>Poster</th><th>Required</th></tr>
<?php
//Loop through every row returned by $result query to display it in table.
while ($newArray = mysql_fetch_array($result)){
$title = $newArray['title'];
$length = $newArray['length'];
$description = $newArray['description'];
$image = $newArray['image'];
//Echo statements will display query results on screen.
echo "<tr><td>$title</td><td>$length</td><td>$description</td>";
echo "<td><image src=\"$image\"</td>";
echo "<td><input type=\"radio\" id='wanted' name=\"wanted[]\" value='$title'></td></tr>";
}
// if (! array_key_exists($_POST['wanted[0]'], $result)){
// echo "Select it.";
//}
?>
</table>
<input type="submit" onsubmit = 'return validate()' value="Select Film">
</form>
```
As a validation measure I created the following in Javascript with the aim of preventing the user from submitting the form if they have not selected a radio button:
```
<script>
function validate(){
var radio = document.getElementById('wanted').checked;
if(radio=="")
{
alert("Please select a film to continue making a booking.");
return false;
}
return true;
}
</script>
```
The script prevents the user from submitting the form if no selection has been made from the radio boxes as intended. However, it will only allow the form to be submitted if the first radio box is selected. Selecting any button other than this one will cause the submit attempt to fail. What changes should I make to the JS to rectify this situation? | 2016/05/24 | [
"https://Stackoverflow.com/questions/37425502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4747805/"
] | This PHP fetch loop attributes multiple times the same id="wanted" to many radio buttons.
An Id should be unique.... So it's a bad practice.
Remove the id and add a class instead:
```
echo "<td><input type=\"radio\" class=\"wanted[]\" name=\"wanted[]\" value='$title'></td></tr>";
```
Then, the use of jQuery saves pain...
Within your submit script:
```
if(!$('.wanted').prop("checked")){
alert("Please select a film to continue making a booking.");
return;
}
```
Add this jQuery lib call in your head:
```
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
```
**EDIT** - See comments
Function validate should be this:
```
function validate(){
var wantedChecked=$(".wanted:checked");
if (!wantedChecked.prop("checked")){
console.log("false");
return false;
}else{
console.log("true");
return true;
}
}
``` | `getElementById` returns the first element matching the selector. If you just want to verify that *any of them* were checked, you could do something like:
```
var anyChecked = document.querySelectorAll('[name=wanted]:checked').length > 0;
``` |
19,854,969 | **Care: No code here, only text and some questions about bitmap caching**
I'm currently developing an App which is almost finished. The only thing left, that I would like to do is caching images. Because, at the moment, when the user opens the app the app downloads images from a server. Those images are not static, that means they can change every minute/hour/day. I don't know when they change, because it's a list of images gathered by the amount of twitter shares, facebook likes etc. That means, when a picture has 100 likes and 100 tweets it is place 1. But when another picture gets more likes and tweets it gets rank 1 and the other one will be placed as rank 2. This isn't exactly my app, but just so you understand the principle.
Now I looked into Bitmap caching so the user doesn't have to download the same images over and over. The question I do have is how do I do it? I mean, i Understand HOW to cache bitmaps.
I looked into this documentation article: `http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html`
But, the problem is, how do I know if the Bitmap already got downloaded and has been cached or if I have to download it again? Don't I have to download the image first to check if I have this particular image already in my system?
I thought about getting the URL of the image, then convert it into a hash. And then, save the files to the cache with the hash as filename. Then, when the image URL comes it will be checked wether the image is available in the cache or not. If it is it will be loaded if not it will be downloaded. Would that the way to go be?
Or am I misunderstanding bitmap caching and it does it from its own already? | 2013/11/08 | [
"https://Stackoverflow.com/questions/19854969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2823419/"
] | Check this library:
<http://code.google.com/p/android-query/wiki/ImageLoading>
It does caching automagically
example
```
//fetch a remote resource in raw bitmap
String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";
aq.ajax(url, Bitmap.class, new AjaxCallback<Bitmap>() {
@Override
public void callback(String url, Bitmap object, AjaxStatus status) {
}
});.
```
<http://code.google.com/p/android-query/wiki/AsyncAPI> | You can try <https://github.com/thest1/LazyList>
the project code was designed for listviews, but still, its purpose is to download images from URLs in the backgroud so the user doesn't have to hold on the whole downloading time.
you take these JAVA classes : `FileCache`, `ImageLoader`, `MemoryCache`, import them into your project,
for downloading an image you just call `imageLoader.DisplayImage(URL,ImageView);`
the best part is that it takes care of the cache itself so you don't have to worry about that
hope this helps |
19,854,969 | **Care: No code here, only text and some questions about bitmap caching**
I'm currently developing an App which is almost finished. The only thing left, that I would like to do is caching images. Because, at the moment, when the user opens the app the app downloads images from a server. Those images are not static, that means they can change every minute/hour/day. I don't know when they change, because it's a list of images gathered by the amount of twitter shares, facebook likes etc. That means, when a picture has 100 likes and 100 tweets it is place 1. But when another picture gets more likes and tweets it gets rank 1 and the other one will be placed as rank 2. This isn't exactly my app, but just so you understand the principle.
Now I looked into Bitmap caching so the user doesn't have to download the same images over and over. The question I do have is how do I do it? I mean, i Understand HOW to cache bitmaps.
I looked into this documentation article: `http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html`
But, the problem is, how do I know if the Bitmap already got downloaded and has been cached or if I have to download it again? Don't I have to download the image first to check if I have this particular image already in my system?
I thought about getting the URL of the image, then convert it into a hash. And then, save the files to the cache with the hash as filename. Then, when the image URL comes it will be checked wether the image is available in the cache or not. If it is it will be loaded if not it will be downloaded. Would that the way to go be?
Or am I misunderstanding bitmap caching and it does it from its own already? | 2013/11/08 | [
"https://Stackoverflow.com/questions/19854969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2823419/"
] | my best advice on those cases is: Do not try to re-invent the wheel.
Image loading/caching is a very complex task in Android and a lot of good developers already did that. Just re-use their work.
My personal preference is Picasso <http://square.github.io/picasso/>
to load stuff with it is one very simple line of code:
```
Picasso.with(context).load(url).into(imgView);
```
it's that simple!
It does both RAM and disk cache, handles all threading issues and use the excellent network layer okHttp.
**edit:**
and to get access directly to the Bitmap you can:
```
Picasso.with(context).load(url).into(new Target() {
void onBitmapLoaded(Bitmap bitmap, LoadedFrom from){
// this will be called on the UI thread after load finishes
}
void onBitmapFailed(Drawable errorDrawable){
}
void onPrepareLoad(Drawable placeHolderDrawable){
}
```
}); | Check this library:
<http://code.google.com/p/android-query/wiki/ImageLoading>
It does caching automagically
example
```
//fetch a remote resource in raw bitmap
String url = "http://www.vikispot.com/z/images/vikispot/android-w.png";
aq.ajax(url, Bitmap.class, new AjaxCallback<Bitmap>() {
@Override
public void callback(String url, Bitmap object, AjaxStatus status) {
}
});.
```
<http://code.google.com/p/android-query/wiki/AsyncAPI> |
19,854,969 | **Care: No code here, only text and some questions about bitmap caching**
I'm currently developing an App which is almost finished. The only thing left, that I would like to do is caching images. Because, at the moment, when the user opens the app the app downloads images from a server. Those images are not static, that means they can change every minute/hour/day. I don't know when they change, because it's a list of images gathered by the amount of twitter shares, facebook likes etc. That means, when a picture has 100 likes and 100 tweets it is place 1. But when another picture gets more likes and tweets it gets rank 1 and the other one will be placed as rank 2. This isn't exactly my app, but just so you understand the principle.
Now I looked into Bitmap caching so the user doesn't have to download the same images over and over. The question I do have is how do I do it? I mean, i Understand HOW to cache bitmaps.
I looked into this documentation article: `http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html`
But, the problem is, how do I know if the Bitmap already got downloaded and has been cached or if I have to download it again? Don't I have to download the image first to check if I have this particular image already in my system?
I thought about getting the URL of the image, then convert it into a hash. And then, save the files to the cache with the hash as filename. Then, when the image URL comes it will be checked wether the image is available in the cache or not. If it is it will be loaded if not it will be downloaded. Would that the way to go be?
Or am I misunderstanding bitmap caching and it does it from its own already? | 2013/11/08 | [
"https://Stackoverflow.com/questions/19854969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2823419/"
] | my best advice on those cases is: Do not try to re-invent the wheel.
Image loading/caching is a very complex task in Android and a lot of good developers already did that. Just re-use their work.
My personal preference is Picasso <http://square.github.io/picasso/>
to load stuff with it is one very simple line of code:
```
Picasso.with(context).load(url).into(imgView);
```
it's that simple!
It does both RAM and disk cache, handles all threading issues and use the excellent network layer okHttp.
**edit:**
and to get access directly to the Bitmap you can:
```
Picasso.with(context).load(url).into(new Target() {
void onBitmapLoaded(Bitmap bitmap, LoadedFrom from){
// this will be called on the UI thread after load finishes
}
void onBitmapFailed(Drawable errorDrawable){
}
void onPrepareLoad(Drawable placeHolderDrawable){
}
```
}); | You can try <https://github.com/thest1/LazyList>
the project code was designed for listviews, but still, its purpose is to download images from URLs in the backgroud so the user doesn't have to hold on the whole downloading time.
you take these JAVA classes : `FileCache`, `ImageLoader`, `MemoryCache`, import them into your project,
for downloading an image you just call `imageLoader.DisplayImage(URL,ImageView);`
the best part is that it takes care of the cache itself so you don't have to worry about that
hope this helps |
6,278,133 | I'd like to split a dataframe into several component dataframes based on the values in one column.
In my example, I want to split dat into dat.1, dat.2 and dat.3 using the values in column "cond".
Is there a simple command which could achieve this?
```
dat
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
1 2 1 2219 9291
1 2 2 3886 7890
1 3 1 4011 9032
2 2 1 3478 8827
2 2 2 2263 8321
2 3 1 4312 7576
3 1 1 4219 7891
3 3 1 3992 6674
dat.1
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
3 1 1 4219 7891
dat.2
sub cond trial time01 time02
2 2 1 3478 8827
2 2 2 2263 8321
1 2 1 2219 9291
1 2 2 3886 7890
dat.3
sub cond trial time01 time02
1 3 1 4011 9032
2 3 1 4312 7576
3 3 1 3992 6674
```
Perhaps because I'm an R novice I've still not determined how to do this despite browsing and trying the solutions proposed in several similar forum queries. Thank you in advance for any replies.
A `dput()` of the data is:
```
structure(list(sub = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L
), cond = c(1L, 1L, 2L, 2L, 3L, 2L, 2L, 3L, 1L, 3L), trial = c(1L,
2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L), time01 = c(2774L, 2697L,
2219L, 3886L, 4011L, 3478L, 2263L, 4312L, 4219L, 3992L), time02 = c(8845L,
9945L, 9291L, 7890L, 9032L, 8827L, 8321L, 7576L, 7891L, 6674L
)), .Names = c("sub", "cond", "trial", "time01", "time02"), class = "data.frame", row.names = c(NA,
-10L))
``` | 2011/06/08 | [
"https://Stackoverflow.com/questions/6278133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/789087/"
] | Is there anything not satisfying about
```
split(dat, dat$cond)
```
?
You do have R and split as tags, you know... | Just for the sake of completeness, here's a way to do it with the `plyr` package.
```
require(plyr)
> dlply( dat, .(cond))
$`1`
sub cond trial time01 time02
1 1 1 1 2774 8845
2 1 1 2 2697 9945
9 3 1 1 4219 7891
$`2`
sub cond trial time01 time02
3 1 2 1 2219 9291
4 1 2 2 3886 7890
6 2 2 1 3478 8827
7 2 2 2 2263 8321
$`3`
sub cond trial time01 time02
5 1 3 1 4011 9032
8 2 3 1 4312 7576
10 3 3 1 3992 6674
attr(,"class")
[1] "split" "list"
```
Note the syntactic simplicity in that you only mention `dat` once. |
6,278,133 | I'd like to split a dataframe into several component dataframes based on the values in one column.
In my example, I want to split dat into dat.1, dat.2 and dat.3 using the values in column "cond".
Is there a simple command which could achieve this?
```
dat
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
1 2 1 2219 9291
1 2 2 3886 7890
1 3 1 4011 9032
2 2 1 3478 8827
2 2 2 2263 8321
2 3 1 4312 7576
3 1 1 4219 7891
3 3 1 3992 6674
dat.1
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
3 1 1 4219 7891
dat.2
sub cond trial time01 time02
2 2 1 3478 8827
2 2 2 2263 8321
1 2 1 2219 9291
1 2 2 3886 7890
dat.3
sub cond trial time01 time02
1 3 1 4011 9032
2 3 1 4312 7576
3 3 1 3992 6674
```
Perhaps because I'm an R novice I've still not determined how to do this despite browsing and trying the solutions proposed in several similar forum queries. Thank you in advance for any replies.
A `dput()` of the data is:
```
structure(list(sub = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L
), cond = c(1L, 1L, 2L, 2L, 3L, 2L, 2L, 3L, 1L, 3L), trial = c(1L,
2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L), time01 = c(2774L, 2697L,
2219L, 3886L, 4011L, 3478L, 2263L, 4312L, 4219L, 3992L), time02 = c(8845L,
9945L, 9291L, 7890L, 9032L, 8827L, 8321L, 7576L, 7891L, 6674L
)), .Names = c("sub", "cond", "trial", "time01", "time02"), class = "data.frame", row.names = c(NA,
-10L))
``` | 2011/06/08 | [
"https://Stackoverflow.com/questions/6278133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/789087/"
] | Is there anything not satisfying about
```
split(dat, dat$cond)
```
?
You do have R and split as tags, you know... | ;)
```
ucond <- unique(dat$cond)
dat_by_cond <- lapply(lapply(ucond, "==", dat$cond), subset, x=dat)
names(dat_by_cond) <- paste("dat",ucond,sep=".")
``` |
6,278,133 | I'd like to split a dataframe into several component dataframes based on the values in one column.
In my example, I want to split dat into dat.1, dat.2 and dat.3 using the values in column "cond".
Is there a simple command which could achieve this?
```
dat
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
1 2 1 2219 9291
1 2 2 3886 7890
1 3 1 4011 9032
2 2 1 3478 8827
2 2 2 2263 8321
2 3 1 4312 7576
3 1 1 4219 7891
3 3 1 3992 6674
dat.1
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
3 1 1 4219 7891
dat.2
sub cond trial time01 time02
2 2 1 3478 8827
2 2 2 2263 8321
1 2 1 2219 9291
1 2 2 3886 7890
dat.3
sub cond trial time01 time02
1 3 1 4011 9032
2 3 1 4312 7576
3 3 1 3992 6674
```
Perhaps because I'm an R novice I've still not determined how to do this despite browsing and trying the solutions proposed in several similar forum queries. Thank you in advance for any replies.
A `dput()` of the data is:
```
structure(list(sub = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L
), cond = c(1L, 1L, 2L, 2L, 3L, 2L, 2L, 3L, 1L, 3L), trial = c(1L,
2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L), time01 = c(2774L, 2697L,
2219L, 3886L, 4011L, 3478L, 2263L, 4312L, 4219L, 3992L), time02 = c(8845L,
9945L, 9291L, 7890L, 9032L, 8827L, 8321L, 7576L, 7891L, 6674L
)), .Names = c("sub", "cond", "trial", "time01", "time02"), class = "data.frame", row.names = c(NA,
-10L))
``` | 2011/06/08 | [
"https://Stackoverflow.com/questions/6278133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/789087/"
] | Yes, `split()`. For example, if your data are in `dat`, then:
```
with(dat, split(dat, cond))
```
returns a list, whose components are the data frames you wanted:
```
R> with(dat, split(dat, cond))
$`1`
sub cond trial time01 time02
1 1 1 1 2774 8845
2 1 1 2 2697 9945
9 3 1 1 4219 7891
$`2`
sub cond trial time01 time02
3 1 2 1 2219 9291
4 1 2 2 3886 7890
6 2 2 1 3478 8827
7 2 2 2 2263 8321
$`3`
sub cond trial time01 time02
5 1 3 1 4011 9032
8 2 3 1 4312 7576
10 3 3 1 3992 6674
``` | Just for the sake of completeness, here's a way to do it with the `plyr` package.
```
require(plyr)
> dlply( dat, .(cond))
$`1`
sub cond trial time01 time02
1 1 1 1 2774 8845
2 1 1 2 2697 9945
9 3 1 1 4219 7891
$`2`
sub cond trial time01 time02
3 1 2 1 2219 9291
4 1 2 2 3886 7890
6 2 2 1 3478 8827
7 2 2 2 2263 8321
$`3`
sub cond trial time01 time02
5 1 3 1 4011 9032
8 2 3 1 4312 7576
10 3 3 1 3992 6674
attr(,"class")
[1] "split" "list"
```
Note the syntactic simplicity in that you only mention `dat` once. |
6,278,133 | I'd like to split a dataframe into several component dataframes based on the values in one column.
In my example, I want to split dat into dat.1, dat.2 and dat.3 using the values in column "cond".
Is there a simple command which could achieve this?
```
dat
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
1 2 1 2219 9291
1 2 2 3886 7890
1 3 1 4011 9032
2 2 1 3478 8827
2 2 2 2263 8321
2 3 1 4312 7576
3 1 1 4219 7891
3 3 1 3992 6674
dat.1
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
3 1 1 4219 7891
dat.2
sub cond trial time01 time02
2 2 1 3478 8827
2 2 2 2263 8321
1 2 1 2219 9291
1 2 2 3886 7890
dat.3
sub cond trial time01 time02
1 3 1 4011 9032
2 3 1 4312 7576
3 3 1 3992 6674
```
Perhaps because I'm an R novice I've still not determined how to do this despite browsing and trying the solutions proposed in several similar forum queries. Thank you in advance for any replies.
A `dput()` of the data is:
```
structure(list(sub = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L
), cond = c(1L, 1L, 2L, 2L, 3L, 2L, 2L, 3L, 1L, 3L), trial = c(1L,
2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L), time01 = c(2774L, 2697L,
2219L, 3886L, 4011L, 3478L, 2263L, 4312L, 4219L, 3992L), time02 = c(8845L,
9945L, 9291L, 7890L, 9032L, 8827L, 8321L, 7576L, 7891L, 6674L
)), .Names = c("sub", "cond", "trial", "time01", "time02"), class = "data.frame", row.names = c(NA,
-10L))
``` | 2011/06/08 | [
"https://Stackoverflow.com/questions/6278133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/789087/"
] | Yes, `split()`. For example, if your data are in `dat`, then:
```
with(dat, split(dat, cond))
```
returns a list, whose components are the data frames you wanted:
```
R> with(dat, split(dat, cond))
$`1`
sub cond trial time01 time02
1 1 1 1 2774 8845
2 1 1 2 2697 9945
9 3 1 1 4219 7891
$`2`
sub cond trial time01 time02
3 1 2 1 2219 9291
4 1 2 2 3886 7890
6 2 2 1 3478 8827
7 2 2 2 2263 8321
$`3`
sub cond trial time01 time02
5 1 3 1 4011 9032
8 2 3 1 4312 7576
10 3 3 1 3992 6674
``` | ;)
```
ucond <- unique(dat$cond)
dat_by_cond <- lapply(lapply(ucond, "==", dat$cond), subset, x=dat)
names(dat_by_cond) <- paste("dat",ucond,sep=".")
``` |
6,278,133 | I'd like to split a dataframe into several component dataframes based on the values in one column.
In my example, I want to split dat into dat.1, dat.2 and dat.3 using the values in column "cond".
Is there a simple command which could achieve this?
```
dat
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
1 2 1 2219 9291
1 2 2 3886 7890
1 3 1 4011 9032
2 2 1 3478 8827
2 2 2 2263 8321
2 3 1 4312 7576
3 1 1 4219 7891
3 3 1 3992 6674
dat.1
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
3 1 1 4219 7891
dat.2
sub cond trial time01 time02
2 2 1 3478 8827
2 2 2 2263 8321
1 2 1 2219 9291
1 2 2 3886 7890
dat.3
sub cond trial time01 time02
1 3 1 4011 9032
2 3 1 4312 7576
3 3 1 3992 6674
```
Perhaps because I'm an R novice I've still not determined how to do this despite browsing and trying the solutions proposed in several similar forum queries. Thank you in advance for any replies.
A `dput()` of the data is:
```
structure(list(sub = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L
), cond = c(1L, 1L, 2L, 2L, 3L, 2L, 2L, 3L, 1L, 3L), trial = c(1L,
2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L), time01 = c(2774L, 2697L,
2219L, 3886L, 4011L, 3478L, 2263L, 4312L, 4219L, 3992L), time02 = c(8845L,
9945L, 9291L, 7890L, 9032L, 8827L, 8321L, 7576L, 7891L, 6674L
)), .Names = c("sub", "cond", "trial", "time01", "time02"), class = "data.frame", row.names = c(NA,
-10L))
``` | 2011/06/08 | [
"https://Stackoverflow.com/questions/6278133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/789087/"
] | I think the easiest way is via `split`:
```
split(dat, dat$cond)
```
Note however, that split returns a list of the data.frames.
To obtain single data.frames from the list you could procede as follows using a loop to make the single objects (implicit in the `lapply` statement):
```
tmp <- split(dat, dat$cond)
lapply(1:length(tmp), function(x) assign(paste("dat.", x, sep = ""), tmp[[x]], envir = .GlobalEnv))
```
However, using a list is probably more `R`ish and will be more useful in the long run.
Thanks to Gavin for posting the data! | Just for the sake of completeness, here's a way to do it with the `plyr` package.
```
require(plyr)
> dlply( dat, .(cond))
$`1`
sub cond trial time01 time02
1 1 1 1 2774 8845
2 1 1 2 2697 9945
9 3 1 1 4219 7891
$`2`
sub cond trial time01 time02
3 1 2 1 2219 9291
4 1 2 2 3886 7890
6 2 2 1 3478 8827
7 2 2 2 2263 8321
$`3`
sub cond trial time01 time02
5 1 3 1 4011 9032
8 2 3 1 4312 7576
10 3 3 1 3992 6674
attr(,"class")
[1] "split" "list"
```
Note the syntactic simplicity in that you only mention `dat` once. |
6,278,133 | I'd like to split a dataframe into several component dataframes based on the values in one column.
In my example, I want to split dat into dat.1, dat.2 and dat.3 using the values in column "cond".
Is there a simple command which could achieve this?
```
dat
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
1 2 1 2219 9291
1 2 2 3886 7890
1 3 1 4011 9032
2 2 1 3478 8827
2 2 2 2263 8321
2 3 1 4312 7576
3 1 1 4219 7891
3 3 1 3992 6674
dat.1
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
3 1 1 4219 7891
dat.2
sub cond trial time01 time02
2 2 1 3478 8827
2 2 2 2263 8321
1 2 1 2219 9291
1 2 2 3886 7890
dat.3
sub cond trial time01 time02
1 3 1 4011 9032
2 3 1 4312 7576
3 3 1 3992 6674
```
Perhaps because I'm an R novice I've still not determined how to do this despite browsing and trying the solutions proposed in several similar forum queries. Thank you in advance for any replies.
A `dput()` of the data is:
```
structure(list(sub = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L
), cond = c(1L, 1L, 2L, 2L, 3L, 2L, 2L, 3L, 1L, 3L), trial = c(1L,
2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L), time01 = c(2774L, 2697L,
2219L, 3886L, 4011L, 3478L, 2263L, 4312L, 4219L, 3992L), time02 = c(8845L,
9945L, 9291L, 7890L, 9032L, 8827L, 8321L, 7576L, 7891L, 6674L
)), .Names = c("sub", "cond", "trial", "time01", "time02"), class = "data.frame", row.names = c(NA,
-10L))
``` | 2011/06/08 | [
"https://Stackoverflow.com/questions/6278133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/789087/"
] | I think the easiest way is via `split`:
```
split(dat, dat$cond)
```
Note however, that split returns a list of the data.frames.
To obtain single data.frames from the list you could procede as follows using a loop to make the single objects (implicit in the `lapply` statement):
```
tmp <- split(dat, dat$cond)
lapply(1:length(tmp), function(x) assign(paste("dat.", x, sep = ""), tmp[[x]], envir = .GlobalEnv))
```
However, using a list is probably more `R`ish and will be more useful in the long run.
Thanks to Gavin for posting the data! | ;)
```
ucond <- unique(dat$cond)
dat_by_cond <- lapply(lapply(ucond, "==", dat$cond), subset, x=dat)
names(dat_by_cond) <- paste("dat",ucond,sep=".")
``` |
6,278,133 | I'd like to split a dataframe into several component dataframes based on the values in one column.
In my example, I want to split dat into dat.1, dat.2 and dat.3 using the values in column "cond".
Is there a simple command which could achieve this?
```
dat
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
1 2 1 2219 9291
1 2 2 3886 7890
1 3 1 4011 9032
2 2 1 3478 8827
2 2 2 2263 8321
2 3 1 4312 7576
3 1 1 4219 7891
3 3 1 3992 6674
dat.1
sub cond trial time01 time02
1 1 1 2774 8845
1 1 2 2697 9945
3 1 1 4219 7891
dat.2
sub cond trial time01 time02
2 2 1 3478 8827
2 2 2 2263 8321
1 2 1 2219 9291
1 2 2 3886 7890
dat.3
sub cond trial time01 time02
1 3 1 4011 9032
2 3 1 4312 7576
3 3 1 3992 6674
```
Perhaps because I'm an R novice I've still not determined how to do this despite browsing and trying the solutions proposed in several similar forum queries. Thank you in advance for any replies.
A `dput()` of the data is:
```
structure(list(sub = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L
), cond = c(1L, 1L, 2L, 2L, 3L, 2L, 2L, 3L, 1L, 3L), trial = c(1L,
2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L), time01 = c(2774L, 2697L,
2219L, 3886L, 4011L, 3478L, 2263L, 4312L, 4219L, 3992L), time02 = c(8845L,
9945L, 9291L, 7890L, 9032L, 8827L, 8321L, 7576L, 7891L, 6674L
)), .Names = c("sub", "cond", "trial", "time01", "time02"), class = "data.frame", row.names = c(NA,
-10L))
``` | 2011/06/08 | [
"https://Stackoverflow.com/questions/6278133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/789087/"
] | Just for the sake of completeness, here's a way to do it with the `plyr` package.
```
require(plyr)
> dlply( dat, .(cond))
$`1`
sub cond trial time01 time02
1 1 1 1 2774 8845
2 1 1 2 2697 9945
9 3 1 1 4219 7891
$`2`
sub cond trial time01 time02
3 1 2 1 2219 9291
4 1 2 2 3886 7890
6 2 2 1 3478 8827
7 2 2 2 2263 8321
$`3`
sub cond trial time01 time02
5 1 3 1 4011 9032
8 2 3 1 4312 7576
10 3 3 1 3992 6674
attr(,"class")
[1] "split" "list"
```
Note the syntactic simplicity in that you only mention `dat` once. | ;)
```
ucond <- unique(dat$cond)
dat_by_cond <- lapply(lapply(ucond, "==", dat$cond), subset, x=dat)
names(dat_by_cond) <- paste("dat",ucond,sep=".")
``` |
32,330,639 | I'm trying to create a custom viewpager inside custom scroll viewthat dynamically wraps the current child's height.
```
package com.example.vihaan.dynamicviewpager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ScrollView;
/**
* Created by vihaan on 1/9/15.
*/
public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev)
&& mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return (Math.abs(distanceY) > Math.abs(distanceX));
}
}
}
```
CustomPager
```
/**
* Created by vihaan on 1/9/15.
*/
public class CustomPager extends ViewPager {
public CustomPager (Context context) {
super(context);
}
public CustomPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
int width = getMeasuredWidth();
int tabHeight = tab.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(tabHeight + fragmentHeight + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
```
MyPagerAdapter
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new FirstFragment());
fragments.add(new SecondFragment());
fragments.add(new ThirdFragment());
fragments.add(new FourthFragment());
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
```
I was hoping that this would wrap around current fragments height but it is only taking the height of first child into consideration.
Sample github project : <https://github.com/VihaanVerma89/DynamicViewPager> | 2015/09/01 | [
"https://Stackoverflow.com/questions/32330639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203565/"
] | Made a few tweaks in your code and it is working fine now.
1] `onMeasure` function wasn't proper. Use below logic
```
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mCurrentView == null) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
int height = 0;
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = mCurrentView.getMeasuredHeight();
if (h > height) height = h;
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
```
2] `ViewPager` needs to be re-measured each time a page is changed. Good place to do this is `setPrimaryItem` function of `PagerAdapter`
```
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (position != mCurrentPosition) {
Fragment fragment = (Fragment) object;
CustomPager pager = (CustomPager) container;
if (fragment != null && fragment.getView() != null) {
mCurrentPosition = position;
pager.measureCurrentView(fragment.getView());
}
}
}
```
Here is the link to GitHub project with these tweaks:
<https://github.com/vabhishek/WrapContentViewPagerDemo> | ```
public class WrapContentViewPager extends ViewPager {
private Boolean mAnimStarted = false;
public WrapContentViewPager(Context context) {
super(context);
}
public WrapContentViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!mAnimStarted && null != getAdapter()) {
int height = 0;
View child = ((CommonViewPagerAdapter) getAdapter()).getItem(getCurrentItem()).getView();
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
height = child.getMeasuredHeight();
if (height < getMinimumHeight()) {
height = getMinimumHeight();
}
}
// Not the best place to put this animation, but it works pretty good.
int newHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
if (getLayoutParams().height != 0 && heightMeasureSpec != newHeight) {
final int targetHeight = height;
final int currentHeight = getLayoutParams().height;
final int heightChange = targetHeight - currentHeight;
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime >= 1) {
getLayoutParams().height = targetHeight;
} else {
int stepHeight = (int) (heightChange * interpolatedTime);
getLayoutParams().height = currentHeight + stepHeight;
}
requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mAnimStarted = true;
}
@Override
public void onAnimationEnd(Animation animation) {
mAnimStarted = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
a.setDuration(100);
startAnimation(a);
mAnimStarted = true;
} else {
heightMeasureSpec = newHeight;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
```
==============================
```
wrapContentViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
wrapContentViewPager.measure(wrapContentViewPager.getMeasuredWidth(), wrapContentViewPager.getMeasuredHeight());
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
``` |
32,330,639 | I'm trying to create a custom viewpager inside custom scroll viewthat dynamically wraps the current child's height.
```
package com.example.vihaan.dynamicviewpager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ScrollView;
/**
* Created by vihaan on 1/9/15.
*/
public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev)
&& mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return (Math.abs(distanceY) > Math.abs(distanceX));
}
}
}
```
CustomPager
```
/**
* Created by vihaan on 1/9/15.
*/
public class CustomPager extends ViewPager {
public CustomPager (Context context) {
super(context);
}
public CustomPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
int width = getMeasuredWidth();
int tabHeight = tab.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(tabHeight + fragmentHeight + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
```
MyPagerAdapter
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new FirstFragment());
fragments.add(new SecondFragment());
fragments.add(new ThirdFragment());
fragments.add(new FourthFragment());
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
```
I was hoping that this would wrap around current fragments height but it is only taking the height of first child into consideration.
Sample github project : <https://github.com/VihaanVerma89/DynamicViewPager> | 2015/09/01 | [
"https://Stackoverflow.com/questions/32330639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203565/"
] | Made a few tweaks in your code and it is working fine now.
1] `onMeasure` function wasn't proper. Use below logic
```
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mCurrentView == null) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
int height = 0;
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = mCurrentView.getMeasuredHeight();
if (h > height) height = h;
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
```
2] `ViewPager` needs to be re-measured each time a page is changed. Good place to do this is `setPrimaryItem` function of `PagerAdapter`
```
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (position != mCurrentPosition) {
Fragment fragment = (Fragment) object;
CustomPager pager = (CustomPager) container;
if (fragment != null && fragment.getView() != null) {
mCurrentPosition = position;
pager.measureCurrentView(fragment.getView());
}
}
}
```
Here is the link to GitHub project with these tweaks:
<https://github.com/vabhishek/WrapContentViewPagerDemo> | Just in case someone else find this post like me. Worked version without bug of initially zero height:
```
public class DynamicHeightViewPager extends ViewPager {
private View mCurrentView;
public DynamicHeightViewPager(Context context) {
super(context);
}
public DynamicHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mCurrentView != null) {
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int height = Math.max(0, mCurrentView.getMeasuredHeight());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void measureCurrentView(View currentView) {
mCurrentView = currentView;
requestLayout();
}
}
```
And used it in custom FragmentPagerAdapter, like this
```
public abstract class AutoheightFragmentPagerAdapter extends FragmentPagerAdapter {
private int mCurrentPosition = -1;
public AutoheightFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (position != mCurrentPosition && container instanceof DynamicHeightViewPager) {
Fragment fragment = (Fragment) object;
DynamicHeightViewPager pager = (DynamicHeightViewPager) container;
if (fragment != null && fragment.getView() != null) {
mCurrentPosition = position;
pager.measureCurrentView(fragment.getView());
}
}
}
}
``` |
32,330,639 | I'm trying to create a custom viewpager inside custom scroll viewthat dynamically wraps the current child's height.
```
package com.example.vihaan.dynamicviewpager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ScrollView;
/**
* Created by vihaan on 1/9/15.
*/
public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev)
&& mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return (Math.abs(distanceY) > Math.abs(distanceX));
}
}
}
```
CustomPager
```
/**
* Created by vihaan on 1/9/15.
*/
public class CustomPager extends ViewPager {
public CustomPager (Context context) {
super(context);
}
public CustomPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
int width = getMeasuredWidth();
int tabHeight = tab.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(tabHeight + fragmentHeight + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
```
MyPagerAdapter
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new FirstFragment());
fragments.add(new SecondFragment());
fragments.add(new ThirdFragment());
fragments.add(new FourthFragment());
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
```
I was hoping that this would wrap around current fragments height but it is only taking the height of first child into consideration.
Sample github project : <https://github.com/VihaanVerma89/DynamicViewPager> | 2015/09/01 | [
"https://Stackoverflow.com/questions/32330639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203565/"
] | Adding to @vihaan's solution, if you have a PagerTitleStrip or PagetTabStrip, you can add this
```
// Account for pagerTitleStrip or pagerTabStrip
View tabStrip = getChildAt(0);
if (tabStrip instanceof PagerTitleStrip) {
tabStrip.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.UNSPECIFIED));
height += tabStrip.getMeasuredHeight();
}
```
just before starting the animation (before the comment
```
// Not the best place to put this animation, but it works pretty good.
```
so that the height of the strip is taken into account. | This few lines of code will solve the problem.
Create a custome widget for viewpager class. and in xml use it for viewpager.
```
public class DynamicHeightViewPager extends ViewPager {
private View mCurrentView;
public DynamicHeightViewPager(Context context) {
super(context);
}
public DynamicHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mCurrentView != null) {
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int height = Math.max(0, mCurrentView.getMeasuredHeight());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void measureCurrentView(View currentView) {
mCurrentView = currentView;
requestLayout();
}
}
```
Then in the view pager adapter override the below method and add the code.
```
@Override
public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
super.setPrimaryItem(container, position, object);
if (container instanceof DynamicHeightViewPager) {
// instead of card view give your root view from your item.xml file.
CardView cardView = (CardView) object;
((DynamicHeightViewPager) container).measureCurrentView(cardView);
}
}
```
Make your view pager height **wrap\_content** inside xml file so you can check the result. |
32,330,639 | I'm trying to create a custom viewpager inside custom scroll viewthat dynamically wraps the current child's height.
```
package com.example.vihaan.dynamicviewpager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ScrollView;
/**
* Created by vihaan on 1/9/15.
*/
public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev)
&& mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return (Math.abs(distanceY) > Math.abs(distanceX));
}
}
}
```
CustomPager
```
/**
* Created by vihaan on 1/9/15.
*/
public class CustomPager extends ViewPager {
public CustomPager (Context context) {
super(context);
}
public CustomPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
int width = getMeasuredWidth();
int tabHeight = tab.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(tabHeight + fragmentHeight + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
```
MyPagerAdapter
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new FirstFragment());
fragments.add(new SecondFragment());
fragments.add(new ThirdFragment());
fragments.add(new FourthFragment());
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
```
I was hoping that this would wrap around current fragments height but it is only taking the height of first child into consideration.
Sample github project : <https://github.com/VihaanVerma89/DynamicViewPager> | 2015/09/01 | [
"https://Stackoverflow.com/questions/32330639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203565/"
] | @abhishek's ans does what is required but the code below also adds animation during height change
```
public class WrappingViewPager extends ViewPager {
private Boolean mAnimStarted = false;
public WrappingViewPager(Context context) {
super(context);
}
public WrappingViewPager(Context context, AttributeSet attrs){
super(context, attrs);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if(!mAnimStarted && null != getAdapter()) {
int height = 0;
View child = ((FragmentPagerAdapter) getAdapter()).getItem(getCurrentItem()).getView();
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
height = child.getMeasuredHeight();
if (VersionUtils.isJellyBean() && height < getMinimumHeight()) {
height = getMinimumHeight();
}
}
// Not the best place to put this animation, but it works pretty good.
int newHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
if (getLayoutParams().height != 0 && heightMeasureSpec != newHeight) {
final int targetHeight = height;
final int currentHeight = getLayoutParams().height;
final int heightChange = targetHeight - currentHeight;
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime >= 1) {
getLayoutParams().height = targetHeight;
} else {
int stepHeight = (int) (heightChange * interpolatedTime);
getLayoutParams().height = currentHeight + stepHeight;
}
requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mAnimStarted = true;
}
@Override
public void onAnimationEnd(Animation animation) {
mAnimStarted = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
a.setDuration(1000);
startAnimation(a);
mAnimStarted = true;
} else {
heightMeasureSpec = newHeight;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
``` | Just in case someone else find this post like me. Worked version without bug of initially zero height:
```
public class DynamicHeightViewPager extends ViewPager {
private View mCurrentView;
public DynamicHeightViewPager(Context context) {
super(context);
}
public DynamicHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mCurrentView != null) {
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int height = Math.max(0, mCurrentView.getMeasuredHeight());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void measureCurrentView(View currentView) {
mCurrentView = currentView;
requestLayout();
}
}
```
And used it in custom FragmentPagerAdapter, like this
```
public abstract class AutoheightFragmentPagerAdapter extends FragmentPagerAdapter {
private int mCurrentPosition = -1;
public AutoheightFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (position != mCurrentPosition && container instanceof DynamicHeightViewPager) {
Fragment fragment = (Fragment) object;
DynamicHeightViewPager pager = (DynamicHeightViewPager) container;
if (fragment != null && fragment.getView() != null) {
mCurrentPosition = position;
pager.measureCurrentView(fragment.getView());
}
}
}
}
``` |
32,330,639 | I'm trying to create a custom viewpager inside custom scroll viewthat dynamically wraps the current child's height.
```
package com.example.vihaan.dynamicviewpager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ScrollView;
/**
* Created by vihaan on 1/9/15.
*/
public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev)
&& mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return (Math.abs(distanceY) > Math.abs(distanceX));
}
}
}
```
CustomPager
```
/**
* Created by vihaan on 1/9/15.
*/
public class CustomPager extends ViewPager {
public CustomPager (Context context) {
super(context);
}
public CustomPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
int width = getMeasuredWidth();
int tabHeight = tab.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(tabHeight + fragmentHeight + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
```
MyPagerAdapter
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new FirstFragment());
fragments.add(new SecondFragment());
fragments.add(new ThirdFragment());
fragments.add(new FourthFragment());
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
```
I was hoping that this would wrap around current fragments height but it is only taking the height of first child into consideration.
Sample github project : <https://github.com/VihaanVerma89/DynamicViewPager> | 2015/09/01 | [
"https://Stackoverflow.com/questions/32330639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203565/"
] | Just in case someone else find this post like me. Worked version without bug of initially zero height:
```
public class DynamicHeightViewPager extends ViewPager {
private View mCurrentView;
public DynamicHeightViewPager(Context context) {
super(context);
}
public DynamicHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mCurrentView != null) {
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int height = Math.max(0, mCurrentView.getMeasuredHeight());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void measureCurrentView(View currentView) {
mCurrentView = currentView;
requestLayout();
}
}
```
And used it in custom FragmentPagerAdapter, like this
```
public abstract class AutoheightFragmentPagerAdapter extends FragmentPagerAdapter {
private int mCurrentPosition = -1;
public AutoheightFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (position != mCurrentPosition && container instanceof DynamicHeightViewPager) {
Fragment fragment = (Fragment) object;
DynamicHeightViewPager pager = (DynamicHeightViewPager) container;
if (fragment != null && fragment.getView() != null) {
mCurrentPosition = position;
pager.measureCurrentView(fragment.getView());
}
}
}
}
``` | Adding to @vihaan's solution, if you have a PagerTitleStrip or PagetTabStrip, you can add this
```
// Account for pagerTitleStrip or pagerTabStrip
View tabStrip = getChildAt(0);
if (tabStrip instanceof PagerTitleStrip) {
tabStrip.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.UNSPECIFIED));
height += tabStrip.getMeasuredHeight();
}
```
just before starting the animation (before the comment
```
// Not the best place to put this animation, but it works pretty good.
```
so that the height of the strip is taken into account. |
32,330,639 | I'm trying to create a custom viewpager inside custom scroll viewthat dynamically wraps the current child's height.
```
package com.example.vihaan.dynamicviewpager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ScrollView;
/**
* Created by vihaan on 1/9/15.
*/
public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev)
&& mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return (Math.abs(distanceY) > Math.abs(distanceX));
}
}
}
```
CustomPager
```
/**
* Created by vihaan on 1/9/15.
*/
public class CustomPager extends ViewPager {
public CustomPager (Context context) {
super(context);
}
public CustomPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
int width = getMeasuredWidth();
int tabHeight = tab.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(tabHeight + fragmentHeight + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
```
MyPagerAdapter
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new FirstFragment());
fragments.add(new SecondFragment());
fragments.add(new ThirdFragment());
fragments.add(new FourthFragment());
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
```
I was hoping that this would wrap around current fragments height but it is only taking the height of first child into consideration.
Sample github project : <https://github.com/VihaanVerma89/DynamicViewPager> | 2015/09/01 | [
"https://Stackoverflow.com/questions/32330639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203565/"
] | Made a few tweaks in your code and it is working fine now.
1] `onMeasure` function wasn't proper. Use below logic
```
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mCurrentView == null) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
int height = 0;
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = mCurrentView.getMeasuredHeight();
if (h > height) height = h;
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
```
2] `ViewPager` needs to be re-measured each time a page is changed. Good place to do this is `setPrimaryItem` function of `PagerAdapter`
```
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (position != mCurrentPosition) {
Fragment fragment = (Fragment) object;
CustomPager pager = (CustomPager) container;
if (fragment != null && fragment.getView() != null) {
mCurrentPosition = position;
pager.measureCurrentView(fragment.getView());
}
}
}
```
Here is the link to GitHub project with these tweaks:
<https://github.com/vabhishek/WrapContentViewPagerDemo> | This few lines of code will solve the problem.
Create a custome widget for viewpager class. and in xml use it for viewpager.
```
public class DynamicHeightViewPager extends ViewPager {
private View mCurrentView;
public DynamicHeightViewPager(Context context) {
super(context);
}
public DynamicHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mCurrentView != null) {
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int height = Math.max(0, mCurrentView.getMeasuredHeight());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void measureCurrentView(View currentView) {
mCurrentView = currentView;
requestLayout();
}
}
```
Then in the view pager adapter override the below method and add the code.
```
@Override
public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
super.setPrimaryItem(container, position, object);
if (container instanceof DynamicHeightViewPager) {
// instead of card view give your root view from your item.xml file.
CardView cardView = (CardView) object;
((DynamicHeightViewPager) container).measureCurrentView(cardView);
}
}
```
Make your view pager height **wrap\_content** inside xml file so you can check the result. |
32,330,639 | I'm trying to create a custom viewpager inside custom scroll viewthat dynamically wraps the current child's height.
```
package com.example.vihaan.dynamicviewpager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ScrollView;
/**
* Created by vihaan on 1/9/15.
*/
public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev)
&& mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return (Math.abs(distanceY) > Math.abs(distanceX));
}
}
}
```
CustomPager
```
/**
* Created by vihaan on 1/9/15.
*/
public class CustomPager extends ViewPager {
public CustomPager (Context context) {
super(context);
}
public CustomPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
int width = getMeasuredWidth();
int tabHeight = tab.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(tabHeight + fragmentHeight + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
```
MyPagerAdapter
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new FirstFragment());
fragments.add(new SecondFragment());
fragments.add(new ThirdFragment());
fragments.add(new FourthFragment());
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
```
I was hoping that this would wrap around current fragments height but it is only taking the height of first child into consideration.
Sample github project : <https://github.com/VihaanVerma89/DynamicViewPager> | 2015/09/01 | [
"https://Stackoverflow.com/questions/32330639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203565/"
] | @abhishek's ans does what is required but the code below also adds animation during height change
```
public class WrappingViewPager extends ViewPager {
private Boolean mAnimStarted = false;
public WrappingViewPager(Context context) {
super(context);
}
public WrappingViewPager(Context context, AttributeSet attrs){
super(context, attrs);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if(!mAnimStarted && null != getAdapter()) {
int height = 0;
View child = ((FragmentPagerAdapter) getAdapter()).getItem(getCurrentItem()).getView();
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
height = child.getMeasuredHeight();
if (VersionUtils.isJellyBean() && height < getMinimumHeight()) {
height = getMinimumHeight();
}
}
// Not the best place to put this animation, but it works pretty good.
int newHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
if (getLayoutParams().height != 0 && heightMeasureSpec != newHeight) {
final int targetHeight = height;
final int currentHeight = getLayoutParams().height;
final int heightChange = targetHeight - currentHeight;
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime >= 1) {
getLayoutParams().height = targetHeight;
} else {
int stepHeight = (int) (heightChange * interpolatedTime);
getLayoutParams().height = currentHeight + stepHeight;
}
requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mAnimStarted = true;
}
@Override
public void onAnimationEnd(Animation animation) {
mAnimStarted = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
a.setDuration(1000);
startAnimation(a);
mAnimStarted = true;
} else {
heightMeasureSpec = newHeight;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
``` | ```
public class WrapContentViewPager extends ViewPager {
private Boolean mAnimStarted = false;
public WrapContentViewPager(Context context) {
super(context);
}
public WrapContentViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!mAnimStarted && null != getAdapter()) {
int height = 0;
View child = ((CommonViewPagerAdapter) getAdapter()).getItem(getCurrentItem()).getView();
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
height = child.getMeasuredHeight();
if (height < getMinimumHeight()) {
height = getMinimumHeight();
}
}
// Not the best place to put this animation, but it works pretty good.
int newHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
if (getLayoutParams().height != 0 && heightMeasureSpec != newHeight) {
final int targetHeight = height;
final int currentHeight = getLayoutParams().height;
final int heightChange = targetHeight - currentHeight;
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime >= 1) {
getLayoutParams().height = targetHeight;
} else {
int stepHeight = (int) (heightChange * interpolatedTime);
getLayoutParams().height = currentHeight + stepHeight;
}
requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mAnimStarted = true;
}
@Override
public void onAnimationEnd(Animation animation) {
mAnimStarted = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
a.setDuration(100);
startAnimation(a);
mAnimStarted = true;
} else {
heightMeasureSpec = newHeight;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
```
==============================
```
wrapContentViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
wrapContentViewPager.measure(wrapContentViewPager.getMeasuredWidth(), wrapContentViewPager.getMeasuredHeight());
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
``` |
32,330,639 | I'm trying to create a custom viewpager inside custom scroll viewthat dynamically wraps the current child's height.
```
package com.example.vihaan.dynamicviewpager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ScrollView;
/**
* Created by vihaan on 1/9/15.
*/
public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev)
&& mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return (Math.abs(distanceY) > Math.abs(distanceX));
}
}
}
```
CustomPager
```
/**
* Created by vihaan on 1/9/15.
*/
public class CustomPager extends ViewPager {
public CustomPager (Context context) {
super(context);
}
public CustomPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
int width = getMeasuredWidth();
int tabHeight = tab.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(tabHeight + fragmentHeight + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
```
MyPagerAdapter
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new FirstFragment());
fragments.add(new SecondFragment());
fragments.add(new ThirdFragment());
fragments.add(new FourthFragment());
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
```
I was hoping that this would wrap around current fragments height but it is only taking the height of first child into consideration.
Sample github project : <https://github.com/VihaanVerma89/DynamicViewPager> | 2015/09/01 | [
"https://Stackoverflow.com/questions/32330639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203565/"
] | Adding to @vihaan's solution, if you have a PagerTitleStrip or PagetTabStrip, you can add this
```
// Account for pagerTitleStrip or pagerTabStrip
View tabStrip = getChildAt(0);
if (tabStrip instanceof PagerTitleStrip) {
tabStrip.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.UNSPECIFIED));
height += tabStrip.getMeasuredHeight();
}
```
just before starting the animation (before the comment
```
// Not the best place to put this animation, but it works pretty good.
```
so that the height of the strip is taken into account. | ```
public class WrapContentViewPager extends ViewPager {
private Boolean mAnimStarted = false;
public WrapContentViewPager(Context context) {
super(context);
}
public WrapContentViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!mAnimStarted && null != getAdapter()) {
int height = 0;
View child = ((CommonViewPagerAdapter) getAdapter()).getItem(getCurrentItem()).getView();
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
height = child.getMeasuredHeight();
if (height < getMinimumHeight()) {
height = getMinimumHeight();
}
}
// Not the best place to put this animation, but it works pretty good.
int newHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
if (getLayoutParams().height != 0 && heightMeasureSpec != newHeight) {
final int targetHeight = height;
final int currentHeight = getLayoutParams().height;
final int heightChange = targetHeight - currentHeight;
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime >= 1) {
getLayoutParams().height = targetHeight;
} else {
int stepHeight = (int) (heightChange * interpolatedTime);
getLayoutParams().height = currentHeight + stepHeight;
}
requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mAnimStarted = true;
}
@Override
public void onAnimationEnd(Animation animation) {
mAnimStarted = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
a.setDuration(100);
startAnimation(a);
mAnimStarted = true;
} else {
heightMeasureSpec = newHeight;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
```
==============================
```
wrapContentViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
wrapContentViewPager.measure(wrapContentViewPager.getMeasuredWidth(), wrapContentViewPager.getMeasuredHeight());
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
``` |
32,330,639 | I'm trying to create a custom viewpager inside custom scroll viewthat dynamically wraps the current child's height.
```
package com.example.vihaan.dynamicviewpager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ScrollView;
/**
* Created by vihaan on 1/9/15.
*/
public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev)
&& mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return (Math.abs(distanceY) > Math.abs(distanceX));
}
}
}
```
CustomPager
```
/**
* Created by vihaan on 1/9/15.
*/
public class CustomPager extends ViewPager {
public CustomPager (Context context) {
super(context);
}
public CustomPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
int width = getMeasuredWidth();
int tabHeight = tab.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(tabHeight + fragmentHeight + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
```
MyPagerAdapter
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new FirstFragment());
fragments.add(new SecondFragment());
fragments.add(new ThirdFragment());
fragments.add(new FourthFragment());
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
```
I was hoping that this would wrap around current fragments height but it is only taking the height of first child into consideration.
Sample github project : <https://github.com/VihaanVerma89/DynamicViewPager> | 2015/09/01 | [
"https://Stackoverflow.com/questions/32330639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203565/"
] | Just in case someone else find this post like me. Worked version without bug of initially zero height:
```
public class DynamicHeightViewPager extends ViewPager {
private View mCurrentView;
public DynamicHeightViewPager(Context context) {
super(context);
}
public DynamicHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mCurrentView != null) {
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int height = Math.max(0, mCurrentView.getMeasuredHeight());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void measureCurrentView(View currentView) {
mCurrentView = currentView;
requestLayout();
}
}
```
And used it in custom FragmentPagerAdapter, like this
```
public abstract class AutoheightFragmentPagerAdapter extends FragmentPagerAdapter {
private int mCurrentPosition = -1;
public AutoheightFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (position != mCurrentPosition && container instanceof DynamicHeightViewPager) {
Fragment fragment = (Fragment) object;
DynamicHeightViewPager pager = (DynamicHeightViewPager) container;
if (fragment != null && fragment.getView() != null) {
mCurrentPosition = position;
pager.measureCurrentView(fragment.getView());
}
}
}
}
``` | ```
public class WrapContentViewPager extends ViewPager {
private Boolean mAnimStarted = false;
public WrapContentViewPager(Context context) {
super(context);
}
public WrapContentViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (!mAnimStarted && null != getAdapter()) {
int height = 0;
View child = ((CommonViewPagerAdapter) getAdapter()).getItem(getCurrentItem()).getView();
if (child != null) {
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
height = child.getMeasuredHeight();
if (height < getMinimumHeight()) {
height = getMinimumHeight();
}
}
// Not the best place to put this animation, but it works pretty good.
int newHeight = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
if (getLayoutParams().height != 0 && heightMeasureSpec != newHeight) {
final int targetHeight = height;
final int currentHeight = getLayoutParams().height;
final int heightChange = targetHeight - currentHeight;
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime >= 1) {
getLayoutParams().height = targetHeight;
} else {
int stepHeight = (int) (heightChange * interpolatedTime);
getLayoutParams().height = currentHeight + stepHeight;
}
requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
mAnimStarted = true;
}
@Override
public void onAnimationEnd(Animation animation) {
mAnimStarted = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
a.setDuration(100);
startAnimation(a);
mAnimStarted = true;
} else {
heightMeasureSpec = newHeight;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
```
==============================
```
wrapContentViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
wrapContentViewPager.measure(wrapContentViewPager.getMeasuredWidth(), wrapContentViewPager.getMeasuredHeight());
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
``` |
32,330,639 | I'm trying to create a custom viewpager inside custom scroll viewthat dynamically wraps the current child's height.
```
package com.example.vihaan.dynamicviewpager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ScrollView;
/**
* Created by vihaan on 1/9/15.
*/
public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev)
&& mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return (Math.abs(distanceY) > Math.abs(distanceX));
}
}
}
```
CustomPager
```
/**
* Created by vihaan on 1/9/15.
*/
public class CustomPager extends ViewPager {
public CustomPager (Context context) {
super(context);
}
public CustomPager (Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
boolean wrapHeight = MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST;
final View tab = getChildAt(0);
int width = getMeasuredWidth();
int tabHeight = tab.getMeasuredHeight();
if (wrapHeight) {
// Keep the current measured width.
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
}
int fragmentHeight = measureFragment(((Fragment) getAdapter().instantiateItem(this, getCurrentItem())).getView());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(tabHeight + fragmentHeight + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public int measureFragment(View view) {
if (view == null)
return 0;
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
```
MyPagerAdapter
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
this.fragments = new ArrayList<Fragment>();
fragments.add(new FirstFragment());
fragments.add(new SecondFragment());
fragments.add(new ThirdFragment());
fragments.add(new FourthFragment());
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
```
I was hoping that this would wrap around current fragments height but it is only taking the height of first child into consideration.
Sample github project : <https://github.com/VihaanVerma89/DynamicViewPager> | 2015/09/01 | [
"https://Stackoverflow.com/questions/32330639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1203565/"
] | Just in case someone else find this post like me. Worked version without bug of initially zero height:
```
public class DynamicHeightViewPager extends ViewPager {
private View mCurrentView;
public DynamicHeightViewPager(Context context) {
super(context);
}
public DynamicHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mCurrentView != null) {
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int height = Math.max(0, mCurrentView.getMeasuredHeight());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void measureCurrentView(View currentView) {
mCurrentView = currentView;
requestLayout();
}
}
```
And used it in custom FragmentPagerAdapter, like this
```
public abstract class AutoheightFragmentPagerAdapter extends FragmentPagerAdapter {
private int mCurrentPosition = -1;
public AutoheightFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (position != mCurrentPosition && container instanceof DynamicHeightViewPager) {
Fragment fragment = (Fragment) object;
DynamicHeightViewPager pager = (DynamicHeightViewPager) container;
if (fragment != null && fragment.getView() != null) {
mCurrentPosition = position;
pager.measureCurrentView(fragment.getView());
}
}
}
}
``` | This few lines of code will solve the problem.
Create a custome widget for viewpager class. and in xml use it for viewpager.
```
public class DynamicHeightViewPager extends ViewPager {
private View mCurrentView;
public DynamicHeightViewPager(Context context) {
super(context);
}
public DynamicHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mCurrentView != null) {
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int height = Math.max(0, mCurrentView.getMeasuredHeight());
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
public void measureCurrentView(View currentView) {
mCurrentView = currentView;
requestLayout();
}
}
```
Then in the view pager adapter override the below method and add the code.
```
@Override
public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
super.setPrimaryItem(container, position, object);
if (container instanceof DynamicHeightViewPager) {
// instead of card view give your root view from your item.xml file.
CardView cardView = (CardView) object;
((DynamicHeightViewPager) container).measureCurrentView(cardView);
}
}
```
Make your view pager height **wrap\_content** inside xml file so you can check the result. |
67,857,366 | I know this question has been asked so many times... but i think i'm doing everything correctly still it's not working, clearInterval doesn't stop the interval, the function is still being called every 1 second.
Here is my full code:
```
const [playerState, setPlayerState] = useState({ playing: true });
let [duration, setDuration] = useState(0);
let counter = null;
let count = () => {
setDuration(++duration);
};
let handlePlay = () => {
setPlayerState({ playing: true });
counter = setInterval(count, 1000); //call count every 1 second, working fine
console.log("playing");
console.log(duration);
};
let handlePause = () => {
setPlayerState({ playing: false });
clearInterval(counter); // doesn't work the function is still being called every 1 second.
console.log("paused");
console.log(duration);
};
```
On calling handePlay the duration should increase by 1 every 1 second that is working fine, after calling handlePause the duration should stop increasing but it's not!
thanks for answering | 2021/06/06 | [
"https://Stackoverflow.com/questions/67857366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11670173/"
] | The problem is that every time your component function gets called to render the component (which is after any series of state changes), a **new** `counter` local variable is created. The one in which you stored the timer handle no longer exists. You have to save the timer handle somewhere you'll be able to use it later (state or a ref, basically). You also need to be sure to have a cleanup callback when your component unmounts that cancels the timer.
See comments:
```
const [playerState, setPlayerState] = useState({ playing: true });
let [duration, setDuration] = useState(0);
// A ref to hold the timer handle
const timerRef = useRef(0);
// Register an unmount callback
useEffect(() => {
// The return value is the clean up callback
return () => {
clearInterval(timerRef.current);
};
}, []); // <== Empty dependency array means callback is called on unmount only
let count = () => {
setDuration(++duration);
};
let handlePlay = () => {
setPlayerState({ playing: true });
// *** Use the ref
clearInterval(timerRef.current);
timerRef.current = setInterval(count, 1000); //call count every 1 second, working fine
console.log("playing");
console.log(duration);
};
let handlePause = () => {
setPlayerState({ playing: false });
// *** Use the ref
clearInterval(timerRef.current);
timerRef.current = 0;
console.log("paused");
console.log(duration);
};
``` | When `handlePlay` is called, it calls `setPlayerState`. This triggers a rerender, which results in a new `counter` with the value `null`. The new `handlePause` has a closure around this value. You can try assigning your counter to state/ref. |
45,028,494 | So I have 1 default publish build definition and I would like to have another one which is in sync with it and does all the same steps but with an additional step at the end.
Can I have another build definition as one of the steps within another build definition?
This question is for Visual Studio Team Services latest. | 2017/07/11 | [
"https://Stackoverflow.com/questions/45028494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2984585/"
] | There are two ways to run another build in your current build.
### Option 1: add PowerShell task in your current build definition to [queue another build by REST API](https://www.visualstudio.com/en-us/docs/integrate/api/build/builds#queue-a-build)
Assume another build id is 5, so you can add PowerShell task with the script:
```
$body = @{
definition = @{
id = 5
}
}
$Uri = "http://account.visualstudio.com/DefaultCollection/project/_apis/build/builds?api-version=2.0"
$buildresponse = Invoke-RestMethod -Method Post -UseDefaultCredentials -ContentType application/json -Uri $Uri -Body (ConvertTo-Json $body)
```
### Option 2: install related extension in Market place
There are some extensions you can install for your VSTS account, then you can add the task to queue another build. such as [Queue Build(s) Task](https://marketplace.visualstudio.com/items?itemName=jb.queue-build), [Trigger New Build](https://marketplace.visualstudio.com/items?itemName=jihedmhadhbi.TriggerNewBuild), [Queue New Build](https://marketplace.visualstudio.com/items?itemName=delegen.DelegenQueueNewBuild) etc. | It appears this is now enabled without an extension through the UI: <https://github.com/MicrosoftDocs/vsts-docs/issues/561> |
54,131,948 | I have two different matplotlib graphs that I would like to switch between upon a button press. The code I have will add the second graph below the first graph when the button is pressed but I want it to replace the first graph. This is a somewhat similar stackoverflow question ([How to update a matplotlib embedded into tkinter?](https://stackoverflow.com/questions/53155949/how-to-update-a-matplotlib-embedded-into-tkinter?rq=1)) but I can't seem to get this to apply to my situation.
The graphs that I have coded, graph\_one and graph\_two, are two simple graphs that I pulled from the matplotlib documentation. In my actual use I have two much more complicated graphs that are very dissimilar, one is a single plot and the other has an additional subplot. Because the graphs I wish to switch back and forth between are so dissimilar it is important to me that the solution be able to handle the graph inputs as separate definitions. It should also be noted that my graphs are embedded in a tkinter widget and it is important that the solution also account for this embedding.
Here is the code I have:
```
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np
from tkinter import *
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
def graph_one():
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='Graph One')
#plt.show()
return fig
def graph_two():
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.cos(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='Graph Two')
#plt.show()
return fig
class matplotlibSwitchGraphs:
def __init__(self, master):
self.master = master
self.frame = Frame(self.master)
self.embed_graph_one()
self.frame.pack(expand=YES, fill=BOTH)
def embed_graph_one(self):
fig = graph_one()
canvas = FigureCanvasTkAgg(fig, self.master)
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
canvas.draw()
canvas.mpl_connect("key_press_event", self.on_key_press)
toolbar = NavigationToolbar2Tk(canvas, self.master)
toolbar.update()
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
self.button = Button(self.master, text="Quit",
command=self._quit)
self.button.pack(side=BOTTOM)
self.button_switch = Button(self.master, text="Switch Graphs",
command=self.switch_graphs)
self.button_switch.pack(side=BOTTOM)
def embed_graph_two(self):
fig = graph_two()
canvas = FigureCanvasTkAgg(fig, self.master)
canvas.draw()
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
canvas.mpl_connect("key_press_event", self.on_key_press)
toolbar = NavigationToolbar2Tk(canvas, self.master)
toolbar.update()
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
self.button = Button(self.master, text="Quit",
command=self._quit)
self.button.pack(side=BOTTOM)
self.button_switch = Button(self.master, text="Switch Graphs",
command=self.switch_graphs)
self.button_switch.pack(side=BOTTOM)
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
def _quit(self):
self.master.quit() # stops mainloop
def switch_graphs(self):
self.embed_graph_two()
def main():
root = Tk()
matplotlibSwitchGraphs(root)
root.mainloop()
if __name__ == '__main__':
main()
```
It seems like I should be able to use a command like
```
ax.clear()
```
in the switch\_graphs def to clear out the first graph but that doesn't work. Any help would be appreciated.
I'm posting updated code to show some small progress I've made as well as to better represent the different nature of the two graphs I wish to switch between. Both graphs are still simple graphs taken directly from the matplotlib documentation but they better represent that one of my graphs is a single plot while the second graph has two plots positioned directly on top of one another.
In my actual case I am trying to use a button to be able to switch between a candlestick chart with a volume overlay and one without the volume overlay. Posting all the code to show the candlestick charts would make for a very long piece of code so I've simplified it by using these simpler graphs. I've also eliminated matplotlib's navigation toolbar for the sake of simplicity. Here is my revised code:
```
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np
from tkinter import *
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
class matplotlibSwitchGraphs:
def __init__(self, master):
self.master = master
self.frame = Frame(self.master)
self.embed_graph_one()
self.frame.pack(expand=YES, fill=BOTH)
# the def creates the first matplotlib graph
def graph_one(self):
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='Graph One')
# plt.show()
return fig, ax
# This def creates the second matplotlib graph that uses subplot
# to place two graphs one on top of the other
def graph_four(self):
x1 = np.linspace(0.0, 5.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig = plt.figure()
ax = plt.subplot2grid((5, 4), (0, 0), rowspan=4, colspan=4)
ax.plot(x1, y1, 'o-')
means_men = (20, 35, 30, 35, 27)
std_men = (2, 3, 4, 1, 2)
ax2 = plt.subplot2grid((5, 4), (4, 0), sharex=ax, rowspan=1,
colspan=4)
ax2.bar(std_men, means_men, color='green', width=0.5,
align='center')
return fig, ax
# this def takes graph one and embeds it in a tkinter widget
def embed_graph_one(self):
fig, ax = self.graph_one()
canvas = FigureCanvasTkAgg(fig, self.master)
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
canvas.draw()
canvas.mpl_connect("key_press_event", self.on_key_press)
self.button = Button(self.master, text="Quit",
command=self._quit)
self.button.pack(side=BOTTOM)
self.button_switch = Button(self.master, text="Switch Graphs",
command=lambda: self.switch_graphs(canvas, fig, ax))
self.button_switch.pack(side=BOTTOM)
# This def takes the second graph and embeds it in a tkinter
# widget
def embed_graph_two(self):
fig, ax = self.graph_two()
canvas = FigureCanvasTkAgg(fig, self.master)
canvas.draw()
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
canvas.mpl_connect("key_press_event", self.on_key_press)
self.button = Button(self.master, text="Quit",
command=self._quit)
self.button.pack(side=BOTTOM)
self.button_switch = Button(self.master, text="Switch Graphs",
command=lambda: self.switch_graphs(canvas, fig, ax))
self.button_switch.pack(side=BOTTOM)
# the def defines the key press event handler
def on_key_press(event):
key_press_handler(event, canvas, toolbar)
# This def quits the tkinter widget
def _quit(self):
self.master.quit() # stops mainloop
# This def switches between the two embedded graphs
def switch_graphs(self, fig, canvas, ax):
ax.clear()
self.embed_graph_two()
canvas.draw()
def main():
root = Tk()
matplotlibSwitchGraphs(root)
root.mainloop()
if __name__ == '__main__':
main()
```
This code still doesn't replace the first graph with second graph but just places the second graph below the first. Any help on getting this code to replace the first graph with the second would be appreciated.
The graphs that I am plotting are an OHLC candlestick chart and an OHLC candlestick chart with a volume overlay. Unfortunately The
```
self.canvas.draw()
```
command in the draw\_graph defs doesn't seem to apply here. When I try to display the graphs all I get is a blank figure. Here is the code I am using that plots the candlestick chart. This would correspond to draw\_graph\_one.
```
def ohlc_daily_date_axis(self, stock_sym):
mondays = WeekdayLocator(MONDAY) # major ticks on the mondays
alldays = DayLocator() # minor ticks on the days
weekFormatter = DateFormatter('%b %d %Y') # e.g., Jan 12 2018
dayFormatter = DateFormatter('%d') # e.g., 12
quotes = get_stock_price_data_list_of_tuples(stock_sym)
graph_header_text = 'Daily OHLC Candlestick Chart: ' + stock_sym + ' Date Range: ' + str(
num2date(quotes[0][0]).date()) + ' - ' + str(num2date(quotes[-1][0]).date())
if len(quotes) == 0:
raise SystemExit
self.fig, self.ax = plt.subplots(figsize=(18, 5))
plt.subplots_adjust(bottom=0.2)
self.ax.xaxis.set_major_locator(mondays)
self.ax.xaxis.set_minor_locator(alldays)
self.ax.xaxis.set_major_formatter(weekFormatter)
# ax.xaxis.set_minor_formatter(dayFormatter)
plt.title(graph_header_text)
self.ax.set_ylabel('Share Price ($)', size=10)
# plot_day_summary(ax, quotes, ticksize=3)
candlestick_ohlc(self.ax, quotes, width=0.6)
self.ax.xaxis_date()
self.ax.autoscale_view()
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
self.ax.format_coord = self.get_ohlc_from_date_xy
# ax.fmt_xdata = get_ohlc_from_date_x
#plt.show()
self.canvas.draw()
```
How would I modify this to get it to show the data? | 2019/01/10 | [
"https://Stackoverflow.com/questions/54131948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7542354/"
] | New answer to include Tk embedding (significant changes from the other answer, so adding new answer instead of editing that one). I moved `graph_one()` and `graph_two()` into the switch graph wrapper class, and renamed them to `draw_graph_one()` and `draw_graph_two()`. Those two new class methods replaced the `embed_graph_one()` and `embed_graph_two()` methods. Most of the content within `embed()` methods were duplicates, and were therefore moved to a `config_window()` method which is called when the class object is instantiated. Created a few class data members to capture the plt variables (e.g. `canvas`, `ax`, `fig`) and created a new data member to keep track of which graph is currently displayed (`graphIndex`) so that we can properly draw the correct graph when `switch_graphs()` is called (instead of calling `embed_graph_two()` every time "switch" is made, as in the original code). Optionally, you can take out `t` from the `draw` methods and make it a class data member (if the values for `t` don't change).
```
import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
import numpy as np
from tkinter import *
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
# Seperated out config of plot to just do it once
def config_plot():
fig, ax = plt.subplots()
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='Graph One')
return (fig, ax)
class matplotlibSwitchGraphs:
def __init__(self, master):
self.master = master
self.frame = Frame(self.master)
self.fig, self.ax = config_plot()
self.graphIndex = 0
self.canvas = FigureCanvasTkAgg(self.fig, self.master)
self.config_window()
self.draw_graph_one()
self.frame.pack(expand=YES, fill=BOTH)
def config_window(self):
self.canvas.mpl_connect("key_press_event", self.on_key_press)
toolbar = NavigationToolbar2Tk(self.canvas, self.master)
toolbar.update()
self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
self.button = Button(self.master, text="Quit", command=self._quit)
self.button.pack(side=BOTTOM)
self.button_switch = Button(self.master, text="Switch Graphs", command=self.switch_graphs)
self.button_switch.pack(side=BOTTOM)
def draw_graph_one(self):
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
self.ax.clear() # clear current axes
self.ax.plot(t, s)
self.ax.set(title='Graph One')
self.canvas.draw()
def draw_graph_two(self):
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.cos(2 * np.pi * t)
self.ax.clear()
self.ax.plot(t, s)
self.ax.set(title='Graph Two')
self.canvas.draw()
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, self.canvas, toolbar)
def _quit(self):
self.master.quit() # stops mainloop
def switch_graphs(self):
# Need to call the correct draw, whether we're on graph one or two
self.graphIndex = (self.graphIndex + 1 ) % 2
if self.graphIndex == 0:
self.draw_graph_one()
else:
self.draw_graph_two()
def main():
root = Tk()
matplotlibSwitchGraphs(root)
root.mainloop()
if __name__ == '__main__':
main()
```
Output (two windows, alternating whenever switch graph button is clicked):
[](https://i.stack.imgur.com/V0LwW.png) | Going off of matplotlib's [documentation on buttons](https://matplotlib.org/gallery/widgets/buttons.html) and the [stackoverflow question you linked](https://stackoverflow.com/questions/53241759/how-to-switch-between-diagrams-with-a-button-in-matplotlib), here is the code that does the basics of what you mean. I'm sorry I didn't use your code, but it was just too big of a code block.
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
# Button handler object
class Index(object):
ind = 0
# This function is called when bswitch is clicked
def switch(self, event):
self.ind = (self.ind+1) % len(functions)
ydata = 1 + functions[self.ind](2 * np.pi * t)
l.set_ydata(ydata)
ax.set(title='Graph '+str(self.ind + 1))
plt.draw()
# This function is called when bquit is clicked
def quit(self, event):
plt.close()
# Store the functions you want to use to plot the two different graphs in a list
functions = [np.sin, np.cos]
# Adjust bottom to make room for Buttons
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
# Get t and s values for Graph 1
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
# Plot Graph 1 and set axes and title
l, = plt.plot(t, s, lw=2)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='Graph 1')
# Initialize Button handler object
callback = Index()
# Connect to a "switch" Button, setting its left, top, width, and height
axswitch = plt.axes([0.40, 0.07, 0.2, 0.05])
bswitch = Button(axswitch, 'Switch graph')
bswitch.on_clicked(callback.switch)
# Connect to a "quit" Button, setting its left, top, width, and height
axquit = plt.axes([0.40, 0.01, 0.2, 0.05])
bquit = Button(axquit, 'Quit')
bquit.on_clicked(callback.quit)
# Show
plt.show()
```
Result:
[](https://i.stack.imgur.com/XdW7K.png)
Click "Switch graph" and you get:
[](https://i.stack.imgur.com/ivMGD.png) |
197,070 | I'm working on a cryptosystem that uses colour pictures as keys for encryption. I'm trying to guess what is the key size of my cryptosystem in order to find the feasibility of a brute force attack. My cryptosystem uses RGB pictures of any size M x N.
The picture is also generated by a chaotic attractor which is sensitive to initial values, so each picture generated is different. These pictures are an example:
[](https://i.stack.imgur.com/HfKhE.png)
I haven't found a paper that tries to do the same calculation yet. Any idea on what the key size is? | 2018/11/05 | [
"https://security.stackexchange.com/questions/197070",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/190594/"
] | A picture is far too large to use as an encryption key directly, you'll want to run it through a [KDF](https://en.wikipedia.org/wiki/Key_derivation_function) first.
It also depends entirely on the picture whether it will have enough entropy to be useful. You could have a 1000x1000 image that's solid white, but it would be useless as a key as it contains no entropy. Pictures from cameras tend to have a fair amount of entropy in the lower bits, so that could be ok, but your users would need to understand that not just any picture is a good key.
Pictures as keys is in general not a great idea. Pictures are usually taken to be shared, and keys are something you don't want to show to everyone. Using a picture as a key also sounds to me like it could be relying on [security through obscurity](https://en.wikipedia.org/wiki/Security_through_obscurity) (i.e. you just use an image from the thousands you have on your computer, but that's effectively very low entropy, probably under 20 bits unless you have an insane number of pictures).
Feel free to continue developing this for the sake of learning, but until you have a much better grasp of cryptography it's better to leave this sort of thing to the experts (see [Why shouldn't we roll our own?](https://security.stackexchange.com/q/18197)). | Any cryptosystem should have keys with keysizes at the 128, 192, and 256 [bit-of-entropy](https://en.wikipedia.org/wiki/Entropy_(computing)) security levels.
So the question comes back to you: where are these images coming from and how much entropy do they contain? If they are completely random bit streams that are being interpreted as an image, then (ignoring entropy loss from lossy compression codecs), you get `log_base2(256x256x256) = 24 bits of entropy per pixel`, so you'd need 6 / 8 / 11 pixels respectively for the 128 / 192 / 256 bit security strengths.
If you're not generating completely random images and instead allowing people to use, like, photos, then I have no idea how you'd even begin estimating the amount of entropy in one of those.
---
**Bottom line:** using images as key material seems like a really odd thing to do and conflicts with the common practice that key material be completely random data from a cryptographic-strength RNG.
Also, from the information in your question, I'm not convinced that brute-force is the attack you need to worry about; I'd be more concerned with the "get access to their laptop and try every image on their hard drive" attack. |
197,070 | I'm working on a cryptosystem that uses colour pictures as keys for encryption. I'm trying to guess what is the key size of my cryptosystem in order to find the feasibility of a brute force attack. My cryptosystem uses RGB pictures of any size M x N.
The picture is also generated by a chaotic attractor which is sensitive to initial values, so each picture generated is different. These pictures are an example:
[](https://i.stack.imgur.com/HfKhE.png)
I haven't found a paper that tries to do the same calculation yet. Any idea on what the key size is? | 2018/11/05 | [
"https://security.stackexchange.com/questions/197070",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/190594/"
] | ***tl;dr*-** You're proposing a [key-stretching algorithm](https://en.wikipedia.org/wiki/Key_stretching) that turns 128 bits of input into a much larger key. This isn't as good as simply using a much larger key of the same size, though it's not *necessarily* as weak as the 128 bits of input. That said, your bitmap looks very ordered, which strongly suggests that it's far weaker than a randomly generated bitmap.
---
According to [@Blender's answer](https://security.stackexchange.com/a/197083/134898), you're just using 128 bits to generate the picture. I'm guessing that you want the picture itself to count as a key larger than the 128 bits that you put into the algorithm that generated it. And it *might*.
Specifically, what you're trying to do is create a [key-stretching algorithm](https://en.wikipedia.org/wiki/Key_stretching) that attempts to stretch 128 bits of input into a much larger key. This isn't necessarily fruitless, but there're things to be aware of:
1. A key-stretching algorithm can be vulnerable to brute-force of the input. For example, even if someone couldn't reverse-engineer the picture-generation algorithm, they could try all $2^{128}$ possible inputs to generate all possible $2^{128}$ possible pictures, then try each. To guard against this, you'd need to ensure that the picture-generation algorithm is too expensive for such an attack to be feasible.
2. Your picture looks far from random at local scales. This is, anyone looking at a few pixels of it can probably guess the neighboring pixels with better-than-random odds of success. This means that the algorithm isn't pseudo-random, even against an attacker who can't reverse-engineer the picture-generation algorithm.
3. Your picture looks far from random at the global scale. This is, the displayed shapes have global geometry, plus the images waste pixels on a well-behaved background. This significantly weakens the pseudo-randomness again, potentially suggesting that it might be easy to fully break.
4. There's no real advantage in a key-stretching algorithm producing a picture as opposed to any other representation of the same data. Granted, the stretched key does look pretty as a picture, but that prettiness merely reflects its weakness vs. a randomly generated bitmap.
[This website](https://www.random.org/bitmaps/) seems to generate random black-and-white bitmaps with specified dimensions. For example, here's a $250 \times 250$-pixel bitmap:
[](https://i.stack.imgur.com/tdj3o.png).
This bitmap is (supposed to be) random in that an attacker looking at any combination of its pixels shouldn't have better-than-even odds of guessing what another pixel might be.
---
### How much entropy?
Unfortunately this site doesn't have MathJax enabled, so it's hard to answer your question directly without it looking weird. Here I'll write a response as-though MathJax were available.
The set of randomly generated RGB images of a given length-and-width contains$${\left(n\_\text{Red} \, n\_\text{Green} \, n\_\text{Blue}\right)}^{n\_\text{width} \, n\_\text{height}} \, \text{members}
\,,$$where:
* $n\_\text{Red}$ is the number of possible values for a pixel's "*red*" dimension;
* $n\_\text{Green}$ is the number of possible values for a pixel's "*green*" dimension;
* $n\_\text{Blue}$ is the number of possible values for a pixel's "*blue*" dimension;
* $n\_\text{width}$ is the number of pixels in the width; and
* $n\_\text{length}$ is the number of pixels in the length.
Then since entropy is the $\log\_2{\left(n\_\text{members}\right)} ,$ this'd be$$
\begin{align}
\left[ \text{entropy} \right]
& ~=~ \log\_2{\left(
{\left( n\_\text{Red} \, n\_\text{Green} \, n\_\text{Blue} \right)}
^{n\_\text{width} \, n\_\text{height}}
\right)} \[5px]
& ~=~ {n\_\text{width} \, n\_\text{height}} \, \log\_2{\left(n\_\text{Red} \, n\_\text{Green} \, n\_\text{Blue}\right)}
\,.\end{align}
$$
In the case of a black-and-white image:
* $n\_\text{Red}=2 ,$ since there're two possible values for the red channel;
* $n\_\text{Green}=n\_\text{Blue}=1 ,$ since the values of the green and blue channels is defined to equal the red channel (such that all pixels are either black or white;
so the entropy'd be$$
\left[ \text{entropy} \right]
~=~ {n\_\text{width} \, n\_\text{height}} \, \log\_2{\left(2 \times 1 \times 1\right)}
~=~ {n\_\text{width} \, n\_\text{height}}
\,.
$$ | So, if you can manage to get past the inital problems involved in too small of keysize and too much loss, and use KDF after, there's a benefit to using these keys for auth after all.
The generation of that stuff must take forever in relation to a traditional hash, so if the initial parameters are treated like a password, password attack times will be slow.
But there's easier ways to get that. `bcrypt()` and friends scale up well. |
197,070 | I'm working on a cryptosystem that uses colour pictures as keys for encryption. I'm trying to guess what is the key size of my cryptosystem in order to find the feasibility of a brute force attack. My cryptosystem uses RGB pictures of any size M x N.
The picture is also generated by a chaotic attractor which is sensitive to initial values, so each picture generated is different. These pictures are an example:
[](https://i.stack.imgur.com/HfKhE.png)
I haven't found a paper that tries to do the same calculation yet. Any idea on what the key size is? | 2018/11/05 | [
"https://security.stackexchange.com/questions/197070",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/190594/"
] | Your most recent edit indicates that your pictures are procedurally-generated, so your key size will therefore be bounded by the amount of state required to generate an image. Yours [seem to be parameterized](https://www.cs.cmu.edu/~kmcrane/Projects/QuaternionJulia/paper.pdf) by four floats for the initial conditions (and fixed output image size, camera location, point light location, convergence conditions, etc).
Those 128-bits of state will then be transformed into an image by an algorithm that depends solely on your provided state, so your image "key" cannot contain more than 128 bits of information. In fact, I think that entire classes of initial values produce identical outputs (e.g. when all four floats are extremely small), so your image "key" size will be strictly less than 128-bits.
There's really no benefit to touching the 128 bits of state by turning it into an image (and then somehow back) if you only reduce the size of the key by doing so. | A picture is far too large to use as an encryption key directly, you'll want to run it through a [KDF](https://en.wikipedia.org/wiki/Key_derivation_function) first.
It also depends entirely on the picture whether it will have enough entropy to be useful. You could have a 1000x1000 image that's solid white, but it would be useless as a key as it contains no entropy. Pictures from cameras tend to have a fair amount of entropy in the lower bits, so that could be ok, but your users would need to understand that not just any picture is a good key.
Pictures as keys is in general not a great idea. Pictures are usually taken to be shared, and keys are something you don't want to show to everyone. Using a picture as a key also sounds to me like it could be relying on [security through obscurity](https://en.wikipedia.org/wiki/Security_through_obscurity) (i.e. you just use an image from the thousands you have on your computer, but that's effectively very low entropy, probably under 20 bits unless you have an insane number of pictures).
Feel free to continue developing this for the sake of learning, but until you have a much better grasp of cryptography it's better to leave this sort of thing to the experts (see [Why shouldn't we roll our own?](https://security.stackexchange.com/q/18197)). |
197,070 | I'm working on a cryptosystem that uses colour pictures as keys for encryption. I'm trying to guess what is the key size of my cryptosystem in order to find the feasibility of a brute force attack. My cryptosystem uses RGB pictures of any size M x N.
The picture is also generated by a chaotic attractor which is sensitive to initial values, so each picture generated is different. These pictures are an example:
[](https://i.stack.imgur.com/HfKhE.png)
I haven't found a paper that tries to do the same calculation yet. Any idea on what the key size is? | 2018/11/05 | [
"https://security.stackexchange.com/questions/197070",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/190594/"
] | A picture is far too large to use as an encryption key directly, you'll want to run it through a [KDF](https://en.wikipedia.org/wiki/Key_derivation_function) first.
It also depends entirely on the picture whether it will have enough entropy to be useful. You could have a 1000x1000 image that's solid white, but it would be useless as a key as it contains no entropy. Pictures from cameras tend to have a fair amount of entropy in the lower bits, so that could be ok, but your users would need to understand that not just any picture is a good key.
Pictures as keys is in general not a great idea. Pictures are usually taken to be shared, and keys are something you don't want to show to everyone. Using a picture as a key also sounds to me like it could be relying on [security through obscurity](https://en.wikipedia.org/wiki/Security_through_obscurity) (i.e. you just use an image from the thousands you have on your computer, but that's effectively very low entropy, probably under 20 bits unless you have an insane number of pictures).
Feel free to continue developing this for the sake of learning, but until you have a much better grasp of cryptography it's better to leave this sort of thing to the experts (see [Why shouldn't we roll our own?](https://security.stackexchange.com/q/18197)). | ***tl;dr*-** You're proposing a [key-stretching algorithm](https://en.wikipedia.org/wiki/Key_stretching) that turns 128 bits of input into a much larger key. This isn't as good as simply using a much larger key of the same size, though it's not *necessarily* as weak as the 128 bits of input. That said, your bitmap looks very ordered, which strongly suggests that it's far weaker than a randomly generated bitmap.
---
According to [@Blender's answer](https://security.stackexchange.com/a/197083/134898), you're just using 128 bits to generate the picture. I'm guessing that you want the picture itself to count as a key larger than the 128 bits that you put into the algorithm that generated it. And it *might*.
Specifically, what you're trying to do is create a [key-stretching algorithm](https://en.wikipedia.org/wiki/Key_stretching) that attempts to stretch 128 bits of input into a much larger key. This isn't necessarily fruitless, but there're things to be aware of:
1. A key-stretching algorithm can be vulnerable to brute-force of the input. For example, even if someone couldn't reverse-engineer the picture-generation algorithm, they could try all $2^{128}$ possible inputs to generate all possible $2^{128}$ possible pictures, then try each. To guard against this, you'd need to ensure that the picture-generation algorithm is too expensive for such an attack to be feasible.
2. Your picture looks far from random at local scales. This is, anyone looking at a few pixels of it can probably guess the neighboring pixels with better-than-random odds of success. This means that the algorithm isn't pseudo-random, even against an attacker who can't reverse-engineer the picture-generation algorithm.
3. Your picture looks far from random at the global scale. This is, the displayed shapes have global geometry, plus the images waste pixels on a well-behaved background. This significantly weakens the pseudo-randomness again, potentially suggesting that it might be easy to fully break.
4. There's no real advantage in a key-stretching algorithm producing a picture as opposed to any other representation of the same data. Granted, the stretched key does look pretty as a picture, but that prettiness merely reflects its weakness vs. a randomly generated bitmap.
[This website](https://www.random.org/bitmaps/) seems to generate random black-and-white bitmaps with specified dimensions. For example, here's a $250 \times 250$-pixel bitmap:
[](https://i.stack.imgur.com/tdj3o.png).
This bitmap is (supposed to be) random in that an attacker looking at any combination of its pixels shouldn't have better-than-even odds of guessing what another pixel might be.
---
### How much entropy?
Unfortunately this site doesn't have MathJax enabled, so it's hard to answer your question directly without it looking weird. Here I'll write a response as-though MathJax were available.
The set of randomly generated RGB images of a given length-and-width contains$${\left(n\_\text{Red} \, n\_\text{Green} \, n\_\text{Blue}\right)}^{n\_\text{width} \, n\_\text{height}} \, \text{members}
\,,$$where:
* $n\_\text{Red}$ is the number of possible values for a pixel's "*red*" dimension;
* $n\_\text{Green}$ is the number of possible values for a pixel's "*green*" dimension;
* $n\_\text{Blue}$ is the number of possible values for a pixel's "*blue*" dimension;
* $n\_\text{width}$ is the number of pixels in the width; and
* $n\_\text{length}$ is the number of pixels in the length.
Then since entropy is the $\log\_2{\left(n\_\text{members}\right)} ,$ this'd be$$
\begin{align}
\left[ \text{entropy} \right]
& ~=~ \log\_2{\left(
{\left( n\_\text{Red} \, n\_\text{Green} \, n\_\text{Blue} \right)}
^{n\_\text{width} \, n\_\text{height}}
\right)} \[5px]
& ~=~ {n\_\text{width} \, n\_\text{height}} \, \log\_2{\left(n\_\text{Red} \, n\_\text{Green} \, n\_\text{Blue}\right)}
\,.\end{align}
$$
In the case of a black-and-white image:
* $n\_\text{Red}=2 ,$ since there're two possible values for the red channel;
* $n\_\text{Green}=n\_\text{Blue}=1 ,$ since the values of the green and blue channels is defined to equal the red channel (such that all pixels are either black or white;
so the entropy'd be$$
\left[ \text{entropy} \right]
~=~ {n\_\text{width} \, n\_\text{height}} \, \log\_2{\left(2 \times 1 \times 1\right)}
~=~ {n\_\text{width} \, n\_\text{height}}
\,.
$$ |
197,070 | I'm working on a cryptosystem that uses colour pictures as keys for encryption. I'm trying to guess what is the key size of my cryptosystem in order to find the feasibility of a brute force attack. My cryptosystem uses RGB pictures of any size M x N.
The picture is also generated by a chaotic attractor which is sensitive to initial values, so each picture generated is different. These pictures are an example:
[](https://i.stack.imgur.com/HfKhE.png)
I haven't found a paper that tries to do the same calculation yet. Any idea on what the key size is? | 2018/11/05 | [
"https://security.stackexchange.com/questions/197070",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/190594/"
] | A picture is far too large to use as an encryption key directly, you'll want to run it through a [KDF](https://en.wikipedia.org/wiki/Key_derivation_function) first.
It also depends entirely on the picture whether it will have enough entropy to be useful. You could have a 1000x1000 image that's solid white, but it would be useless as a key as it contains no entropy. Pictures from cameras tend to have a fair amount of entropy in the lower bits, so that could be ok, but your users would need to understand that not just any picture is a good key.
Pictures as keys is in general not a great idea. Pictures are usually taken to be shared, and keys are something you don't want to show to everyone. Using a picture as a key also sounds to me like it could be relying on [security through obscurity](https://en.wikipedia.org/wiki/Security_through_obscurity) (i.e. you just use an image from the thousands you have on your computer, but that's effectively very low entropy, probably under 20 bits unless you have an insane number of pictures).
Feel free to continue developing this for the sake of learning, but until you have a much better grasp of cryptography it's better to leave this sort of thing to the experts (see [Why shouldn't we roll our own?](https://security.stackexchange.com/q/18197)). | So, if you can manage to get past the inital problems involved in too small of keysize and too much loss, and use KDF after, there's a benefit to using these keys for auth after all.
The generation of that stuff must take forever in relation to a traditional hash, so if the initial parameters are treated like a password, password attack times will be slow.
But there's easier ways to get that. `bcrypt()` and friends scale up well. |
197,070 | I'm working on a cryptosystem that uses colour pictures as keys for encryption. I'm trying to guess what is the key size of my cryptosystem in order to find the feasibility of a brute force attack. My cryptosystem uses RGB pictures of any size M x N.
The picture is also generated by a chaotic attractor which is sensitive to initial values, so each picture generated is different. These pictures are an example:
[](https://i.stack.imgur.com/HfKhE.png)
I haven't found a paper that tries to do the same calculation yet. Any idea on what the key size is? | 2018/11/05 | [
"https://security.stackexchange.com/questions/197070",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/190594/"
] | Your most recent edit indicates that your pictures are procedurally-generated, so your key size will therefore be bounded by the amount of state required to generate an image. Yours [seem to be parameterized](https://www.cs.cmu.edu/~kmcrane/Projects/QuaternionJulia/paper.pdf) by four floats for the initial conditions (and fixed output image size, camera location, point light location, convergence conditions, etc).
Those 128-bits of state will then be transformed into an image by an algorithm that depends solely on your provided state, so your image "key" cannot contain more than 128 bits of information. In fact, I think that entire classes of initial values produce identical outputs (e.g. when all four floats are extremely small), so your image "key" size will be strictly less than 128-bits.
There's really no benefit to touching the 128 bits of state by turning it into an image (and then somehow back) if you only reduce the size of the key by doing so. | I can tell from the images that your key size is significantly less than the size of the images (because otherwise most of them would look like random coloured static).
Your key size is less than or equal to the base 2 logarithm of the total number of different images your chaotic attractor program can generate.\*
That's another way of saying your key size is less than or equal to (probably less than) the amount of bits it takes to specify all of the inputs to your chaotic attractor program.
If you hash the image and use the hash as a crypto key, your key size is equal to or less than the size of the hash.
\*That's your exact key size if your encryption algorithm is something like "XOR each bit of the image with the corresponding bit of the plaintext" (don't use that algorithm for important secrets, BTW, because parts of the message covered by the grey areas in your images could be super easy to decrypt). |
197,070 | I'm working on a cryptosystem that uses colour pictures as keys for encryption. I'm trying to guess what is the key size of my cryptosystem in order to find the feasibility of a brute force attack. My cryptosystem uses RGB pictures of any size M x N.
The picture is also generated by a chaotic attractor which is sensitive to initial values, so each picture generated is different. These pictures are an example:
[](https://i.stack.imgur.com/HfKhE.png)
I haven't found a paper that tries to do the same calculation yet. Any idea on what the key size is? | 2018/11/05 | [
"https://security.stackexchange.com/questions/197070",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/190594/"
] | Your most recent edit indicates that your pictures are procedurally-generated, so your key size will therefore be bounded by the amount of state required to generate an image. Yours [seem to be parameterized](https://www.cs.cmu.edu/~kmcrane/Projects/QuaternionJulia/paper.pdf) by four floats for the initial conditions (and fixed output image size, camera location, point light location, convergence conditions, etc).
Those 128-bits of state will then be transformed into an image by an algorithm that depends solely on your provided state, so your image "key" cannot contain more than 128 bits of information. In fact, I think that entire classes of initial values produce identical outputs (e.g. when all four floats are extremely small), so your image "key" size will be strictly less than 128-bits.
There's really no benefit to touching the 128 bits of state by turning it into an image (and then somehow back) if you only reduce the size of the key by doing so. | ***tl;dr*-** You're proposing a [key-stretching algorithm](https://en.wikipedia.org/wiki/Key_stretching) that turns 128 bits of input into a much larger key. This isn't as good as simply using a much larger key of the same size, though it's not *necessarily* as weak as the 128 bits of input. That said, your bitmap looks very ordered, which strongly suggests that it's far weaker than a randomly generated bitmap.
---
According to [@Blender's answer](https://security.stackexchange.com/a/197083/134898), you're just using 128 bits to generate the picture. I'm guessing that you want the picture itself to count as a key larger than the 128 bits that you put into the algorithm that generated it. And it *might*.
Specifically, what you're trying to do is create a [key-stretching algorithm](https://en.wikipedia.org/wiki/Key_stretching) that attempts to stretch 128 bits of input into a much larger key. This isn't necessarily fruitless, but there're things to be aware of:
1. A key-stretching algorithm can be vulnerable to brute-force of the input. For example, even if someone couldn't reverse-engineer the picture-generation algorithm, they could try all $2^{128}$ possible inputs to generate all possible $2^{128}$ possible pictures, then try each. To guard against this, you'd need to ensure that the picture-generation algorithm is too expensive for such an attack to be feasible.
2. Your picture looks far from random at local scales. This is, anyone looking at a few pixels of it can probably guess the neighboring pixels with better-than-random odds of success. This means that the algorithm isn't pseudo-random, even against an attacker who can't reverse-engineer the picture-generation algorithm.
3. Your picture looks far from random at the global scale. This is, the displayed shapes have global geometry, plus the images waste pixels on a well-behaved background. This significantly weakens the pseudo-randomness again, potentially suggesting that it might be easy to fully break.
4. There's no real advantage in a key-stretching algorithm producing a picture as opposed to any other representation of the same data. Granted, the stretched key does look pretty as a picture, but that prettiness merely reflects its weakness vs. a randomly generated bitmap.
[This website](https://www.random.org/bitmaps/) seems to generate random black-and-white bitmaps with specified dimensions. For example, here's a $250 \times 250$-pixel bitmap:
[](https://i.stack.imgur.com/tdj3o.png).
This bitmap is (supposed to be) random in that an attacker looking at any combination of its pixels shouldn't have better-than-even odds of guessing what another pixel might be.
---
### How much entropy?
Unfortunately this site doesn't have MathJax enabled, so it's hard to answer your question directly without it looking weird. Here I'll write a response as-though MathJax were available.
The set of randomly generated RGB images of a given length-and-width contains$${\left(n\_\text{Red} \, n\_\text{Green} \, n\_\text{Blue}\right)}^{n\_\text{width} \, n\_\text{height}} \, \text{members}
\,,$$where:
* $n\_\text{Red}$ is the number of possible values for a pixel's "*red*" dimension;
* $n\_\text{Green}$ is the number of possible values for a pixel's "*green*" dimension;
* $n\_\text{Blue}$ is the number of possible values for a pixel's "*blue*" dimension;
* $n\_\text{width}$ is the number of pixels in the width; and
* $n\_\text{length}$ is the number of pixels in the length.
Then since entropy is the $\log\_2{\left(n\_\text{members}\right)} ,$ this'd be$$
\begin{align}
\left[ \text{entropy} \right]
& ~=~ \log\_2{\left(
{\left( n\_\text{Red} \, n\_\text{Green} \, n\_\text{Blue} \right)}
^{n\_\text{width} \, n\_\text{height}}
\right)} \[5px]
& ~=~ {n\_\text{width} \, n\_\text{height}} \, \log\_2{\left(n\_\text{Red} \, n\_\text{Green} \, n\_\text{Blue}\right)}
\,.\end{align}
$$
In the case of a black-and-white image:
* $n\_\text{Red}=2 ,$ since there're two possible values for the red channel;
* $n\_\text{Green}=n\_\text{Blue}=1 ,$ since the values of the green and blue channels is defined to equal the red channel (such that all pixels are either black or white;
so the entropy'd be$$
\left[ \text{entropy} \right]
~=~ {n\_\text{width} \, n\_\text{height}} \, \log\_2{\left(2 \times 1 \times 1\right)}
~=~ {n\_\text{width} \, n\_\text{height}}
\,.
$$ |
197,070 | I'm working on a cryptosystem that uses colour pictures as keys for encryption. I'm trying to guess what is the key size of my cryptosystem in order to find the feasibility of a brute force attack. My cryptosystem uses RGB pictures of any size M x N.
The picture is also generated by a chaotic attractor which is sensitive to initial values, so each picture generated is different. These pictures are an example:
[](https://i.stack.imgur.com/HfKhE.png)
I haven't found a paper that tries to do the same calculation yet. Any idea on what the key size is? | 2018/11/05 | [
"https://security.stackexchange.com/questions/197070",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/190594/"
] | Any cryptosystem should have keys with keysizes at the 128, 192, and 256 [bit-of-entropy](https://en.wikipedia.org/wiki/Entropy_(computing)) security levels.
So the question comes back to you: where are these images coming from and how much entropy do they contain? If they are completely random bit streams that are being interpreted as an image, then (ignoring entropy loss from lossy compression codecs), you get `log_base2(256x256x256) = 24 bits of entropy per pixel`, so you'd need 6 / 8 / 11 pixels respectively for the 128 / 192 / 256 bit security strengths.
If you're not generating completely random images and instead allowing people to use, like, photos, then I have no idea how you'd even begin estimating the amount of entropy in one of those.
---
**Bottom line:** using images as key material seems like a really odd thing to do and conflicts with the common practice that key material be completely random data from a cryptographic-strength RNG.
Also, from the information in your question, I'm not convinced that brute-force is the attack you need to worry about; I'd be more concerned with the "get access to their laptop and try every image on their hard drive" attack. | ***tl;dr*-** You're proposing a [key-stretching algorithm](https://en.wikipedia.org/wiki/Key_stretching) that turns 128 bits of input into a much larger key. This isn't as good as simply using a much larger key of the same size, though it's not *necessarily* as weak as the 128 bits of input. That said, your bitmap looks very ordered, which strongly suggests that it's far weaker than a randomly generated bitmap.
---
According to [@Blender's answer](https://security.stackexchange.com/a/197083/134898), you're just using 128 bits to generate the picture. I'm guessing that you want the picture itself to count as a key larger than the 128 bits that you put into the algorithm that generated it. And it *might*.
Specifically, what you're trying to do is create a [key-stretching algorithm](https://en.wikipedia.org/wiki/Key_stretching) that attempts to stretch 128 bits of input into a much larger key. This isn't necessarily fruitless, but there're things to be aware of:
1. A key-stretching algorithm can be vulnerable to brute-force of the input. For example, even if someone couldn't reverse-engineer the picture-generation algorithm, they could try all $2^{128}$ possible inputs to generate all possible $2^{128}$ possible pictures, then try each. To guard against this, you'd need to ensure that the picture-generation algorithm is too expensive for such an attack to be feasible.
2. Your picture looks far from random at local scales. This is, anyone looking at a few pixels of it can probably guess the neighboring pixels with better-than-random odds of success. This means that the algorithm isn't pseudo-random, even against an attacker who can't reverse-engineer the picture-generation algorithm.
3. Your picture looks far from random at the global scale. This is, the displayed shapes have global geometry, plus the images waste pixels on a well-behaved background. This significantly weakens the pseudo-randomness again, potentially suggesting that it might be easy to fully break.
4. There's no real advantage in a key-stretching algorithm producing a picture as opposed to any other representation of the same data. Granted, the stretched key does look pretty as a picture, but that prettiness merely reflects its weakness vs. a randomly generated bitmap.
[This website](https://www.random.org/bitmaps/) seems to generate random black-and-white bitmaps with specified dimensions. For example, here's a $250 \times 250$-pixel bitmap:
[](https://i.stack.imgur.com/tdj3o.png).
This bitmap is (supposed to be) random in that an attacker looking at any combination of its pixels shouldn't have better-than-even odds of guessing what another pixel might be.
---
### How much entropy?
Unfortunately this site doesn't have MathJax enabled, so it's hard to answer your question directly without it looking weird. Here I'll write a response as-though MathJax were available.
The set of randomly generated RGB images of a given length-and-width contains$${\left(n\_\text{Red} \, n\_\text{Green} \, n\_\text{Blue}\right)}^{n\_\text{width} \, n\_\text{height}} \, \text{members}
\,,$$where:
* $n\_\text{Red}$ is the number of possible values for a pixel's "*red*" dimension;
* $n\_\text{Green}$ is the number of possible values for a pixel's "*green*" dimension;
* $n\_\text{Blue}$ is the number of possible values for a pixel's "*blue*" dimension;
* $n\_\text{width}$ is the number of pixels in the width; and
* $n\_\text{length}$ is the number of pixels in the length.
Then since entropy is the $\log\_2{\left(n\_\text{members}\right)} ,$ this'd be$$
\begin{align}
\left[ \text{entropy} \right]
& ~=~ \log\_2{\left(
{\left( n\_\text{Red} \, n\_\text{Green} \, n\_\text{Blue} \right)}
^{n\_\text{width} \, n\_\text{height}}
\right)} \[5px]
& ~=~ {n\_\text{width} \, n\_\text{height}} \, \log\_2{\left(n\_\text{Red} \, n\_\text{Green} \, n\_\text{Blue}\right)}
\,.\end{align}
$$
In the case of a black-and-white image:
* $n\_\text{Red}=2 ,$ since there're two possible values for the red channel;
* $n\_\text{Green}=n\_\text{Blue}=1 ,$ since the values of the green and blue channels is defined to equal the red channel (such that all pixels are either black or white;
so the entropy'd be$$
\left[ \text{entropy} \right]
~=~ {n\_\text{width} \, n\_\text{height}} \, \log\_2{\left(2 \times 1 \times 1\right)}
~=~ {n\_\text{width} \, n\_\text{height}}
\,.
$$ |
197,070 | I'm working on a cryptosystem that uses colour pictures as keys for encryption. I'm trying to guess what is the key size of my cryptosystem in order to find the feasibility of a brute force attack. My cryptosystem uses RGB pictures of any size M x N.
The picture is also generated by a chaotic attractor which is sensitive to initial values, so each picture generated is different. These pictures are an example:
[](https://i.stack.imgur.com/HfKhE.png)
I haven't found a paper that tries to do the same calculation yet. Any idea on what the key size is? | 2018/11/05 | [
"https://security.stackexchange.com/questions/197070",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/190594/"
] | A picture is far too large to use as an encryption key directly, you'll want to run it through a [KDF](https://en.wikipedia.org/wiki/Key_derivation_function) first.
It also depends entirely on the picture whether it will have enough entropy to be useful. You could have a 1000x1000 image that's solid white, but it would be useless as a key as it contains no entropy. Pictures from cameras tend to have a fair amount of entropy in the lower bits, so that could be ok, but your users would need to understand that not just any picture is a good key.
Pictures as keys is in general not a great idea. Pictures are usually taken to be shared, and keys are something you don't want to show to everyone. Using a picture as a key also sounds to me like it could be relying on [security through obscurity](https://en.wikipedia.org/wiki/Security_through_obscurity) (i.e. you just use an image from the thousands you have on your computer, but that's effectively very low entropy, probably under 20 bits unless you have an insane number of pictures).
Feel free to continue developing this for the sake of learning, but until you have a much better grasp of cryptography it's better to leave this sort of thing to the experts (see [Why shouldn't we roll our own?](https://security.stackexchange.com/q/18197)). | I can tell from the images that your key size is significantly less than the size of the images (because otherwise most of them would look like random coloured static).
Your key size is less than or equal to the base 2 logarithm of the total number of different images your chaotic attractor program can generate.\*
That's another way of saying your key size is less than or equal to (probably less than) the amount of bits it takes to specify all of the inputs to your chaotic attractor program.
If you hash the image and use the hash as a crypto key, your key size is equal to or less than the size of the hash.
\*That's your exact key size if your encryption algorithm is something like "XOR each bit of the image with the corresponding bit of the plaintext" (don't use that algorithm for important secrets, BTW, because parts of the message covered by the grey areas in your images could be super easy to decrypt). |
197,070 | I'm working on a cryptosystem that uses colour pictures as keys for encryption. I'm trying to guess what is the key size of my cryptosystem in order to find the feasibility of a brute force attack. My cryptosystem uses RGB pictures of any size M x N.
The picture is also generated by a chaotic attractor which is sensitive to initial values, so each picture generated is different. These pictures are an example:
[](https://i.stack.imgur.com/HfKhE.png)
I haven't found a paper that tries to do the same calculation yet. Any idea on what the key size is? | 2018/11/05 | [
"https://security.stackexchange.com/questions/197070",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/190594/"
] | Your most recent edit indicates that your pictures are procedurally-generated, so your key size will therefore be bounded by the amount of state required to generate an image. Yours [seem to be parameterized](https://www.cs.cmu.edu/~kmcrane/Projects/QuaternionJulia/paper.pdf) by four floats for the initial conditions (and fixed output image size, camera location, point light location, convergence conditions, etc).
Those 128-bits of state will then be transformed into an image by an algorithm that depends solely on your provided state, so your image "key" cannot contain more than 128 bits of information. In fact, I think that entire classes of initial values produce identical outputs (e.g. when all four floats are extremely small), so your image "key" size will be strictly less than 128-bits.
There's really no benefit to touching the 128 bits of state by turning it into an image (and then somehow back) if you only reduce the size of the key by doing so. | Any cryptosystem should have keys with keysizes at the 128, 192, and 256 [bit-of-entropy](https://en.wikipedia.org/wiki/Entropy_(computing)) security levels.
So the question comes back to you: where are these images coming from and how much entropy do they contain? If they are completely random bit streams that are being interpreted as an image, then (ignoring entropy loss from lossy compression codecs), you get `log_base2(256x256x256) = 24 bits of entropy per pixel`, so you'd need 6 / 8 / 11 pixels respectively for the 128 / 192 / 256 bit security strengths.
If you're not generating completely random images and instead allowing people to use, like, photos, then I have no idea how you'd even begin estimating the amount of entropy in one of those.
---
**Bottom line:** using images as key material seems like a really odd thing to do and conflicts with the common practice that key material be completely random data from a cryptographic-strength RNG.
Also, from the information in your question, I'm not convinced that brute-force is the attack you need to worry about; I'd be more concerned with the "get access to their laptop and try every image on their hard drive" attack. |
221,824 | I need to get data from a function as below.
```
GetServiceListData():any
{
var resultData;
pnp.sp.web.lists.getByTitle('Test').items.select('Title,FullName,DOJ,ManagerName/Title').expand('ManagerName').get(asy).then(function(data) {
resultData= data;
});
}
```
This method is calling synchronous in which I am unable to get the data in the first time when trying to call in other function. How we can make a pnp function to call async?
Glad for any help.. | 2017/07/27 | [
"https://sharepoint.stackexchange.com/questions/221824",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/61247/"
] | I have tested it out and was able to do it using CSR and JS Link. Save the below code to say:projectCode.js and upload it to site assets and then refer it in the JS Link of the list view :
```
(function () {
var overrideCurrentContext = {};
overrideCurrentContext.Templates = {};
overrideCurrentContext.Templates.Fields = {
'ProjectCode': { 'View': ProjectCode }
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCurrentContext);
function ProjectCode(ctx) {
var modifiedProjectCode =ctx.CurrentItem.ProjectCode.replace(";", "<br/>");
return modifiedProjectCode
}
})();
```
You can remove the alert and debugger after testing it out. See the below output
Before :
[](https://i.stack.imgur.com/C3Grd.png)
[](https://i.stack.imgur.com/rfz9u.png)
Steps to add JS Link :
* Save the below code to projectCode.js and upload to site assets of site collection/subsite
* Go to the list view and go to the edit page by appending "toolpaneview=2". Edit the webpart and open the 'miscellaneous' section.
* In the JSLink text box refer the JS file. If you have uploaded to the site collection's site assets, use ~sitecollection/siteassets/projectcode.js . If you have uploaded it to subsite's site assets use ~site/siteassets/projectcode.js | You can do it using CSR as well as using javascript. Here i'm giving simple and easy javascript solution.
**Working Javascript solution:**
```
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("table[summary='YourListTitle'] td:nth-child(4)").each(function () {
var choices = $(this).html();
choices = choices.replace(/,/g, "<br/>");
$(this).html(choices);
});
});
</script>
```
1. Add script/content editor webpart on page and add above script.
2. Change summary attribute with your list title & change child number with TD number which contains your column. **(Specify list title same as showing on list view page)**
**Identify exact TD of your column:**
In your list, if check-boxes and title(with edit menu) are coming before your choice column then add two in your column position number. For example If your column position is **2** then its TD number will be **4**. see below screenshot. There are only 2 fields in my list view but my "choices" field contains in 4th TD. So check exact TD position and mention it in script. below is working example on my test site.
[](https://i.stack.imgur.com/3zAkl.png)
**Note:** This solution depends upon position of TD contains column in list view. if you change column position in view then you have to changes TD position in script. |
221,824 | I need to get data from a function as below.
```
GetServiceListData():any
{
var resultData;
pnp.sp.web.lists.getByTitle('Test').items.select('Title,FullName,DOJ,ManagerName/Title').expand('ManagerName').get(asy).then(function(data) {
resultData= data;
});
}
```
This method is calling synchronous in which I am unable to get the data in the first time when trying to call in other function. How we can make a pnp function to call async?
Glad for any help.. | 2017/07/27 | [
"https://sharepoint.stackexchange.com/questions/221824",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/61247/"
] | You can do it using CSR as well as using javascript. Here i'm giving simple and easy javascript solution.
**Working Javascript solution:**
```
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("table[summary='YourListTitle'] td:nth-child(4)").each(function () {
var choices = $(this).html();
choices = choices.replace(/,/g, "<br/>");
$(this).html(choices);
});
});
</script>
```
1. Add script/content editor webpart on page and add above script.
2. Change summary attribute with your list title & change child number with TD number which contains your column. **(Specify list title same as showing on list view page)**
**Identify exact TD of your column:**
In your list, if check-boxes and title(with edit menu) are coming before your choice column then add two in your column position number. For example If your column position is **2** then its TD number will be **4**. see below screenshot. There are only 2 fields in my list view but my "choices" field contains in 4th TD. So check exact TD position and mention it in script. below is working example on my test site.
[](https://i.stack.imgur.com/3zAkl.png)
**Note:** This solution depends upon position of TD contains column in list view. if you change column position in view then you have to changes TD position in script. | Interesting. I had to use both the answers in 1 and 2 above for it to work with SP Online. Possibly because some js files I've used for altering formats must be posted in [master site]/\_catalogs/masterpage/Forms/AllItems.aspx and uploaded as a Javascript Display Template with a specified Target Type (view, form, etc.); Standalone (Override); and Target Scope (form, View/List url) in order to work correctly (see: <https://code.msdn.microsoft.com/office/Client-side-rendering-code-b2eedf92/view/Discussions/3> peterstilgoe's comments). Also had to change from "," to ";" in answer 2 - and add additional functions for 6th, 7th, and 8th nth-child. But very helpful: searched high and low for a way to split multi values in a List/View and this seemed to be the only answer for SPO. A shame that MS doesn't address this natively somehow. |
221,824 | I need to get data from a function as below.
```
GetServiceListData():any
{
var resultData;
pnp.sp.web.lists.getByTitle('Test').items.select('Title,FullName,DOJ,ManagerName/Title').expand('ManagerName').get(asy).then(function(data) {
resultData= data;
});
}
```
This method is calling synchronous in which I am unable to get the data in the first time when trying to call in other function. How we can make a pnp function to call async?
Glad for any help.. | 2017/07/27 | [
"https://sharepoint.stackexchange.com/questions/221824",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/61247/"
] | I have tested it out and was able to do it using CSR and JS Link. Save the below code to say:projectCode.js and upload it to site assets and then refer it in the JS Link of the list view :
```
(function () {
var overrideCurrentContext = {};
overrideCurrentContext.Templates = {};
overrideCurrentContext.Templates.Fields = {
'ProjectCode': { 'View': ProjectCode }
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCurrentContext);
function ProjectCode(ctx) {
var modifiedProjectCode =ctx.CurrentItem.ProjectCode.replace(";", "<br/>");
return modifiedProjectCode
}
})();
```
You can remove the alert and debugger after testing it out. See the below output
Before :
[](https://i.stack.imgur.com/C3Grd.png)
[](https://i.stack.imgur.com/rfz9u.png)
Steps to add JS Link :
* Save the below code to projectCode.js and upload to site assets of site collection/subsite
* Go to the list view and go to the edit page by appending "toolpaneview=2". Edit the webpart and open the 'miscellaneous' section.
* In the JSLink text box refer the JS file. If you have uploaded to the site collection's site assets, use ~sitecollection/siteassets/projectcode.js . If you have uploaded it to subsite's site assets use ~site/siteassets/projectcode.js | You can try CSR concept. It will be applied to the List View Web Part, so you need to following script in all the places where you are using List View Web Part (if you are) otherwise, just follow the below steps.
1. Open the List `All Items` view or the desired view.
2. Now click on gear icon and select `Edit Page`.
3. Now the page will be on edit mode, so you can select the list view web part and bring it to edit mode as well by using `Edit Web Part`.
4. Now expand the `Miscellaneous` section and scroll to bottom of that section.
5. The last property will be `JS Link`. Put the reference to JS file (will generate in a moment) in this property. Kindly note, you cannot put relative site collection/sub site url here. If you host JS file in root web then `~siteCollection/doc_Lib_name/path_to_js_file.js` if it is a sub site use `~site/doc_lib_name/path_to_js_file.js`.
6. Save the web part property, and finally save the page. That's it, you are done here.
**Code for JS File**
Following will be code you need to put in JS file and save it to document library before performing above steps. I'll recommend you to use `Site Assets` library but its completely your choice which document library you pick.
```
var FillCtx = {};
FillCtx.Templates = {};
FillCtx.Templates.Fields = {'ProjectCode':{'View': fillStatus}}
function fillStatus(ctx){
var html ="";
var fieldVal = ctx.CurrentItem['ProjectCode'];
var projectCodes =[];
if(fieldVal.indexOf(';') > 0){
projectCodes = fieldVal.split(';');
}else{
projectCodes.push(fieldVal);
}
for(var i = 0; i < projectCodes.length; i++){
html += projectCodes[i] + "<br/>";
}
return html;
}
ExecuteOrDelayUntilScriptLoaded(SPClientTemplates.TemplateManager.RegisterTemplateOverrides(FillCtx), 'clienttemplates.js');
```
Note: Incase if your field internal name is not `ProjectCode`, replace the ProjectCode keyword used in two places with the internal name. |
221,824 | I need to get data from a function as below.
```
GetServiceListData():any
{
var resultData;
pnp.sp.web.lists.getByTitle('Test').items.select('Title,FullName,DOJ,ManagerName/Title').expand('ManagerName').get(asy).then(function(data) {
resultData= data;
});
}
```
This method is calling synchronous in which I am unable to get the data in the first time when trying to call in other function. How we can make a pnp function to call async?
Glad for any help.. | 2017/07/27 | [
"https://sharepoint.stackexchange.com/questions/221824",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/61247/"
] | I have tested it out and was able to do it using CSR and JS Link. Save the below code to say:projectCode.js and upload it to site assets and then refer it in the JS Link of the list view :
```
(function () {
var overrideCurrentContext = {};
overrideCurrentContext.Templates = {};
overrideCurrentContext.Templates.Fields = {
'ProjectCode': { 'View': ProjectCode }
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCurrentContext);
function ProjectCode(ctx) {
var modifiedProjectCode =ctx.CurrentItem.ProjectCode.replace(";", "<br/>");
return modifiedProjectCode
}
})();
```
You can remove the alert and debugger after testing it out. See the below output
Before :
[](https://i.stack.imgur.com/C3Grd.png)
[](https://i.stack.imgur.com/rfz9u.png)
Steps to add JS Link :
* Save the below code to projectCode.js and upload to site assets of site collection/subsite
* Go to the list view and go to the edit page by appending "toolpaneview=2". Edit the webpart and open the 'miscellaneous' section.
* In the JSLink text box refer the JS file. If you have uploaded to the site collection's site assets, use ~sitecollection/siteassets/projectcode.js . If you have uploaded it to subsite's site assets use ~site/siteassets/projectcode.js | Interesting. I had to use both the answers in 1 and 2 above for it to work with SP Online. Possibly because some js files I've used for altering formats must be posted in [master site]/\_catalogs/masterpage/Forms/AllItems.aspx and uploaded as a Javascript Display Template with a specified Target Type (view, form, etc.); Standalone (Override); and Target Scope (form, View/List url) in order to work correctly (see: <https://code.msdn.microsoft.com/office/Client-side-rendering-code-b2eedf92/view/Discussions/3> peterstilgoe's comments). Also had to change from "," to ";" in answer 2 - and add additional functions for 6th, 7th, and 8th nth-child. But very helpful: searched high and low for a way to split multi values in a List/View and this seemed to be the only answer for SPO. A shame that MS doesn't address this natively somehow. |
221,824 | I need to get data from a function as below.
```
GetServiceListData():any
{
var resultData;
pnp.sp.web.lists.getByTitle('Test').items.select('Title,FullName,DOJ,ManagerName/Title').expand('ManagerName').get(asy).then(function(data) {
resultData= data;
});
}
```
This method is calling synchronous in which I am unable to get the data in the first time when trying to call in other function. How we can make a pnp function to call async?
Glad for any help.. | 2017/07/27 | [
"https://sharepoint.stackexchange.com/questions/221824",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/61247/"
] | You can try CSR concept. It will be applied to the List View Web Part, so you need to following script in all the places where you are using List View Web Part (if you are) otherwise, just follow the below steps.
1. Open the List `All Items` view or the desired view.
2. Now click on gear icon and select `Edit Page`.
3. Now the page will be on edit mode, so you can select the list view web part and bring it to edit mode as well by using `Edit Web Part`.
4. Now expand the `Miscellaneous` section and scroll to bottom of that section.
5. The last property will be `JS Link`. Put the reference to JS file (will generate in a moment) in this property. Kindly note, you cannot put relative site collection/sub site url here. If you host JS file in root web then `~siteCollection/doc_Lib_name/path_to_js_file.js` if it is a sub site use `~site/doc_lib_name/path_to_js_file.js`.
6. Save the web part property, and finally save the page. That's it, you are done here.
**Code for JS File**
Following will be code you need to put in JS file and save it to document library before performing above steps. I'll recommend you to use `Site Assets` library but its completely your choice which document library you pick.
```
var FillCtx = {};
FillCtx.Templates = {};
FillCtx.Templates.Fields = {'ProjectCode':{'View': fillStatus}}
function fillStatus(ctx){
var html ="";
var fieldVal = ctx.CurrentItem['ProjectCode'];
var projectCodes =[];
if(fieldVal.indexOf(';') > 0){
projectCodes = fieldVal.split(';');
}else{
projectCodes.push(fieldVal);
}
for(var i = 0; i < projectCodes.length; i++){
html += projectCodes[i] + "<br/>";
}
return html;
}
ExecuteOrDelayUntilScriptLoaded(SPClientTemplates.TemplateManager.RegisterTemplateOverrides(FillCtx), 'clienttemplates.js');
```
Note: Incase if your field internal name is not `ProjectCode`, replace the ProjectCode keyword used in two places with the internal name. | Interesting. I had to use both the answers in 1 and 2 above for it to work with SP Online. Possibly because some js files I've used for altering formats must be posted in [master site]/\_catalogs/masterpage/Forms/AllItems.aspx and uploaded as a Javascript Display Template with a specified Target Type (view, form, etc.); Standalone (Override); and Target Scope (form, View/List url) in order to work correctly (see: <https://code.msdn.microsoft.com/office/Client-side-rendering-code-b2eedf92/view/Discussions/3> peterstilgoe's comments). Also had to change from "," to ";" in answer 2 - and add additional functions for 6th, 7th, and 8th nth-child. But very helpful: searched high and low for a way to split multi values in a List/View and this seemed to be the only answer for SPO. A shame that MS doesn't address this natively somehow. |
1,467,228 | I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
```
I want the checkbox to be checked when clicking on a `div`, and unchecked if clicked again - a click toggle. | 2009/09/23 | [
"https://Stackoverflow.com/questions/1467228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | This is easily done by flipping the current 'checked' state of the checkbox upon each click. Examples:
```
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.attr('checked'));
});
```
or:
```
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.is(':checked'));
});
```
or, by directly manipulating the DOM 'checked' property (i.e. not using `attr()` to *fetch* the current state of the clicked checkbox):
```
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox[0].checked);
});
```
...and so on.
Note: since jQuery 1.6, checkboxes should be set using `prop` not `attr`:
```
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.prop('checked', !$checkbox[0].checked);
});
``` | Another alternative solution to toggle checkbox value:
```
<div id="parent">
<img src="" class="avatar" />
<input type="checkbox" name="" />
</div>
$("img.avatar").click(function(){
var op = !$(this).parent().find(':checkbox').attr('checked');
$(this).parent().find(':checkbox').attr('checked', op);
});
``` |
1,467,228 | I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
```
I want the checkbox to be checked when clicking on a `div`, and unchecked if clicked again - a click toggle. | 2009/09/23 | [
"https://Stackoverflow.com/questions/1467228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | You could use the [`toggle`](http://docs.jquery.com/Events/toggle) function:
```
$('.offer').toggle(function() {
$(this).find(':checkbox').attr('checked', true);
}, function() {
$(this).find(':checkbox').attr('checked', false);
});
``` | Easiest solution
```
$('.offer').click(function(){
var cc = $(this).attr('checked') == undefined ? false : true;
$(this).find(':checkbox').attr('checked',cc);
});
``` |
1,467,228 | I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
```
I want the checkbox to be checked when clicking on a `div`, and unchecked if clicked again - a click toggle. | 2009/09/23 | [
"https://Stackoverflow.com/questions/1467228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | Warning: using **attr()** or **prop()** to change the state of a checkbox **does not** fire the **change event** in most browsers I've tested with. The checked state will change but no event bubbling. You must trigger the change event manually after setting the checked attribute. I had some other event handlers monitoring the state of checkboxes and they would work fine with direct user clicks. However, setting the checked state programmatically fails to consistently trigger the change event.
jQuery 1.6
```
$('.offer').bind('click', function(){
var $checkbox = $(this).find(':checkbox');
$checkbox[0].checked = !$checkbox[0].checked;
$checkbox.trigger('change'); //<- Works in IE6 - IE9, Chrome, Firefox
});
``` | I have a single checkbox named `chkDueDate` and an HTML object with a click event as follows:
```
$('#chkDueDate').attr('checked', !$('#chkDueDate').is(':checked'));
```
Clicking the HTML object (in this case a `<span>`) toggles the checked property of the checkbox. |
1,467,228 | I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
```
I want the checkbox to be checked when clicking on a `div`, and unchecked if clicked again - a click toggle. | 2009/09/23 | [
"https://Stackoverflow.com/questions/1467228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | Another approach would be to extended jquery like this:
```
$.fn.toggleCheckbox = function() {
this.attr('checked', !this.attr('checked'));
}
```
Then call:
```
$('.offer').find(':checkbox').toggleCheckbox();
``` | try changing this:
```
$(this).find(':checkbox').attr('checked', true );
```
to this:
```
$(this).find(':checkbox').attr('checked', 'checked');
```
Not 100% sure if that will do it, but I seem to recall having a similar problem. Good luck! |
1,467,228 | I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
```
I want the checkbox to be checked when clicking on a `div`, and unchecked if clicked again - a click toggle. | 2009/09/23 | [
"https://Stackoverflow.com/questions/1467228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | Warning: using **attr()** or **prop()** to change the state of a checkbox **does not** fire the **change event** in most browsers I've tested with. The checked state will change but no event bubbling. You must trigger the change event manually after setting the checked attribute. I had some other event handlers monitoring the state of checkboxes and they would work fine with direct user clicks. However, setting the checked state programmatically fails to consistently trigger the change event.
jQuery 1.6
```
$('.offer').bind('click', function(){
var $checkbox = $(this).find(':checkbox');
$checkbox[0].checked = !$checkbox[0].checked;
$checkbox.trigger('change'); //<- Works in IE6 - IE9, Chrome, Firefox
});
``` | Why not in one line?
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', !$(this).find(':checkbox').attr('checked'));
});
``` |
1,467,228 | I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
```
I want the checkbox to be checked when clicking on a `div`, and unchecked if clicked again - a click toggle. | 2009/09/23 | [
"https://Stackoverflow.com/questions/1467228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | You could use the [`toggle`](http://docs.jquery.com/Events/toggle) function:
```
$('.offer').toggle(function() {
$(this).find(':checkbox').attr('checked', true);
}, function() {
$(this).find(':checkbox').attr('checked', false);
});
``` | ```
$('.offer').click(function() {
$(':checkbox', this).each(function() {
this.checked = !this.checked;
});
});
``` |
1,467,228 | I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
```
I want the checkbox to be checked when clicking on a `div`, and unchecked if clicked again - a click toggle. | 2009/09/23 | [
"https://Stackoverflow.com/questions/1467228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | This is easily done by flipping the current 'checked' state of the checkbox upon each click. Examples:
```
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.attr('checked'));
});
```
or:
```
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox.is(':checked'));
});
```
or, by directly manipulating the DOM 'checked' property (i.e. not using `attr()` to *fetch* the current state of the clicked checkbox):
```
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.attr('checked', !$checkbox[0].checked);
});
```
...and so on.
Note: since jQuery 1.6, checkboxes should be set using `prop` not `attr`:
```
$(".offer").on("click", function () {
var $checkbox = $(this).find(':checkbox');
$checkbox.prop('checked', !$checkbox[0].checked);
});
``` | ```
$('.offer').click(function() {
$(':checkbox', this).each(function() {
this.checked = !this.checked;
});
});
``` |
1,467,228 | I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
```
I want the checkbox to be checked when clicking on a `div`, and unchecked if clicked again - a click toggle. | 2009/09/23 | [
"https://Stackoverflow.com/questions/1467228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | Why not in one line?
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', !$(this).find(':checkbox').attr('checked'));
});
``` | ```
<label>
<input
type="checkbox"
onclick="$('input[type=checkbox]').attr('checked', $(this).is(':checked'));"
/>
Check all
</label>
``` |
1,467,228 | I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
```
I want the checkbox to be checked when clicking on a `div`, and unchecked if clicked again - a click toggle. | 2009/09/23 | [
"https://Stackoverflow.com/questions/1467228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | You could use the [`toggle`](http://docs.jquery.com/Events/toggle) function:
```
$('.offer').toggle(function() {
$(this).find(':checkbox').attr('checked', true);
}, function() {
$(this).find(':checkbox').attr('checked', false);
});
``` | Why not in one line?
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', !$(this).find(':checkbox').attr('checked'));
});
``` |
1,467,228 | I've used a hover function where you do x on mouseover and y and mouseout. I'm trying the same for click but it doesn't seem to work:
```
$('.offer').click(function(){
$(this).find(':checkbox').attr('checked', true );
},function(){
$(this).find(':checkbox').attr('checked', false );
});
```
I want the checkbox to be checked when clicking on a `div`, and unchecked if clicked again - a click toggle. | 2009/09/23 | [
"https://Stackoverflow.com/questions/1467228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172637/"
] | Warning: using **attr()** or **prop()** to change the state of a checkbox **does not** fire the **change event** in most browsers I've tested with. The checked state will change but no event bubbling. You must trigger the change event manually after setting the checked attribute. I had some other event handlers monitoring the state of checkboxes and they would work fine with direct user clicks. However, setting the checked state programmatically fails to consistently trigger the change event.
jQuery 1.6
```
$('.offer').bind('click', function(){
var $checkbox = $(this).find(':checkbox');
$checkbox[0].checked = !$checkbox[0].checked;
$checkbox.trigger('change'); //<- Works in IE6 - IE9, Chrome, Firefox
});
``` | ```
<label>
<input
type="checkbox"
onclick="$('input[type=checkbox]').attr('checked', $(this).is(':checked'));"
/>
Check all
</label>
``` |
61,449,900 | Let's say I have a dict that looks like this:
```
d['a']['1'] = 'foo'
d['a']['2'] = 'bar'
d['b']['1'] = 'baz'
d['b']['2'] = 'boo'
```
If I want to get every item where the first key is 'a', I can just do `d['a']` and I will get all of them. However, what if I want to get all items where the second key is '1'? The only way I can think of is to make a second dictionary with a reverse order of the keys, which requires duplicating the contents. Is there a way to do this within a single structure?
Edit: forgot to mention: I want to do this without iterating over everything. I'm going to be dealing with dicts with hundreds of thousands of keys, so I need something scalable. | 2020/04/27 | [
"https://Stackoverflow.com/questions/61449900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4855256/"
] | You're dealing with three dictionaries in this example: One with the values "foo" and "bar", one with the values "baz" and "boo", and an outer dictionary that maps the keys "a" and "b" to those first two inner dictionaries. You can iterate over the keys of both the outer and inner dictionaries with a nested for loop:
```
items = []
for outer_key in d:
for inner_key in d[outer_key]:
if inner_key == "1":
items.append(d[outer_key][inner_key])
break # No need to keep checking keys once you've found a match
```
If you don't care about the keys of the outer dictionary, you can also use `d.values()` to ignore the keys and just see the inner dictionaries, then do a direct membership check on those:
```
items = []
for inner_dict in d.values():
if "1" in inner_dict:
items.append(inner_dict["1"])
```
This can also be written as a list comprehension:
```
items = [inner_dict["1"] for inner_dict in d.values() if "1" in inner_dict]
``` | What you want sounds very similar to a tree-structure which can be implemented as a dictionary-of-dictionaries. Here's a simple implement taken from one of the answers to the question [What is the best way to implement nested dictionaries?](https://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries):
```
class Tree(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
def get_second_level(self, second_key):
found = []
for level2 in self.values():
if second_key in level2:
found.append(level2[second_key])
return found
d = Tree()
d['a']['1'] = 'foo'
d['a']['2'] = 'bar'
d['b']['1'] = 'baz'
d['b']['2'] = 'boo'
d['c']['2'] = 'mox'
d['c']['3'] = 'nix'
print(d) # -> {'a': {'1': 'foo', '2': 'bar'}, 'b': {'1': 'baz', '2': 'boo'},
# 'c': {'2': 'mox', '3': 'nix'}}
print(d['a']) # -> {'1': 'foo', '2': 'bar'}
print(d['a']['1']) # -> foo
print(d['a']['2']) # -> bar
print()
second_key = '1'
found = d.get_second_level(second_key)
print(f'Those with a second key of {second_key!r}') # -> Those with a second key of '1'
print(f' {found}') # -> ['foo', 'baz']
``` |
61,449,900 | Let's say I have a dict that looks like this:
```
d['a']['1'] = 'foo'
d['a']['2'] = 'bar'
d['b']['1'] = 'baz'
d['b']['2'] = 'boo'
```
If I want to get every item where the first key is 'a', I can just do `d['a']` and I will get all of them. However, what if I want to get all items where the second key is '1'? The only way I can think of is to make a second dictionary with a reverse order of the keys, which requires duplicating the contents. Is there a way to do this within a single structure?
Edit: forgot to mention: I want to do this without iterating over everything. I'm going to be dealing with dicts with hundreds of thousands of keys, so I need something scalable. | 2020/04/27 | [
"https://Stackoverflow.com/questions/61449900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4855256/"
] | You're dealing with three dictionaries in this example: One with the values "foo" and "bar", one with the values "baz" and "boo", and an outer dictionary that maps the keys "a" and "b" to those first two inner dictionaries. You can iterate over the keys of both the outer and inner dictionaries with a nested for loop:
```
items = []
for outer_key in d:
for inner_key in d[outer_key]:
if inner_key == "1":
items.append(d[outer_key][inner_key])
break # No need to keep checking keys once you've found a match
```
If you don't care about the keys of the outer dictionary, you can also use `d.values()` to ignore the keys and just see the inner dictionaries, then do a direct membership check on those:
```
items = []
for inner_dict in d.values():
if "1" in inner_dict:
items.append(inner_dict["1"])
```
This can also be written as a list comprehension:
```
items = [inner_dict["1"] for inner_dict in d.values() if "1" in inner_dict]
``` | So after sleeping on it the solution I came up with was to make three dicts, the main one where the data is actually stored and identified by a tuple (`d['a', '1'] = 'foo'`) and the other two are indexes that store all possible values of key B under key A where (A,B) is a valid combination (so `a['a'] = ['1', '2']`, `b['1'] = ['a', 'b']`. I don't entirely like this, since it still requires a hefty storage overhead and doesn't scale efficiently to higher numbers of keys, but it gets the job done without iterating and without duplicating the data. If anyone has a better idea, I'll be happy to hear it. |
55,110,483 | New to regex. How to combine multiple replace like this into a single regex (ie with variables) over all or a range of hex values?
`s.replace(r'\xF1', '\xF1').replace(r'\xE1', '\xE1').replace(r'\xEA', '\xEA')`
where s are strings to be parsed by json.load, eg
`s = 'M : AU : \\xA0MDA:CON'`
Certain fragments containing hex cause sporadic errors:
`{'M': 77,
' ': 32,
':': 58,
'A': 65,
'U': 85,
'\\': 92,
'x': 120,
'0': 48,
'D': 68,
'C': 67,
'O': 79,
'N': 78}`
**EDIT**
Only looking to convert hex values, not all escaped characters as those include control codes which are also problematic for json.loads. | 2019/03/11 | [
"https://Stackoverflow.com/questions/55110483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1472770/"
] | ```
^REF-\w{4}-\w{4}$
```
`^REF` matches the characters REF- literally at start (case sensitive)
`\w{4}` matches any word character exactly 4 times
`\w` equal to `[a-zA-Z0-9_]`, if you don't need to include `_` you can replace it with `[a-zA-Z0-9]`
```
^(REF)-([a-zA-Z0-9]{4})-([a-zA-Z0-9]{4})
``` | What about this?
`REF-([0-9a-zA-Z]{4})-\1` |
55,110,483 | New to regex. How to combine multiple replace like this into a single regex (ie with variables) over all or a range of hex values?
`s.replace(r'\xF1', '\xF1').replace(r'\xE1', '\xE1').replace(r'\xEA', '\xEA')`
where s are strings to be parsed by json.load, eg
`s = 'M : AU : \\xA0MDA:CON'`
Certain fragments containing hex cause sporadic errors:
`{'M': 77,
' ': 32,
':': 58,
'A': 65,
'U': 85,
'\\': 92,
'x': 120,
'0': 48,
'D': 68,
'C': 67,
'O': 79,
'N': 78}`
**EDIT**
Only looking to convert hex values, not all escaped characters as those include control codes which are also problematic for json.loads. | 2019/03/11 | [
"https://Stackoverflow.com/questions/55110483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1472770/"
] | You will want something like this:
```
^REF-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}$
```
you were missing the hyphen and there is no need for the "\*" inside the list | What about this?
`REF-([0-9a-zA-Z]{4})-\1` |
55,110,483 | New to regex. How to combine multiple replace like this into a single regex (ie with variables) over all or a range of hex values?
`s.replace(r'\xF1', '\xF1').replace(r'\xE1', '\xE1').replace(r'\xEA', '\xEA')`
where s are strings to be parsed by json.load, eg
`s = 'M : AU : \\xA0MDA:CON'`
Certain fragments containing hex cause sporadic errors:
`{'M': 77,
' ': 32,
':': 58,
'A': 65,
'U': 85,
'\\': 92,
'x': 120,
'0': 48,
'D': 68,
'C': 67,
'O': 79,
'N': 78}`
**EDIT**
Only looking to convert hex values, not all escaped characters as those include control codes which are also problematic for json.loads. | 2019/03/11 | [
"https://Stackoverflow.com/questions/55110483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1472770/"
] | You will want something like this:
```
^REF-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}$
```
you were missing the hyphen and there is no need for the "\*" inside the list | ```
^REF-\w{4}-\w{4}$
```
`^REF` matches the characters REF- literally at start (case sensitive)
`\w{4}` matches any word character exactly 4 times
`\w` equal to `[a-zA-Z0-9_]`, if you don't need to include `_` you can replace it with `[a-zA-Z0-9]`
```
^(REF)-([a-zA-Z0-9]{4})-([a-zA-Z0-9]{4})
``` |
48,353,778 | in my music app i created listView and fetched songs from sd card.everything is perfect but when when i click on listItem songs doesnt play.it doesnt give any response.i m lost.please give me some idea how to fix this problem.its been long i m finding solution for this.i looked every single line of code but coudnt find mistake.please help.
```
public class BlankFragment2 extends Fragment {
private ArrayList<songInfo> _songs = new ArrayList<songInfo>();
RecyclerView recyclerView;
SeekBar seekBar;
Button play;
public songAdapter songAdapter1;
protected ImageView album_art;
MediaPlayer mediaPlayer;
private Handler myHandler = new Handler();
public Cursor cursor;
View rootView;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private BlankFragment.OnFragmentInteractionListener mListener;
public BlankFragment2() {
// Required empty public constructor/
}
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView= inflater.inflate(R.layout.fragment_blank_fragment2, container, false);
recyclerView = rootView. findViewById(R.id.recyclerView);
seekBar = rootView.findViewById(R.id.seekBar);
album_art = rootView.findViewById(R.id.albumArt);
songAdapter1 = new songAdapter(getActivity(),_songs);
recyclerView.setAdapter(songAdapter1);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
linearLayoutManager.getOrientation());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
songAdapter1.setOnItemClickListener(new songAdapter.OnItemClickListener() {
@Override
public void onItemClick(RecyclerView.ViewHolder holder, View view, final songInfo obj, int position) {
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}else {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(obj.getSongUrl());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
Log.d("Prog", "run: " + mediaPlayer.getDuration());
}
});
}catch (Exception e){}
}
};
myHandler.postDelayed(runnable,100);
}
}
});
checkUserPermission();
Thread t = new runThread();
t.start();
return rootView;
}
public class runThread extends Thread {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("Runwa", "run: " + 1);
if (mediaPlayer != null) {
seekBar.post(new Runnable() {
@Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
});
Log.d("Runwa", "run: " + mediaPlayer.getCurrentPosition());
}
}
}
}
private void checkUserPermission(){
if(Build.VERSION.SDK_INT>=23){
if(ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},123);
return;
}
}
loadSongs();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 123:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
loadSongs();
}else{
Toast.makeText(getContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
checkUserPermission();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void loadSongs() {
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
cursor = getContext().getContentResolver().query(uri, null, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
String id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
songInfo s = new songInfo(name, artist, url,id);
_songs.add(s);
}
while (cursor.moveToNext());
cursor.close();
recyclerView.setAdapter(songAdapter1);
}
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (BlankFragment.OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
songAdapter
public class songAdapter extends RecyclerView.Adapter<songAdapter.SongHolder>{
private ArrayList<songInfo> _songs = new ArrayList<>();
private Context context;
MediaMetadataRetriever metaRetriver;
byte[] art;
private OnItemClickListener mOnItemClickListener;
public songAdapter(Context context, ArrayList<songInfo> songs) {
this.context = context;
this._songs = songs;
}
public interface OnItemClickListener {
void onItemClick(RecyclerView.ViewHolder holder, View view, songInfo obj, int position);
// void onItemClick(Button b, View view, songInfo obj, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
@Override
public SongHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View myView = LayoutInflater.from(context).inflate(R.layout.card,viewGroup,false);
return new SongHolder(myView);
}
@Override
public void onBindViewHolder(final SongHolder songHolder, final int i) {
final songInfo s = _songs.get(i);
metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource(_songs.get(i).getId());
try {
art = metaRetriver.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
songHolder.album_art.setImageBitmap(songImage);
} catch (Exception e) {
songHolder.album_art.setBackgroundColor(Color.GRAY);
}
songHolder.tvSongName.setText(_songs.get(i).getSongName());
songHolder.tvSongArtist.setText(_songs.get(i).getArtistName());
setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(RecyclerView.ViewHolder holder, View view, songInfo obj, int position) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(songHolder, view, s, i);
}
}
});
}
@Override
public int getItemCount() {
return _songs.size();
}
public class SongHolder extends RecyclerView.ViewHolder {
TextView tvSongName,tvSongArtist;
ImageView album_art;
Button play;
public SongHolder(View itemView) {
super(itemView);
play=(Button)itemView.findViewById(R.id.play);
tvSongName = (TextView) itemView.findViewById(R.id.songName);
tvSongArtist = (TextView) itemView.findViewById(R.id.artistName);
album_art = (ImageView) itemView.findViewById(R.id.albumArt);
}
}
}
``` | 2018/01/20 | [
"https://Stackoverflow.com/questions/48353778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9220213/"
] | A real time command pipe for redis.log. (you can call `bgsave` to test it.)
```
package main
import (
"os"
"os/exec"
"fmt"
"bufio"
)
func main() {
cmd := exec.Command("tail", "-f", "/usr/local/var/log/redis.log")
// create a pipe for the output of the script
cmdReader, err := cmd.StdoutPipe()
if err != nil {
fmt.Fprintln(os.Stderr, "Error creating StdoutPipe for Cmd", err)
return
}
scanner := bufio.NewScanner(cmdReader)
go func() {
for scanner.Scan() {
fmt.Printf("\t > %s\n", scanner.Text())
}
}()
err = cmd.Start()
if err != nil {
fmt.Fprintln(os.Stderr, "Error starting Cmd", err)
return
}
err = cmd.Wait()
if err != nil {
fmt.Fprintln(os.Stderr, "Error waiting for Cmd", err)
return
}
}
``` | I haven't found a solution to your problem, but I have found something strange.
I wrote three versions of a program that repeatingly output a short string with one second interval, one in Python, one in C, and one in Go:
talker.py
---------
```
import time
while True:
print("Now!")
time.sleep(1)
```
talker.c
--------
```
#include <unistd.h>
main() {
for(;;) {
write(1, "Now!\n", 5);
sleep(1);
}
}
```
talker.go
---------
```
package main
import (
"fmt"
"time"
)
func main() {
for {
fmt.Println("Now!")
time.Sleep(time.Second)
}
}
```
When I run them by themselves (e.g. `python ./talker.py`) they seem to work exactly the same. But when I pipe the output to `cat` I see a difference; the C and Go version gets their output through to the screen immediately, but not so the Python version. Its output gets buffered and doesn't show up on screen until enough data has been collected.
I even tried with a simple Go version of `cat`, and that doesn't change the behaviour:
```
package main
import (
"io"
"os"
)
func main() {
io.Copy(os.Stdout, os.Stdin)
}
``` |
13,774,909 | i am designing one drop down list with css
Here is my html code:

>
> i have set each `li a` property border-right to `border-right:1px dashed silver`; i want to delete that property for last `li a` element
>
>
>
and here is css code :
```
#navigation
{
display:inline-table;
text-align:center;
background:silver;
}
#navigation li
{
float:left;
list-style:none;
padding:2px 10px 2px 10px;
}
#navigation a
{
display:block;
text-decoration:none;
color:green;
font-weight:bold;
padding:5px;
border-right:1px dashed green;
}
.noBorder
{
display:block;
text-decoration:none;
color:red;
font-weight:bold;
padding:5px;
border:0px;
}
#navigation a:hover
{
color:yellow;
background:black;
}
```
i want to delete right-border of the last list `software Developments` so i tried with
`noBorder` class. but can't give any solution please can any one let me know
thanks advance | 2012/12/08 | [
"https://Stackoverflow.com/questions/13774909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1537107/"
] | you can do this by
```
border: none !important;
```
it will remove all border
to remove right border ony try
```
border-right: none !important;
```
**Good Read**
[**Is !important bad for performance?**](https://stackoverflow.com/questions/13743671/is-important-bad-for-performance/13745254) | ```
#navigation {
display: inline - table;
text - align: center;
background: silver;
}
#navigationli {
float: left;
list - style: none;
padding: 2px 10px 2px 10px;
}
#navigationa {
display: block;
text - decoration: none;
color: green;
font - weight: bold;
padding: 5px;
border - right: 1px dashed green;
}
.noBorder {
display: block;
text - decoration: none;
color: red;
font - weight: bold;
padding: 5px;
border: 0px;
}
#navigationa: hover {
color: yellow;
background: black;
}
``` |
13,774,909 | i am designing one drop down list with css
Here is my html code:

>
> i have set each `li a` property border-right to `border-right:1px dashed silver`; i want to delete that property for last `li a` element
>
>
>
and here is css code :
```
#navigation
{
display:inline-table;
text-align:center;
background:silver;
}
#navigation li
{
float:left;
list-style:none;
padding:2px 10px 2px 10px;
}
#navigation a
{
display:block;
text-decoration:none;
color:green;
font-weight:bold;
padding:5px;
border-right:1px dashed green;
}
.noBorder
{
display:block;
text-decoration:none;
color:red;
font-weight:bold;
padding:5px;
border:0px;
}
#navigation a:hover
{
color:yellow;
background:black;
}
```
i want to delete right-border of the last list `software Developments` so i tried with
`noBorder` class. but can't give any solution please can any one let me know
thanks advance | 2012/12/08 | [
"https://Stackoverflow.com/questions/13774909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1537107/"
] | Am not sure which border are you talking about but try this if you want to remove the border from last `li`
```
.noBorder {
border-right: none !important;
}
``` | ```
#navigation {
display: inline - table;
text - align: center;
background: silver;
}
#navigationli {
float: left;
list - style: none;
padding: 2px 10px 2px 10px;
}
#navigationa {
display: block;
text - decoration: none;
color: green;
font - weight: bold;
padding: 5px;
border - right: 1px dashed green;
}
.noBorder {
display: block;
text - decoration: none;
color: red;
font - weight: bold;
padding: 5px;
border: 0px;
}
#navigationa: hover {
color: yellow;
background: black;
}
``` |
13,774,909 | i am designing one drop down list with css
Here is my html code:

>
> i have set each `li a` property border-right to `border-right:1px dashed silver`; i want to delete that property for last `li a` element
>
>
>
and here is css code :
```
#navigation
{
display:inline-table;
text-align:center;
background:silver;
}
#navigation li
{
float:left;
list-style:none;
padding:2px 10px 2px 10px;
}
#navigation a
{
display:block;
text-decoration:none;
color:green;
font-weight:bold;
padding:5px;
border-right:1px dashed green;
}
.noBorder
{
display:block;
text-decoration:none;
color:red;
font-weight:bold;
padding:5px;
border:0px;
}
#navigation a:hover
{
color:yellow;
background:black;
}
```
i want to delete right-border of the last list `software Developments` so i tried with
`noBorder` class. but can't give any solution please can any one let me know
thanks advance | 2012/12/08 | [
"https://Stackoverflow.com/questions/13774909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1537107/"
] | Try this, it will work
```
.noBorder
{
border-right:0px!important;
}
``` | ```
#navigation {
display: inline - table;
text - align: center;
background: silver;
}
#navigationli {
float: left;
list - style: none;
padding: 2px 10px 2px 10px;
}
#navigationa {
display: block;
text - decoration: none;
color: green;
font - weight: bold;
padding: 5px;
border - right: 1px dashed green;
}
.noBorder {
display: block;
text - decoration: none;
color: red;
font - weight: bold;
padding: 5px;
border: 0px;
}
#navigationa: hover {
color: yellow;
background: black;
}
``` |
13,774,909 | i am designing one drop down list with css
Here is my html code:

>
> i have set each `li a` property border-right to `border-right:1px dashed silver`; i want to delete that property for last `li a` element
>
>
>
and here is css code :
```
#navigation
{
display:inline-table;
text-align:center;
background:silver;
}
#navigation li
{
float:left;
list-style:none;
padding:2px 10px 2px 10px;
}
#navigation a
{
display:block;
text-decoration:none;
color:green;
font-weight:bold;
padding:5px;
border-right:1px dashed green;
}
.noBorder
{
display:block;
text-decoration:none;
color:red;
font-weight:bold;
padding:5px;
border:0px;
}
#navigation a:hover
{
color:yellow;
background:black;
}
```
i want to delete right-border of the last list `software Developments` so i tried with
`noBorder` class. but can't give any solution please can any one let me know
thanks advance | 2012/12/08 | [
"https://Stackoverflow.com/questions/13774909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1537107/"
] | Am not sure which border are you talking about but try this if you want to remove the border from last `li`
```
.noBorder {
border-right: none !important;
}
``` | you can do this by
```
border: none !important;
```
it will remove all border
to remove right border ony try
```
border-right: none !important;
```
**Good Read**
[**Is !important bad for performance?**](https://stackoverflow.com/questions/13743671/is-important-bad-for-performance/13745254) |
13,774,909 | i am designing one drop down list with css
Here is my html code:

>
> i have set each `li a` property border-right to `border-right:1px dashed silver`; i want to delete that property for last `li a` element
>
>
>
and here is css code :
```
#navigation
{
display:inline-table;
text-align:center;
background:silver;
}
#navigation li
{
float:left;
list-style:none;
padding:2px 10px 2px 10px;
}
#navigation a
{
display:block;
text-decoration:none;
color:green;
font-weight:bold;
padding:5px;
border-right:1px dashed green;
}
.noBorder
{
display:block;
text-decoration:none;
color:red;
font-weight:bold;
padding:5px;
border:0px;
}
#navigation a:hover
{
color:yellow;
background:black;
}
```
i want to delete right-border of the last list `software Developments` so i tried with
`noBorder` class. but can't give any solution please can any one let me know
thanks advance | 2012/12/08 | [
"https://Stackoverflow.com/questions/13774909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1537107/"
] | Am not sure which border are you talking about but try this if you want to remove the border from last `li`
```
.noBorder {
border-right: none !important;
}
``` | Try this, it will work
```
.noBorder
{
border-right:0px!important;
}
``` |
6,719,946 | I am currently trying to declare a public string within a while loop, as I would like to use it (the string) in other methods
The string in question is "s"
```
private void CheckLog()
{
bool _found;
while (true)
{
_found = false;
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
_found = true;
break;
}
}
}
}
}
``` | 2011/07/16 | [
"https://Stackoverflow.com/questions/6719946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/848081/"
] | you can't declare `public` string inside the method.
Try this:
```
string s = "";
private void CheckLog()
{
bool _found;
while (true)
{
_found = false;
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
//s = "VALUE";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
_found = true;
break;
}
}
}
}
}
``` | You should create a global variable and assign that instead for example
```
public class MyClass
{
public string s;
private void CheckLog() { ... }
}
```
In any method you might use it remember to check if `s.IsNullOrEmpty()` to avoid getting a NullPointerException (also I'm assuming that the string should contain something). |
6,719,946 | I am currently trying to declare a public string within a while loop, as I would like to use it (the string) in other methods
The string in question is "s"
```
private void CheckLog()
{
bool _found;
while (true)
{
_found = false;
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
_found = true;
break;
}
}
}
}
}
``` | 2011/07/16 | [
"https://Stackoverflow.com/questions/6719946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/848081/"
] | you can't declare `public` string inside the method.
Try this:
```
string s = "";
private void CheckLog()
{
bool _found;
while (true)
{
_found = false;
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
//s = "VALUE";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
_found = true;
break;
}
}
}
}
}
``` | Better pass the string as by-ref argument to function, or return it from the function. Declaring it as member doesn't seem to be a good idea.
```
public string CheckLog(){}
``` |
30,463 | So I've created this planet that's about 90% the size of Earth, orbits a binary yellow dwarf star and has an extremely electrified atmosphere. Cloud plumes coming from volcanoes contain various conducting compounds, resulting in huge lightning storms which occur almost every night globally.
This planet's equivalent to plants - phytids - use the electricity in much the same way that our own plants use light, in a process called electrosynthesis. My question is: what sort of biology would these phytids have that could allow them to convert electricity into energy for growth and reproduction?
They have long, rigid spires made mostly of copper-based proteins which face upwards into the air to conduct this electrical energy into their bodies, but that's about all I know. What would they need to do with the electricity once it was inside of them? | 2015/11/25 | [
"https://worldbuilding.stackexchange.com/questions/30463",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/15567/"
] | Why would you 'produce energy' from electricity? IT IS ENERGY. Likely they would utilize as much as possible in it's native form. The human body uses electric impulses all to pass information back and forth throughout the body.
Adding in capacitors to hold this energy would be fairly important, it would be kind of like the fat cells in animals or sugars in plants. So plants and animals need energy to grow (and move). The growing is generally all chemical changes powered by chemical reactions from chemical energy sources. [Electrochemistry](https://en.wikipedia.org/wiki/Electrochemistry) would be huge in this planet.
I think a lot more plants and animals would be utilizing aluminum in their make up since with all the 'free' electricity it can be separated much easier from it compounds. 'Diets' of plants and animals might be significantly different when you can use electricity to break bonds instead of a chemical (acid) or physical (teeth or crop) to break things down to be useful for building ones own body.
Water can be broken down into Hydrogen and Oxygen with electricity and maybe some plants will store the two gases instead of a capacitor or in conjunction with them? | The Asian Hornet converts sunlight into electricity, then appears to use it directly:
```
The sunlight that these hornets capture is likely converted into electrical
energy. There exists a voltage between the inner and outer layers of the
yellow stripe that increases in response to illumination. The harvested
energy may be used in physical activity (digging or flight) and temperature
regulation. It even seems to provide enough energy to carry out metabolic
functions similar to the liver (producing or filtering enzymes and sugars).
The enzymatic activity in these regions has been shown to decrease when the
hornet is exposed to light, allowing it to conserve its energy.
```
[Photovoltaic Asian Hornet](https://asknature.org/strategy/photovoltaic-pigments-harvest-solar-energy/#.WjVuBFWnFaQ)
While the Asian Hornet is unique, it doesn't seem to need any exotic materials to make use of the electricity, though I believe the process is not completely understood.
Since the hornet can use the electricity to produce sugars, I imagine similar organisms might get by with a sugar reserve to consume when electrical energy sources are scarce. |
50,874,400 | I am using node.js,express and postgres db for my project. I have few queries in async function which I am not able to execute in a sequence. sample code for reference.
```
for(let i=0;i<person_size;i++)
{
var check_person_query="select per_id_pk from person_tbl where per_fname='"+person_fname[i]+"' and per_lname='"+person_lname[i]+"'";
dbClient.query(check_person_query,function(err,result){
if(result.rows.length>0)
{
console.log("Call: 1.1");
console.log("person already exists");
}
else
{
var insert_person_query = "insert into person_tbl (per_fname,per_lname,per_gender,profile_photo) values('"+person_fname[i]+"','"+person_lname[i]+"','"+person_gender[i]+"','profile_photo_link')";
//console.log("query2: "+insert_person_query);
dbClient.query(insert_person_query,function(err,result){
if (err) throw err;
console.log("Call: 1.2");
console.log("New person has been added");
});
var fullname = person_fname[i].concat(person_lname[i]);
low_fullname = fullname.toLowerCase();
person_pic[i].mv("/home/aniket/content_info/images/"+low_fullname+".jpg", function(err){
if (err) throw err;
});
}
});
}//end for
```
In above code, when if condition fails, the else part gets executed in the very end of my async.series function. As long as if condition succeeds, everything works perfectly in sequential manner. How to sequentially run nested db queries? I have used async.waterfall but still no expected output.
UPDATE: (SOLVED)
Instead of using nested query functions, I removed the nesting, and prepared a single query so that I would obtain an expected result and maintain the execution sequence. | 2018/06/15 | [
"https://Stackoverflow.com/questions/50874400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5142959/"
] | Yes, it's definitely possible:
```
## create matrix
#set($matrix = [
['A','B',0,'hello',0,0],
['C','D',0.56,'there',0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0],
[0,0,0,0,0,0] ])
## display a cell
$matrix[0][3]
## change some cells
## (warning, indices are zero-based)
#set($matrix[2][3] = 'how are you?')
## display whole matrix in line
$matrix
``` | ##You can use that, i try a 2D array but i can do it, i find this solution
#set ( $test= { "mytest": [[], []]
} )
#set($dummy = $test.get('mytest').get(0).add('hello'))
#set($dummy = $test.get('mytest').get(1).add('World'))
$test.get('mytest').get(0).get(0) ## hello
$test.get('mytest').get(1).get(0) ## world |
33,328,187 | I am relatively new at this and have been racking my brain attempting to get my program to work properly and it just won't. I am working in Visual Studio 2012 C# on a Forms Application.
I need it to produce a distinct error message when the user input value is more than `0` but less than `10,000`. It also must produce a distinct error message when the user enters a non-numeric value and a distinct error message when the user fails to enter any value at all.
The code I've written so far produces a distinct error message when the user enters a non-numeric value or when they fail to enter any value at all, but it does not trigger an error message when the user enters a value that is below or over the required range.
It is as if the compiler is ignoring the code I've written for the first exception/overflow exception and only recognizing the code for the second and final exception. My code has no coding errors. It appears that my problem is in the logic.
Please help me if you can. My code is below thanks!
```
private void btnCalculate_Click(object sender, System.EventArgs e)
{
try
{
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
decimal discountPercent = .25m;
decimal discountAmount = subtotal * discountPercent;
decimal invoiceTotal = subtotal - discountAmount;
lblDiscountPercent.Text = discountPercent.ToString("p1");
lblDiscountAmount.Text = discountAmount.ToString("c");
lblTotal.Text = invoiceTotal.ToString("c");
}
}
catch (OverflowException)
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
if (subtotal <= 0)
{
MessageBox.Show("Subtotal must be greater than $0.00. ", "Error Entry");
txtSubtotal.Focus();
}
if (subtotal >= 10000)
{
MessageBox.Show("Subtotal must be less than $10000.00. ", "Error Entry");
txtSubtotal.Focus();
}
}
catch (Exception)
{
if (txtSubtotal.Text == "")
{
MessageBox.Show("Subtotal is a required field. ", "Error Entry");
}
else
{
MessageBox.Show(
"Please enter a valid Number for the subtotal field.", "Error Entry");
txtSubtotal.Focus();
}
}
}
private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void txtSubtotal_TextChanged(object sender, EventArgs e)
{
}
}
```
} | 2015/10/25 | [
"https://Stackoverflow.com/questions/33328187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3473475/"
] | As I already mentioned in comment you should consider moving your code out of catch block.
In this case you should think of creating a simple method which will validate your input and produces output message.
An example is for you:
```
private bool IsPageValid()
{
string errorMessage = string.Empty;
bool isValid = true;
if (subtotal <= 0)
{
errorMessage+="<li>"+"<b>Subtotal must be greater than $0.00. ", "Error Entry"+ "</b><br/>";
txtSubtotal.Focus();
isValid=false;
}
}
```
>
> ***Likewise write other clause of validations in this function.***.This will validate each of your condition and if fails it would make the isValid false thus not allowing users to submit.
>
>
>
Now you should call this function in your button click.
```
protected void btnSubmit_Click(object sender, EventArgs e)
{
ClearMessage();
if (IsPageValid().Equals(true))
{
// allow next action to happen.
}
}
``` | Code should look like this
```
try {
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
try {
if(x<0 || x>10000){
throw new OverFlowException("");
}
//Do what ever you want
}
catch(Exception ex){
// catch overflow
}
}
catch(Exception ex){
// catch nonnumeric value
}
``` |
33,328,187 | I am relatively new at this and have been racking my brain attempting to get my program to work properly and it just won't. I am working in Visual Studio 2012 C# on a Forms Application.
I need it to produce a distinct error message when the user input value is more than `0` but less than `10,000`. It also must produce a distinct error message when the user enters a non-numeric value and a distinct error message when the user fails to enter any value at all.
The code I've written so far produces a distinct error message when the user enters a non-numeric value or when they fail to enter any value at all, but it does not trigger an error message when the user enters a value that is below or over the required range.
It is as if the compiler is ignoring the code I've written for the first exception/overflow exception and only recognizing the code for the second and final exception. My code has no coding errors. It appears that my problem is in the logic.
Please help me if you can. My code is below thanks!
```
private void btnCalculate_Click(object sender, System.EventArgs e)
{
try
{
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
decimal discountPercent = .25m;
decimal discountAmount = subtotal * discountPercent;
decimal invoiceTotal = subtotal - discountAmount;
lblDiscountPercent.Text = discountPercent.ToString("p1");
lblDiscountAmount.Text = discountAmount.ToString("c");
lblTotal.Text = invoiceTotal.ToString("c");
}
}
catch (OverflowException)
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
if (subtotal <= 0)
{
MessageBox.Show("Subtotal must be greater than $0.00. ", "Error Entry");
txtSubtotal.Focus();
}
if (subtotal >= 10000)
{
MessageBox.Show("Subtotal must be less than $10000.00. ", "Error Entry");
txtSubtotal.Focus();
}
}
catch (Exception)
{
if (txtSubtotal.Text == "")
{
MessageBox.Show("Subtotal is a required field. ", "Error Entry");
}
else
{
MessageBox.Show(
"Please enter a valid Number for the subtotal field.", "Error Entry");
txtSubtotal.Focus();
}
}
}
private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void txtSubtotal_TextChanged(object sender, EventArgs e)
{
}
}
```
} | 2015/10/25 | [
"https://Stackoverflow.com/questions/33328187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3473475/"
] | I would used KeyEvent press enter or Leave event for this, first I need to create generic class for verification if the input from the user is not a string.
Condition:
1 verify if the input is not a string Im using generic for general purposes class.
```
public class iCnF()
{
public static System.Boolean IsNumeric(System.Object Expression)
{
if (Expression == null || Expression is DateTime)
return false;
if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if(Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
} catch {} // just dismiss errors but return false
return false;
}
}
```
2. Then I need to verify if the input is not empty
```
private void txtSubtotal_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
{
if (txtSubtotal.Text.Length > 0)
{
bool sd = iCnF.IsNumeric(txtSubtotal.Text);
if (sd == false)
{
MessageBox.Show("Subtotal must be a numeric value. ", "Error Entry");
txtSubtotal.Clear();
txtSubtotal.Focus();
}
else
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
if (subtotal <= 0)
{
MessageBox.Show("Subtotal must be greater than $0.00. ", "Error Entry");
txtSubtotal.Focus();
}
if (subtotal >= 10000)
{
MessageBox.Show("Subtotal must be less than $10000.00. ", "Error Entry");
txtSubtotal.Focus();
}
}
}
else
{
MessageBox.Show("Subtotal must not be empty. ", "Error Entry");
txtSubtotal.Focus();
}
}
}
```
3. if not empty and numberic value my subtotal <= 0 and subtotal >= 10000
Hope this will help you :D | As I already mentioned in comment you should consider moving your code out of catch block.
In this case you should think of creating a simple method which will validate your input and produces output message.
An example is for you:
```
private bool IsPageValid()
{
string errorMessage = string.Empty;
bool isValid = true;
if (subtotal <= 0)
{
errorMessage+="<li>"+"<b>Subtotal must be greater than $0.00. ", "Error Entry"+ "</b><br/>";
txtSubtotal.Focus();
isValid=false;
}
}
```
>
> ***Likewise write other clause of validations in this function.***.This will validate each of your condition and if fails it would make the isValid false thus not allowing users to submit.
>
>
>
Now you should call this function in your button click.
```
protected void btnSubmit_Click(object sender, EventArgs e)
{
ClearMessage();
if (IsPageValid().Equals(true))
{
// allow next action to happen.
}
}
``` |
33,328,187 | I am relatively new at this and have been racking my brain attempting to get my program to work properly and it just won't. I am working in Visual Studio 2012 C# on a Forms Application.
I need it to produce a distinct error message when the user input value is more than `0` but less than `10,000`. It also must produce a distinct error message when the user enters a non-numeric value and a distinct error message when the user fails to enter any value at all.
The code I've written so far produces a distinct error message when the user enters a non-numeric value or when they fail to enter any value at all, but it does not trigger an error message when the user enters a value that is below or over the required range.
It is as if the compiler is ignoring the code I've written for the first exception/overflow exception and only recognizing the code for the second and final exception. My code has no coding errors. It appears that my problem is in the logic.
Please help me if you can. My code is below thanks!
```
private void btnCalculate_Click(object sender, System.EventArgs e)
{
try
{
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
decimal discountPercent = .25m;
decimal discountAmount = subtotal * discountPercent;
decimal invoiceTotal = subtotal - discountAmount;
lblDiscountPercent.Text = discountPercent.ToString("p1");
lblDiscountAmount.Text = discountAmount.ToString("c");
lblTotal.Text = invoiceTotal.ToString("c");
}
}
catch (OverflowException)
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
if (subtotal <= 0)
{
MessageBox.Show("Subtotal must be greater than $0.00. ", "Error Entry");
txtSubtotal.Focus();
}
if (subtotal >= 10000)
{
MessageBox.Show("Subtotal must be less than $10000.00. ", "Error Entry");
txtSubtotal.Focus();
}
}
catch (Exception)
{
if (txtSubtotal.Text == "")
{
MessageBox.Show("Subtotal is a required field. ", "Error Entry");
}
else
{
MessageBox.Show(
"Please enter a valid Number for the subtotal field.", "Error Entry");
txtSubtotal.Focus();
}
}
}
private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void txtSubtotal_TextChanged(object sender, EventArgs e)
{
}
}
```
} | 2015/10/25 | [
"https://Stackoverflow.com/questions/33328187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3473475/"
] | I would used KeyEvent press enter or Leave event for this, first I need to create generic class for verification if the input from the user is not a string.
Condition:
1 verify if the input is not a string Im using generic for general purposes class.
```
public class iCnF()
{
public static System.Boolean IsNumeric(System.Object Expression)
{
if (Expression == null || Expression is DateTime)
return false;
if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
return true;
try
{
if(Expression is string)
Double.Parse(Expression as string);
else
Double.Parse(Expression.ToString());
return true;
} catch {} // just dismiss errors but return false
return false;
}
}
```
2. Then I need to verify if the input is not empty
```
private void txtSubtotal_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab)
{
if (txtSubtotal.Text.Length > 0)
{
bool sd = iCnF.IsNumeric(txtSubtotal.Text);
if (sd == false)
{
MessageBox.Show("Subtotal must be a numeric value. ", "Error Entry");
txtSubtotal.Clear();
txtSubtotal.Focus();
}
else
{
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
if (subtotal <= 0)
{
MessageBox.Show("Subtotal must be greater than $0.00. ", "Error Entry");
txtSubtotal.Focus();
}
if (subtotal >= 10000)
{
MessageBox.Show("Subtotal must be less than $10000.00. ", "Error Entry");
txtSubtotal.Focus();
}
}
}
else
{
MessageBox.Show("Subtotal must not be empty. ", "Error Entry");
txtSubtotal.Focus();
}
}
}
```
3. if not empty and numberic value my subtotal <= 0 and subtotal >= 10000
Hope this will help you :D | Code should look like this
```
try {
decimal subtotal = Convert.ToDecimal(txtSubtotal.Text);
try {
if(x<0 || x>10000){
throw new OverFlowException("");
}
//Do what ever you want
}
catch(Exception ex){
// catch overflow
}
}
catch(Exception ex){
// catch nonnumeric value
}
``` |
2,047,165 | **Background**
I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programming" was about ten years ago in, high school, using Pascal. We didn't get all that far. What we did have though was what I think programmers call "an environment" that made some sort of sense. There was someplace to type in the "code" (programs), then a button to "compile," then (if it worked) a button to "run."
**A Python Environment (is this the right word at all?)**
Now I have been trying to get a set up where I can put in an hour or two whenever I have time but have utterly failed at setup. Any tutorials or guides that I have tried using seem to jump in with things like Shell, IDE, Interactive Shell, terminal, command line interface.
**My Failure So Far**
For example, I just tried to follow diveintopython's setup instructions. I'm using a mac. It tells me that for the fist few chapters I can get buy with python's command line version if I am comfortable with that (I am not) or I can download graphical interactive shell which will also be up to date. I go to here homepages.cwi.nl/~jack/macpython/download.html where it tells me that for osx10.3 (I'm on 10.5) it's already installed. I just need the "*IDE, "the Package Manager" and the waste module on which they depend*." They sound important (waste module sounds kind of dubious) because they sound like maybe I can click on something and have it open up a place to type in the code from the tutorial in some way that resembles the way I did it ten years ago in Pascal. Maybe. I hope.
Anyway, since that seems to be the most recent version, I install that. I click on the PythonIDE & nothing happens. Is it because I'm using the osx 10.3 package?
I then figured out that I seem to have macpython2.5 installed. Not sure if this came with the machine or if I installed it at some point (this is not my first failed attempt) which for some reason I assume corresponds to mac osx 10.5 in some way. But, as the instructions on the site above suggest for 2.3, there isn't a PythonIDE or package manager.
Is there an easier way to do this? I know what I wrote sounds comical but I'm really stuck & as you can see, I don't even really know what to ask. I'm not even really sure what it means to "have python installed. " I'm not sure where I write the program. I'm not sure how I run it. I'm fairly sure that you don't compile python the way we compiled Pascal.
What questions should I be asking?
<http://dl.dropbox.com/u/131615/screenshots/Snapshot%202010-01-12%2011-23-23.tiff>
\*\*Sidestory\* I once tried to start learning to program with php & made some basic progress. It took a while but I eventually figured out that a php program runs inside a html file that must (unlike normal html files) be run through an apache server. Where I write the program is a text file. Where I "compile & run" the program is in the browser/webserver. I thought that was complicated but I did figure it out and was working my way through php tutorial in about half an hour. | 2010/01/12 | [
"https://Stackoverflow.com/questions/2047165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Lots of great "Python tutorials for non-programmers" are listed [here](http://wiki.python.org/moin/BeginnersGuide/NonProgrammers)! | If you are a true beginner; **ALWAYS** keep the interactive shell handy (even if you write your code and tutorials in an editor) and use `help(whatever_you_need_help_with)`and `dir(whatever)` extensively.
For example;
```
>>> a = "foobar"
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__',
'__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith',
'expandtabs','find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle','isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
'rjust','rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title','translate', 'upper', 'zfill']
>>> help(a.title)
Help on built-in function title:
title(...)
S.title() -> string
Return a titlecased version of S, i.e. words start with uppercase
characters, all remaining cased characters have lowercase.
>>> a.title()
'Foobar'
``` |
2,047,165 | **Background**
I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programming" was about ten years ago in, high school, using Pascal. We didn't get all that far. What we did have though was what I think programmers call "an environment" that made some sort of sense. There was someplace to type in the "code" (programs), then a button to "compile," then (if it worked) a button to "run."
**A Python Environment (is this the right word at all?)**
Now I have been trying to get a set up where I can put in an hour or two whenever I have time but have utterly failed at setup. Any tutorials or guides that I have tried using seem to jump in with things like Shell, IDE, Interactive Shell, terminal, command line interface.
**My Failure So Far**
For example, I just tried to follow diveintopython's setup instructions. I'm using a mac. It tells me that for the fist few chapters I can get buy with python's command line version if I am comfortable with that (I am not) or I can download graphical interactive shell which will also be up to date. I go to here homepages.cwi.nl/~jack/macpython/download.html where it tells me that for osx10.3 (I'm on 10.5) it's already installed. I just need the "*IDE, "the Package Manager" and the waste module on which they depend*." They sound important (waste module sounds kind of dubious) because they sound like maybe I can click on something and have it open up a place to type in the code from the tutorial in some way that resembles the way I did it ten years ago in Pascal. Maybe. I hope.
Anyway, since that seems to be the most recent version, I install that. I click on the PythonIDE & nothing happens. Is it because I'm using the osx 10.3 package?
I then figured out that I seem to have macpython2.5 installed. Not sure if this came with the machine or if I installed it at some point (this is not my first failed attempt) which for some reason I assume corresponds to mac osx 10.5 in some way. But, as the instructions on the site above suggest for 2.3, there isn't a PythonIDE or package manager.
Is there an easier way to do this? I know what I wrote sounds comical but I'm really stuck & as you can see, I don't even really know what to ask. I'm not even really sure what it means to "have python installed. " I'm not sure where I write the program. I'm not sure how I run it. I'm fairly sure that you don't compile python the way we compiled Pascal.
What questions should I be asking?
<http://dl.dropbox.com/u/131615/screenshots/Snapshot%202010-01-12%2011-23-23.tiff>
\*\*Sidestory\* I once tried to start learning to program with php & made some basic progress. It took a while but I eventually figured out that a php program runs inside a html file that must (unlike normal html files) be run through an apache server. Where I write the program is a text file. Where I "compile & run" the program is in the browser/webserver. I thought that was complicated but I did figure it out and was working my way through php tutorial in about half an hour. | 2010/01/12 | [
"https://Stackoverflow.com/questions/2047165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Since you're on OSX, you don't actually need to install anything to get started. Simply open up the Terminal application, and type `python`. You'll go straight into the Python shell (command line) where you can type simple Python programs.
When you want to write longer ones, simply do as you did with PHP - write them in a text file, save them, then in the shell just type `python myprogram.py`. (Note that you'll have to quit the existing Python shell first, by pressing Ctrl-D).
As regards books, Dive Into Python is a fantastic guide but it's firmly aimed at people who already know how to program. There are plenty of beginners' guides at the link Alex gives. | The easiest way to start will be an online interpreter like [Try Python](http://try-python.mired.org/) or [codepad](http://codepad.org/).
Type `print "Hello world"` after the `>>>` in the input field and press enter. Your first Python program should be done.
There are lots of excellent python tutorials out there, you could start [here](http://docs.python.org/tutorial/). |
2,047,165 | **Background**
I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programming" was about ten years ago in, high school, using Pascal. We didn't get all that far. What we did have though was what I think programmers call "an environment" that made some sort of sense. There was someplace to type in the "code" (programs), then a button to "compile," then (if it worked) a button to "run."
**A Python Environment (is this the right word at all?)**
Now I have been trying to get a set up where I can put in an hour or two whenever I have time but have utterly failed at setup. Any tutorials or guides that I have tried using seem to jump in with things like Shell, IDE, Interactive Shell, terminal, command line interface.
**My Failure So Far**
For example, I just tried to follow diveintopython's setup instructions. I'm using a mac. It tells me that for the fist few chapters I can get buy with python's command line version if I am comfortable with that (I am not) or I can download graphical interactive shell which will also be up to date. I go to here homepages.cwi.nl/~jack/macpython/download.html where it tells me that for osx10.3 (I'm on 10.5) it's already installed. I just need the "*IDE, "the Package Manager" and the waste module on which they depend*." They sound important (waste module sounds kind of dubious) because they sound like maybe I can click on something and have it open up a place to type in the code from the tutorial in some way that resembles the way I did it ten years ago in Pascal. Maybe. I hope.
Anyway, since that seems to be the most recent version, I install that. I click on the PythonIDE & nothing happens. Is it because I'm using the osx 10.3 package?
I then figured out that I seem to have macpython2.5 installed. Not sure if this came with the machine or if I installed it at some point (this is not my first failed attempt) which for some reason I assume corresponds to mac osx 10.5 in some way. But, as the instructions on the site above suggest for 2.3, there isn't a PythonIDE or package manager.
Is there an easier way to do this? I know what I wrote sounds comical but I'm really stuck & as you can see, I don't even really know what to ask. I'm not even really sure what it means to "have python installed. " I'm not sure where I write the program. I'm not sure how I run it. I'm fairly sure that you don't compile python the way we compiled Pascal.
What questions should I be asking?
<http://dl.dropbox.com/u/131615/screenshots/Snapshot%202010-01-12%2011-23-23.tiff>
\*\*Sidestory\* I once tried to start learning to program with php & made some basic progress. It took a while but I eventually figured out that a php program runs inside a html file that must (unlike normal html files) be run through an apache server. Where I write the program is a text file. Where I "compile & run" the program is in the browser/webserver. I thought that was complicated but I did figure it out and was working my way through php tutorial in about half an hour. | 2010/01/12 | [
"https://Stackoverflow.com/questions/2047165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I recommend biting the bullet and using the command line version to start with.
Later you'll get onto writing scripts and you'll need a good editor, but not necessarily a python IDE.
For learning I found the "Python Tutorial" by Guido van Rossum, the author of python, to be a good starting point. ( <http://docs.python.org/tutorial/> )
And since you're on OSX you probably have python already installed so no install needed.
To check just type "python --version" into the command prompt in a terminal. | I was in the same boat, two books really helped me:
* Python 3 for Absolute Beginners
* Learning Python 4th Edition
* Python Pocket Reference (for when you've started coding basic stuff and need a handy reference book) |
2,047,165 | **Background**
I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programming" was about ten years ago in, high school, using Pascal. We didn't get all that far. What we did have though was what I think programmers call "an environment" that made some sort of sense. There was someplace to type in the "code" (programs), then a button to "compile," then (if it worked) a button to "run."
**A Python Environment (is this the right word at all?)**
Now I have been trying to get a set up where I can put in an hour or two whenever I have time but have utterly failed at setup. Any tutorials or guides that I have tried using seem to jump in with things like Shell, IDE, Interactive Shell, terminal, command line interface.
**My Failure So Far**
For example, I just tried to follow diveintopython's setup instructions. I'm using a mac. It tells me that for the fist few chapters I can get buy with python's command line version if I am comfortable with that (I am not) or I can download graphical interactive shell which will also be up to date. I go to here homepages.cwi.nl/~jack/macpython/download.html where it tells me that for osx10.3 (I'm on 10.5) it's already installed. I just need the "*IDE, "the Package Manager" and the waste module on which they depend*." They sound important (waste module sounds kind of dubious) because they sound like maybe I can click on something and have it open up a place to type in the code from the tutorial in some way that resembles the way I did it ten years ago in Pascal. Maybe. I hope.
Anyway, since that seems to be the most recent version, I install that. I click on the PythonIDE & nothing happens. Is it because I'm using the osx 10.3 package?
I then figured out that I seem to have macpython2.5 installed. Not sure if this came with the machine or if I installed it at some point (this is not my first failed attempt) which for some reason I assume corresponds to mac osx 10.5 in some way. But, as the instructions on the site above suggest for 2.3, there isn't a PythonIDE or package manager.
Is there an easier way to do this? I know what I wrote sounds comical but I'm really stuck & as you can see, I don't even really know what to ask. I'm not even really sure what it means to "have python installed. " I'm not sure where I write the program. I'm not sure how I run it. I'm fairly sure that you don't compile python the way we compiled Pascal.
What questions should I be asking?
<http://dl.dropbox.com/u/131615/screenshots/Snapshot%202010-01-12%2011-23-23.tiff>
\*\*Sidestory\* I once tried to start learning to program with php & made some basic progress. It took a while but I eventually figured out that a php program runs inside a html file that must (unlike normal html files) be run through an apache server. Where I write the program is a text file. Where I "compile & run" the program is in the browser/webserver. I thought that was complicated but I did figure it out and was working my way through php tutorial in about half an hour. | 2010/01/12 | [
"https://Stackoverflow.com/questions/2047165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Start with the very basics:
[Python 2.6.4 Installer](http://www.python.org/download/)
[The Official Python Tutorial](http://docs.python.org/tutorial/)
That's how I did it. | Buy
[Head First Programming](https://rads.stackoverflow.com/amzn/click/com/0596802374)
Seems like a really neat book ^^ |
2,047,165 | **Background**
I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programming" was about ten years ago in, high school, using Pascal. We didn't get all that far. What we did have though was what I think programmers call "an environment" that made some sort of sense. There was someplace to type in the "code" (programs), then a button to "compile," then (if it worked) a button to "run."
**A Python Environment (is this the right word at all?)**
Now I have been trying to get a set up where I can put in an hour or two whenever I have time but have utterly failed at setup. Any tutorials or guides that I have tried using seem to jump in with things like Shell, IDE, Interactive Shell, terminal, command line interface.
**My Failure So Far**
For example, I just tried to follow diveintopython's setup instructions. I'm using a mac. It tells me that for the fist few chapters I can get buy with python's command line version if I am comfortable with that (I am not) or I can download graphical interactive shell which will also be up to date. I go to here homepages.cwi.nl/~jack/macpython/download.html where it tells me that for osx10.3 (I'm on 10.5) it's already installed. I just need the "*IDE, "the Package Manager" and the waste module on which they depend*." They sound important (waste module sounds kind of dubious) because they sound like maybe I can click on something and have it open up a place to type in the code from the tutorial in some way that resembles the way I did it ten years ago in Pascal. Maybe. I hope.
Anyway, since that seems to be the most recent version, I install that. I click on the PythonIDE & nothing happens. Is it because I'm using the osx 10.3 package?
I then figured out that I seem to have macpython2.5 installed. Not sure if this came with the machine or if I installed it at some point (this is not my first failed attempt) which for some reason I assume corresponds to mac osx 10.5 in some way. But, as the instructions on the site above suggest for 2.3, there isn't a PythonIDE or package manager.
Is there an easier way to do this? I know what I wrote sounds comical but I'm really stuck & as you can see, I don't even really know what to ask. I'm not even really sure what it means to "have python installed. " I'm not sure where I write the program. I'm not sure how I run it. I'm fairly sure that you don't compile python the way we compiled Pascal.
What questions should I be asking?
<http://dl.dropbox.com/u/131615/screenshots/Snapshot%202010-01-12%2011-23-23.tiff>
\*\*Sidestory\* I once tried to start learning to program with php & made some basic progress. It took a while but I eventually figured out that a php program runs inside a html file that must (unlike normal html files) be run through an apache server. Where I write the program is a text file. Where I "compile & run" the program is in the browser/webserver. I thought that was complicated but I did figure it out and was working my way through php tutorial in about half an hour. | 2010/01/12 | [
"https://Stackoverflow.com/questions/2047165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Since you're on OSX, you don't actually need to install anything to get started. Simply open up the Terminal application, and type `python`. You'll go straight into the Python shell (command line) where you can type simple Python programs.
When you want to write longer ones, simply do as you did with PHP - write them in a text file, save them, then in the shell just type `python myprogram.py`. (Note that you'll have to quit the existing Python shell first, by pressing Ctrl-D).
As regards books, Dive Into Python is a fantastic guide but it's firmly aimed at people who already know how to program. There are plenty of beginners' guides at the link Alex gives. | Buy
[Head First Programming](https://rads.stackoverflow.com/amzn/click/com/0596802374)
Seems like a really neat book ^^ |
2,047,165 | **Background**
I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programming" was about ten years ago in, high school, using Pascal. We didn't get all that far. What we did have though was what I think programmers call "an environment" that made some sort of sense. There was someplace to type in the "code" (programs), then a button to "compile," then (if it worked) a button to "run."
**A Python Environment (is this the right word at all?)**
Now I have been trying to get a set up where I can put in an hour or two whenever I have time but have utterly failed at setup. Any tutorials or guides that I have tried using seem to jump in with things like Shell, IDE, Interactive Shell, terminal, command line interface.
**My Failure So Far**
For example, I just tried to follow diveintopython's setup instructions. I'm using a mac. It tells me that for the fist few chapters I can get buy with python's command line version if I am comfortable with that (I am not) or I can download graphical interactive shell which will also be up to date. I go to here homepages.cwi.nl/~jack/macpython/download.html where it tells me that for osx10.3 (I'm on 10.5) it's already installed. I just need the "*IDE, "the Package Manager" and the waste module on which they depend*." They sound important (waste module sounds kind of dubious) because they sound like maybe I can click on something and have it open up a place to type in the code from the tutorial in some way that resembles the way I did it ten years ago in Pascal. Maybe. I hope.
Anyway, since that seems to be the most recent version, I install that. I click on the PythonIDE & nothing happens. Is it because I'm using the osx 10.3 package?
I then figured out that I seem to have macpython2.5 installed. Not sure if this came with the machine or if I installed it at some point (this is not my first failed attempt) which for some reason I assume corresponds to mac osx 10.5 in some way. But, as the instructions on the site above suggest for 2.3, there isn't a PythonIDE or package manager.
Is there an easier way to do this? I know what I wrote sounds comical but I'm really stuck & as you can see, I don't even really know what to ask. I'm not even really sure what it means to "have python installed. " I'm not sure where I write the program. I'm not sure how I run it. I'm fairly sure that you don't compile python the way we compiled Pascal.
What questions should I be asking?
<http://dl.dropbox.com/u/131615/screenshots/Snapshot%202010-01-12%2011-23-23.tiff>
\*\*Sidestory\* I once tried to start learning to program with php & made some basic progress. It took a while but I eventually figured out that a php program runs inside a html file that must (unlike normal html files) be run through an apache server. Where I write the program is a text file. Where I "compile & run" the program is in the browser/webserver. I thought that was complicated but I did figure it out and was working my way through php tutorial in about half an hour. | 2010/01/12 | [
"https://Stackoverflow.com/questions/2047165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I recommend biting the bullet and using the command line version to start with.
Later you'll get onto writing scripts and you'll need a good editor, but not necessarily a python IDE.
For learning I found the "Python Tutorial" by Guido van Rossum, the author of python, to be a good starting point. ( <http://docs.python.org/tutorial/> )
And since you're on OSX you probably have python already installed so no install needed.
To check just type "python --version" into the command prompt in a terminal. | The easiest way to start will be an online interpreter like [Try Python](http://try-python.mired.org/) or [codepad](http://codepad.org/).
Type `print "Hello world"` after the `>>>` in the input field and press enter. Your first Python program should be done.
There are lots of excellent python tutorials out there, you could start [here](http://docs.python.org/tutorial/). |
2,047,165 | **Background**
I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programming" was about ten years ago in, high school, using Pascal. We didn't get all that far. What we did have though was what I think programmers call "an environment" that made some sort of sense. There was someplace to type in the "code" (programs), then a button to "compile," then (if it worked) a button to "run."
**A Python Environment (is this the right word at all?)**
Now I have been trying to get a set up where I can put in an hour or two whenever I have time but have utterly failed at setup. Any tutorials or guides that I have tried using seem to jump in with things like Shell, IDE, Interactive Shell, terminal, command line interface.
**My Failure So Far**
For example, I just tried to follow diveintopython's setup instructions. I'm using a mac. It tells me that for the fist few chapters I can get buy with python's command line version if I am comfortable with that (I am not) or I can download graphical interactive shell which will also be up to date. I go to here homepages.cwi.nl/~jack/macpython/download.html where it tells me that for osx10.3 (I'm on 10.5) it's already installed. I just need the "*IDE, "the Package Manager" and the waste module on which they depend*." They sound important (waste module sounds kind of dubious) because they sound like maybe I can click on something and have it open up a place to type in the code from the tutorial in some way that resembles the way I did it ten years ago in Pascal. Maybe. I hope.
Anyway, since that seems to be the most recent version, I install that. I click on the PythonIDE & nothing happens. Is it because I'm using the osx 10.3 package?
I then figured out that I seem to have macpython2.5 installed. Not sure if this came with the machine or if I installed it at some point (this is not my first failed attempt) which for some reason I assume corresponds to mac osx 10.5 in some way. But, as the instructions on the site above suggest for 2.3, there isn't a PythonIDE or package manager.
Is there an easier way to do this? I know what I wrote sounds comical but I'm really stuck & as you can see, I don't even really know what to ask. I'm not even really sure what it means to "have python installed. " I'm not sure where I write the program. I'm not sure how I run it. I'm fairly sure that you don't compile python the way we compiled Pascal.
What questions should I be asking?
<http://dl.dropbox.com/u/131615/screenshots/Snapshot%202010-01-12%2011-23-23.tiff>
\*\*Sidestory\* I once tried to start learning to program with php & made some basic progress. It took a while but I eventually figured out that a php program runs inside a html file that must (unlike normal html files) be run through an apache server. Where I write the program is a text file. Where I "compile & run" the program is in the browser/webserver. I thought that was complicated but I did figure it out and was working my way through php tutorial in about half an hour. | 2010/01/12 | [
"https://Stackoverflow.com/questions/2047165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Start with the very basics:
[Python 2.6.4 Installer](http://www.python.org/download/)
[The Official Python Tutorial](http://docs.python.org/tutorial/)
That's how I did it. | The easiest way to start will be an online interpreter like [Try Python](http://try-python.mired.org/) or [codepad](http://codepad.org/).
Type `print "Hello world"` after the `>>>` in the input field and press enter. Your first Python program should be done.
There are lots of excellent python tutorials out there, you could start [here](http://docs.python.org/tutorial/). |
2,047,165 | **Background**
I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programming" was about ten years ago in, high school, using Pascal. We didn't get all that far. What we did have though was what I think programmers call "an environment" that made some sort of sense. There was someplace to type in the "code" (programs), then a button to "compile," then (if it worked) a button to "run."
**A Python Environment (is this the right word at all?)**
Now I have been trying to get a set up where I can put in an hour or two whenever I have time but have utterly failed at setup. Any tutorials or guides that I have tried using seem to jump in with things like Shell, IDE, Interactive Shell, terminal, command line interface.
**My Failure So Far**
For example, I just tried to follow diveintopython's setup instructions. I'm using a mac. It tells me that for the fist few chapters I can get buy with python's command line version if I am comfortable with that (I am not) or I can download graphical interactive shell which will also be up to date. I go to here homepages.cwi.nl/~jack/macpython/download.html where it tells me that for osx10.3 (I'm on 10.5) it's already installed. I just need the "*IDE, "the Package Manager" and the waste module on which they depend*." They sound important (waste module sounds kind of dubious) because they sound like maybe I can click on something and have it open up a place to type in the code from the tutorial in some way that resembles the way I did it ten years ago in Pascal. Maybe. I hope.
Anyway, since that seems to be the most recent version, I install that. I click on the PythonIDE & nothing happens. Is it because I'm using the osx 10.3 package?
I then figured out that I seem to have macpython2.5 installed. Not sure if this came with the machine or if I installed it at some point (this is not my first failed attempt) which for some reason I assume corresponds to mac osx 10.5 in some way. But, as the instructions on the site above suggest for 2.3, there isn't a PythonIDE or package manager.
Is there an easier way to do this? I know what I wrote sounds comical but I'm really stuck & as you can see, I don't even really know what to ask. I'm not even really sure what it means to "have python installed. " I'm not sure where I write the program. I'm not sure how I run it. I'm fairly sure that you don't compile python the way we compiled Pascal.
What questions should I be asking?
<http://dl.dropbox.com/u/131615/screenshots/Snapshot%202010-01-12%2011-23-23.tiff>
\*\*Sidestory\* I once tried to start learning to program with php & made some basic progress. It took a while but I eventually figured out that a php program runs inside a html file that must (unlike normal html files) be run through an apache server. Where I write the program is a text file. Where I "compile & run" the program is in the browser/webserver. I thought that was complicated but I did figure it out and was working my way through php tutorial in about half an hour. | 2010/01/12 | [
"https://Stackoverflow.com/questions/2047165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Start with the very basics:
[Python 2.6.4 Installer](http://www.python.org/download/)
[The Official Python Tutorial](http://docs.python.org/tutorial/)
That's how I did it. | If you are a true beginner; **ALWAYS** keep the interactive shell handy (even if you write your code and tutorials in an editor) and use `help(whatever_you_need_help_with)`and `dir(whatever)` extensively.
For example;
```
>>> a = "foobar"
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__',
'__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith',
'expandtabs','find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle','isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
'rjust','rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase',
'title','translate', 'upper', 'zfill']
>>> help(a.title)
Help on built-in function title:
title(...)
S.title() -> string
Return a titlecased version of S, i.e. words start with uppercase
characters, all remaining cased characters have lowercase.
>>> a.title()
'Foobar'
``` |
2,047,165 | **Background**
I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programming" was about ten years ago in, high school, using Pascal. We didn't get all that far. What we did have though was what I think programmers call "an environment" that made some sort of sense. There was someplace to type in the "code" (programs), then a button to "compile," then (if it worked) a button to "run."
**A Python Environment (is this the right word at all?)**
Now I have been trying to get a set up where I can put in an hour or two whenever I have time but have utterly failed at setup. Any tutorials or guides that I have tried using seem to jump in with things like Shell, IDE, Interactive Shell, terminal, command line interface.
**My Failure So Far**
For example, I just tried to follow diveintopython's setup instructions. I'm using a mac. It tells me that for the fist few chapters I can get buy with python's command line version if I am comfortable with that (I am not) or I can download graphical interactive shell which will also be up to date. I go to here homepages.cwi.nl/~jack/macpython/download.html where it tells me that for osx10.3 (I'm on 10.5) it's already installed. I just need the "*IDE, "the Package Manager" and the waste module on which they depend*." They sound important (waste module sounds kind of dubious) because they sound like maybe I can click on something and have it open up a place to type in the code from the tutorial in some way that resembles the way I did it ten years ago in Pascal. Maybe. I hope.
Anyway, since that seems to be the most recent version, I install that. I click on the PythonIDE & nothing happens. Is it because I'm using the osx 10.3 package?
I then figured out that I seem to have macpython2.5 installed. Not sure if this came with the machine or if I installed it at some point (this is not my first failed attempt) which for some reason I assume corresponds to mac osx 10.5 in some way. But, as the instructions on the site above suggest for 2.3, there isn't a PythonIDE or package manager.
Is there an easier way to do this? I know what I wrote sounds comical but I'm really stuck & as you can see, I don't even really know what to ask. I'm not even really sure what it means to "have python installed. " I'm not sure where I write the program. I'm not sure how I run it. I'm fairly sure that you don't compile python the way we compiled Pascal.
What questions should I be asking?
<http://dl.dropbox.com/u/131615/screenshots/Snapshot%202010-01-12%2011-23-23.tiff>
\*\*Sidestory\* I once tried to start learning to program with php & made some basic progress. It took a while but I eventually figured out that a php program runs inside a html file that must (unlike normal html files) be run through an apache server. Where I write the program is a text file. Where I "compile & run" the program is in the browser/webserver. I thought that was complicated but I did figure it out and was working my way through php tutorial in about half an hour. | 2010/01/12 | [
"https://Stackoverflow.com/questions/2047165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I wrote Building Skills in Programming for folks who are struggling, it may help.
<http://homepage.mac.com/s_lott/books/nonprogrammer.html> | Buy
[Head First Programming](https://rads.stackoverflow.com/amzn/click/com/0596802374)
Seems like a really neat book ^^ |
2,047,165 | **Background**
I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programming" was about ten years ago in, high school, using Pascal. We didn't get all that far. What we did have though was what I think programmers call "an environment" that made some sort of sense. There was someplace to type in the "code" (programs), then a button to "compile," then (if it worked) a button to "run."
**A Python Environment (is this the right word at all?)**
Now I have been trying to get a set up where I can put in an hour or two whenever I have time but have utterly failed at setup. Any tutorials or guides that I have tried using seem to jump in with things like Shell, IDE, Interactive Shell, terminal, command line interface.
**My Failure So Far**
For example, I just tried to follow diveintopython's setup instructions. I'm using a mac. It tells me that for the fist few chapters I can get buy with python's command line version if I am comfortable with that (I am not) or I can download graphical interactive shell which will also be up to date. I go to here homepages.cwi.nl/~jack/macpython/download.html where it tells me that for osx10.3 (I'm on 10.5) it's already installed. I just need the "*IDE, "the Package Manager" and the waste module on which they depend*." They sound important (waste module sounds kind of dubious) because they sound like maybe I can click on something and have it open up a place to type in the code from the tutorial in some way that resembles the way I did it ten years ago in Pascal. Maybe. I hope.
Anyway, since that seems to be the most recent version, I install that. I click on the PythonIDE & nothing happens. Is it because I'm using the osx 10.3 package?
I then figured out that I seem to have macpython2.5 installed. Not sure if this came with the machine or if I installed it at some point (this is not my first failed attempt) which for some reason I assume corresponds to mac osx 10.5 in some way. But, as the instructions on the site above suggest for 2.3, there isn't a PythonIDE or package manager.
Is there an easier way to do this? I know what I wrote sounds comical but I'm really stuck & as you can see, I don't even really know what to ask. I'm not even really sure what it means to "have python installed. " I'm not sure where I write the program. I'm not sure how I run it. I'm fairly sure that you don't compile python the way we compiled Pascal.
What questions should I be asking?
<http://dl.dropbox.com/u/131615/screenshots/Snapshot%202010-01-12%2011-23-23.tiff>
\*\*Sidestory\* I once tried to start learning to program with php & made some basic progress. It took a while but I eventually figured out that a php program runs inside a html file that must (unlike normal html files) be run through an apache server. Where I write the program is a text file. Where I "compile & run" the program is in the browser/webserver. I thought that was complicated but I did figure it out and was working my way through php tutorial in about half an hour. | 2010/01/12 | [
"https://Stackoverflow.com/questions/2047165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Start with the very basics:
[Python 2.6.4 Installer](http://www.python.org/download/)
[The Official Python Tutorial](http://docs.python.org/tutorial/)
That's how I did it. | Since you're on OSX, you don't actually need to install anything to get started. Simply open up the Terminal application, and type `python`. You'll go straight into the Python shell (command line) where you can type simple Python programs.
When you want to write longer ones, simply do as you did with PHP - write them in a text file, save them, then in the shell just type `python myprogram.py`. (Note that you'll have to quit the existing Python shell first, by pressing Ctrl-D).
As regards books, Dive Into Python is a fantastic guide but it's firmly aimed at people who already know how to program. There are plenty of beginners' guides at the link Alex gives. |
54,830,272 | Just starting out with f#, I come OO C# background and I have the following code that reads a text file of uk postscodes, it then hits an api end point with post codes, I test the result to see if post is valid or not:
```
let postCodeFile = "c:\\tmp\\randomPostCodes.txt"
let readLines filePath = System.IO.File.ReadLines(filePath)
let lines = readLines postCodeFile
let postCodeValidDaterUrl = "https://api.postcodes.io/postcodes/"
let validatePostCode postCode =
Request.createUrl Get (postCodeValidDaterUrl + postCode)
|> getResponse
|> run
let translateResponse response =
match response.statusCode with
| 200 -> true
| _ -> false
let validPostCode = validatePostCode >> translateResponse
lines |> Seq.iter(fun x -> validPostCode(x) |> printfn "%s-%b" x)
```
Any suggestions on making it more functional? | 2019/02/22 | [
"https://Stackoverflow.com/questions/54830272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719625/"
] | ### Critique / code review
You've already made this about as functional as it can be. I'll go through your code and explain why your decisions were good, and in a few cases, where you could make minor improvements.
```
let postCodeFile = "c:\\tmp\\randomPostCodes.txt"
```
Good to have this as a named variable; in real code, this would of course be a parameter to the script or a function parameter. So having it as a named variable is useful.
```
let readLines filePath = System.IO.File.ReadLines(filePath)
```
This function isn't strictly necessary; since `System.IO.File.ReadLines` takes a single parameter, you would be able to pipe into it (e.g., `postCodeFile |> System.IO.File.ReadLines |> Seq.iter(...)`. But I like the shorter name, so I'd probably write it this way as well.
```
let lines = readLines postCodeFile
```
I'd probably leave off creating the `lines` name, and instead do `postCodeFile |> readLines |> Seq.iter (...)` in the last line of your code. There's nothing inherently *wrong* with the way you've done it, but you don't use the `lines` variable anywhere else so there's no real reason to give it a name. F#'s pipes allow you to skip naming your intermediate steps.
```
let postCodeValidDaterUrl = "https://api.postcodes.io/postcodes/"
```
Again, good to give this a name so that you can turn it into a parameter or a config file variable later. Only thing I see here that could be improved is the spelling: `ValidDater` should have been `Validator`.
```
let validatePostCode postCode =
Request.createUrl Get (postCodeValidDaterUrl + postCode)
|> getResponse
|> run
```
Looks good.
```
let translateResponse response =
match response.statusCode with
| 200 -> true
| _ -> false
```
Could be simpler: `let translateResponse response = (response.statusCode = 200)`. But the `match` expression lets you expand it later if you have an API that could return other status codes, like 204, to indicate success as well. I'd probably go with the simpler comparison here, and add the `match` statement only if it's needed.
```
let validPostCode = validatePostCode >> translateResponse
```
Nice.
```
lines |> Seq.iter(fun x -> validPostCode(x) |> printfn "%s-%b" x)
```
As I mentioned earlier, `lines` is an intermediate step, so I'd probably change this to `postCodeFile |> readLines |> Seq.iter (...)` since that allows you to skip giving names to your intermediate steps.
### Why this is good
Two things you did well here:
1. You wrote each function to do just one thing, and composed functions together to create larger "building blocks" of code. E.g., `validatePostCode` just sends off a request, and a different function decides whether the response indicates a valid code. This is good.
2. You separated (as much as you could) your I/O from your business logic. Specifically, the part of the code that validates the post codes doesn't try to read them in, or write out the results; it just says "Is this valid, or not?" That means that if you later need to swap out the API you call, or if you can do some internal checking on post codes that doesn't need to go hit the outside world, you can swap that out easily later. It's usually good practice to write your code in "layers", with I/O as the "outside" layer of your code, validation just "inside" the I/O layer, and then business logic inside the validation layer — so that your business-logic code can trust that it has received only valid data. You don't have any business logic in this simple example, but you have the I/O and validation layers properly separated. Well done. | This is just my style, it is not necessarily more functional or better:
```
open System.IO
let postCodeFile = "c:\\tmp\\randomPostCodes.txt"
let postCodeValidDaterUrl = "https://api.postcodes.io/postcodes/"
let validatePostCode postCode =
Request.createUrl Get (postCodeValidDaterUrl + postCode)
|> getResponse
|> run
|> fun response -> response.statusCode = 200
File.ReadLines postCodeFile
|> Seq.iter (fun code -> validatePostCode code |> printfn "%s-%b" code )
``` |
54,830,272 | Just starting out with f#, I come OO C# background and I have the following code that reads a text file of uk postscodes, it then hits an api end point with post codes, I test the result to see if post is valid or not:
```
let postCodeFile = "c:\\tmp\\randomPostCodes.txt"
let readLines filePath = System.IO.File.ReadLines(filePath)
let lines = readLines postCodeFile
let postCodeValidDaterUrl = "https://api.postcodes.io/postcodes/"
let validatePostCode postCode =
Request.createUrl Get (postCodeValidDaterUrl + postCode)
|> getResponse
|> run
let translateResponse response =
match response.statusCode with
| 200 -> true
| _ -> false
let validPostCode = validatePostCode >> translateResponse
lines |> Seq.iter(fun x -> validPostCode(x) |> printfn "%s-%b" x)
```
Any suggestions on making it more functional? | 2019/02/22 | [
"https://Stackoverflow.com/questions/54830272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719625/"
] | I don't think the aim here should be to make the code "more functional". Being functional is not an inherent value. In F#, it makes sense to keep the core of your logic functional, but if you are doing a lot of I/O, then it makes sense to follow more imperative style.
My version of your code would look like this (somewhat overlapping with some suggestions by @rmunn):
```
let postCodeFile = "c:\\tmp\\randomPostCodes.txt"
let postCodeValidDaterUrl = "https://api.postcodes.io/postcodes/"
let lines = System.IO.File.ReadLines(postCodeFile)
let validatePostCode postCode =
Request.createUrl Get (postCodeValidDaterUrl + postCode)
|> getResponse
|> run
let translateResponse response =
response.statusCode = 200
for line in lines do
let valid = translateResponse (validatePostCode line)
printfn "%s-%b" line valid
```
My changes are:
* I removed the `readLines` helper and just call `File.ReadLines` directly. There is no need to introduce F# alias for .NET methods if it does not serve some greater purpose like providing a more F#-friendly API that is reused in multiple places.
* Like @rmunn, I replaced the `match` with `response.statusCode = 200`. I only use `match` when I need to bind new variables as part of matching. When just testing Boolean conditions, I think `if` is better.
* I replaced your composed function and `Seq.iter` with a normal `for` loop. The code is imperative anyway, so I do not see why you wouldn't want to use a built-in language construct. I eliminated `validPostCode` because you're only using the composed function in one place, so introducing it does not simplify code. | This is just my style, it is not necessarily more functional or better:
```
open System.IO
let postCodeFile = "c:\\tmp\\randomPostCodes.txt"
let postCodeValidDaterUrl = "https://api.postcodes.io/postcodes/"
let validatePostCode postCode =
Request.createUrl Get (postCodeValidDaterUrl + postCode)
|> getResponse
|> run
|> fun response -> response.statusCode = 200
File.ReadLines postCodeFile
|> Seq.iter (fun code -> validatePostCode code |> printfn "%s-%b" code )
``` |
459,552 | Find all the values of $x \in \mathbb{R}$ from this inequality:
$$\left|\frac3{x^3-8}\right|=\left|\frac1{x-2}\right|$$
This is my work:
$$\frac{\left|\frac3{x^3-8}\right|}{\left|\frac1{x-2}\right|}=1$$
$$\left|\frac{3(x-2)}{x^3-8}\right|=1$$
$$\left|\frac {x-2}{x^3-2^3}\right|=\frac13$$ | 2013/08/04 | [
"https://math.stackexchange.com/questions/459552",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/88419/"
] | $$\left|\;\frac3{x^3-8}\;\right|=\left|\;\frac1{x-2}\;\right|\iff3|x-2|=|x-2||x^2+2x+4|$$
Now, it obviously *has* to be $\,x\ne 2\,$ , so... | HINT:
$x^3-8=x^3-2^3=(x-2)\{x^2+2x+2^2\}=(x-2)\{(x+1)^2+3\}$
So assuming $x-2\ne0,$ we can safely cancel $x-2$ and utilize $|x^2+2x+4|=x^2+2x+4$ |
459,552 | Find all the values of $x \in \mathbb{R}$ from this inequality:
$$\left|\frac3{x^3-8}\right|=\left|\frac1{x-2}\right|$$
This is my work:
$$\frac{\left|\frac3{x^3-8}\right|}{\left|\frac1{x-2}\right|}=1$$
$$\left|\frac{3(x-2)}{x^3-8}\right|=1$$
$$\left|\frac {x-2}{x^3-2^3}\right|=\frac13$$ | 2013/08/04 | [
"https://math.stackexchange.com/questions/459552",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/88419/"
] | $$\left|\;\frac3{x^3-8}\;\right|=\left|\;\frac1{x-2}\;\right|\iff3|x-2|=|x-2||x^2+2x+4|$$
Now, it obviously *has* to be $\,x\ne 2\,$ , so... | $$\left|\;\frac3{x^3-8}\;\right|=\left|\;\frac1{x-2}\;\right|\iff3|x-2|=|x-2||x^2+2x+4|$$
Since $x-2\ne0$ we can cancel both sides and get a quadratic $|x^2+2x+4|$ which has no solution in the real axis. |
14,245,233 | I want to have a customer testimonial quote centered in the middle of a page. The quote might be arbitrary length, but doesn't span two lines. Then I want a new line and then the name of the person that provided the testimonial, just under the testimonial but right justified.
```
<div class="quote">
"Wow! Thanks, create customer service."
</div>
<div class="source">
-- John S. - California
</div>
```
Styles:
```
.quote {text-align:center}
.source {text-align:right; padding-right:300px;}
```
How do I align the source so that I works for arbitrary length of quotes? | 2013/01/09 | [
"https://Stackoverflow.com/questions/14245233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/793454/"
] | This will do, probably:
HTML:
```
<blockquote>
<p>
<span class="quote">
"Wow! Thanks, create customer service."
<cite>
-- John S. - California
</cite>
</span>
</p>
</blockquote>
```
CSS:
```
blockquote {
text-align: center;
}
.quote {
position: relative;
}
cite {
position: absolute;
right: 0;
bottom: -25px;
text-align: right;
}
``` | Basically: you can't without going too ugly and hack-y with your markup. (See THiCE's answer for such a solution).
I do **not** recommend this, but if you're okay with using JavaScript, then this is fairly simple: (below uses jQuery, but can be achieved without it)
```
$(".quote").each(function() {
var $this = $(this);
$this.next().css({"padding-right": ($this.parent().width() - $this.width()) / 2});
});
```
If you don't want to use JavaScript and don't want to go hack-y, I suggest you rethink your layout just a bit. |
14,245,233 | I want to have a customer testimonial quote centered in the middle of a page. The quote might be arbitrary length, but doesn't span two lines. Then I want a new line and then the name of the person that provided the testimonial, just under the testimonial but right justified.
```
<div class="quote">
"Wow! Thanks, create customer service."
</div>
<div class="source">
-- John S. - California
</div>
```
Styles:
```
.quote {text-align:center}
.source {text-align:right; padding-right:300px;}
```
How do I align the source so that I works for arbitrary length of quotes? | 2013/01/09 | [
"https://Stackoverflow.com/questions/14245233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/793454/"
] | This will do, probably:
HTML:
```
<blockquote>
<p>
<span class="quote">
"Wow! Thanks, create customer service."
<cite>
-- John S. - California
</cite>
</span>
</p>
</blockquote>
```
CSS:
```
blockquote {
text-align: center;
}
.quote {
position: relative;
}
cite {
position: absolute;
right: 0;
bottom: -25px;
text-align: right;
}
``` | Change your markup a bit and nest the source into the quote.
```
<div class="quote">
"Wow! Thanks, create customer service."
<div class="source">
-- John S. - California
</div>
</div>
```
The CSS for it:
```
.quote {
display:table;
text-align: center;
margin:0 auto;
}
.quote .source {
text-align:right;
}
```
Here is the [fiddle](http://jsfiddle.net/PskLe/) for it. |
14,245,233 | I want to have a customer testimonial quote centered in the middle of a page. The quote might be arbitrary length, but doesn't span two lines. Then I want a new line and then the name of the person that provided the testimonial, just under the testimonial but right justified.
```
<div class="quote">
"Wow! Thanks, create customer service."
</div>
<div class="source">
-- John S. - California
</div>
```
Styles:
```
.quote {text-align:center}
.source {text-align:right; padding-right:300px;}
```
How do I align the source so that I works for arbitrary length of quotes? | 2013/01/09 | [
"https://Stackoverflow.com/questions/14245233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/793454/"
] | Change your markup a bit and nest the source into the quote.
```
<div class="quote">
"Wow! Thanks, create customer service."
<div class="source">
-- John S. - California
</div>
</div>
```
The CSS for it:
```
.quote {
display:table;
text-align: center;
margin:0 auto;
}
.quote .source {
text-align:right;
}
```
Here is the [fiddle](http://jsfiddle.net/PskLe/) for it. | Basically: you can't without going too ugly and hack-y with your markup. (See THiCE's answer for such a solution).
I do **not** recommend this, but if you're okay with using JavaScript, then this is fairly simple: (below uses jQuery, but can be achieved without it)
```
$(".quote").each(function() {
var $this = $(this);
$this.next().css({"padding-right": ($this.parent().width() - $this.width()) / 2});
});
```
If you don't want to use JavaScript and don't want to go hack-y, I suggest you rethink your layout just a bit. |
3,379 | What is the best torrent client and is there a client that has a search feature? I mean not to search for local torrent files, but to search for files to download. | 2015/12/05 | [
"https://elementaryos.stackexchange.com/questions/3379",
"https://elementaryos.stackexchange.com",
"https://elementaryos.stackexchange.com/users/3333/"
] | Transmission will be your best bet since it is also written in GTK+, it is integrated well with elementary OS. Note that it doesn't have a search features but it is the [best client](http://pastehtml.com/view/5tx16jw.html) in terms of CPU usage and RAM usage while downloading. | I quite like qBittorrent (`sudo apt install qbittorent` if the command-line is your thing)
I don't know if it is the best - I haven't done that much testing - but it satisfies your requirement for searching (it has a whole bunch of built-in searches, and you can add more), and I think the interface is quite nice
If you're new to Linux, you might find <http://alternativeto.net> useful, it allows for you to search for applications that you might be familiar with on other platforms and provides suggestions for possible alternatives.
The site features user ratings to give you an idea of what the replacement apps are like. |
3,379 | What is the best torrent client and is there a client that has a search feature? I mean not to search for local torrent files, but to search for files to download. | 2015/12/05 | [
"https://elementaryos.stackexchange.com/questions/3379",
"https://elementaryos.stackexchange.com",
"https://elementaryos.stackexchange.com/users/3333/"
] | Transmission will be your best bet since it is also written in GTK+, it is integrated well with elementary OS. Note that it doesn't have a search features but it is the [best client](http://pastehtml.com/view/5tx16jw.html) in terms of CPU usage and RAM usage while downloading. | I'm going to preface this with a nod to the fact that I work on [elementary.io](https://elementary.io), and thanks to that have access to lots of lovely metrics mere mortals are not normally privy to.
---
Transmission (38%)
==================
[Transmission](https://transmissionbt.com/) is by far the most popular torrent client, more than a third of torrent users use it and it comes with some reasonably nice GTK support. This provides a nice, clean, open-source client that is easy to use.
[](https://i.stack.imgur.com/4bbGc.png)
µTorrent (24% +1.6%)
====================
Second up is [µTorrent](http://www.utorrent.com/intl/en/), sometimes uTorrent because it's easier to type. It's been around a long time and has had a lot of controversy over the years. It's ad-supported by default but does have some nifty features built in for finding torrents.
[](https://i.stack.imgur.com/myODs.png)
qBittorrent (16%)
=================
[qBittorrent](http://www.qbittorrent.org/) is a Qt toolkit knock-off of uTorrent, and because of the mismatched toolkits probably doesn't look quite so nice on elementary.
[](https://i.stack.imgur.com/Qthqn.png)
Deluge (6.6%)
=============
Finally, [Deluge](http://deluge-torrent.org/) is another open-source client, available for practically every system. This is a common linux-enthusiasts favourite.
[](https://i.stack.imgur.com/K2Ui3.png) |
29,363,978 | This is my first attempt to create a sample angular application.
In `app.js` I defined the following -
```
var app = angular.module('myTestApp', ['ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch']);
app.config(function ($routeProvider) {
routeProvider
.when('sample', {
templateUrl: 'views/sample.html',
controller: 'sampleCtrl'
})
});
```
I have created corresponding `sample.js` for controller, `sample.html` for template and `sampleModel.js` for model.
In grunt console, it throws `app` is not defined in controller and model file
Here is the controller file -
```
'use strict';
app.controller('SampleCtrl', function ($scope,
$location,
$routeParams,
SampleModel) {
console.log('this is a test controller');
});
```
All the files are included in index.html and the resources are loading correctly which I checked by chrome developer tool but I can't find the reason why it says app not defined. Is there anything I am missing? | 2015/03/31 | [
"https://Stackoverflow.com/questions/29363978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3396009/"
] | As they are separate files and grunt/jshint will not know that the variable is available in other files. Instead of that it would be a best practice to use it in this way:
Instead use this:
```
angular.module('myTestApp')
.controller('SampleCtrl', function ($scope,
$location,
$routeParams,
SampleModel) {
console.log('this is a test controller');
});
```
Another general pattern you might have noticed in most the other's code, wrapping the code inside an IIFE.
```
(function() {
"use strict";
var app = angular.module('myTestApp')
app.controller('SampleCtrl', function ($scope,
$location,
$routeParams,
SampleModel) {
console.log('this is a test controller');
});
})();
```
In this app will not pollute the global namespace and it's local to that function.
Here if you've noticed, I've not used `[]` while using `angular.module()`, it means that we're just getting that module.
So in your app.'s alone, it will be with `[]` and in other files without `[]`
```
(function() {
"use strict";
var app = angular.module('myTestApp', ['ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch']);
app.config(function ($routeProvider) {
$routeProvider
.when('sample', {
templateUrl: 'views/sample.html',
controller: 'sampleCtrl'
})
});
})();
``` | If everything else is fine, this line is causing the issue in your code -
```
app.config(function ($routeProvider) {
routeProvider
```
you should instead use -
```
app.config(function ($routeProvider) {
$routeProvider
```
And yes, if `var app` is not working, try using
```
angular.module('myTestApp')
.controller('SampleCtrl',...
``` |
2,494,862 | I have the following code:
```
ifstream initFile;
initFile.open("D:\\InitTLM.csv");
if(initFile.is_open())
{
// Process file
}
```
The file is not opening. The file does exist on the D: drive. Is there a way to find out exactly why this file cannot be found? Like an "errno"? | 2010/03/22 | [
"https://Stackoverflow.com/questions/2494862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257569/"
] | Answered here I believe: [Get std::fstream failure error messages and/or exceptions](https://stackoverflow.com/questions/839644/get-stdfstream-failure-error-messages-and-or-exceptions) | The STL is not great at reporting errors. Here's the best you can do within the standard:
```
ifstream initFile;
initFile.exceptions(ifstream::eofbit|ifstream::failbit|ifstream::badbit);
try
{
initFile.open("D:\\InitTLM.csv");
// Process File
}
catch(ifstream::failure e)
{
cout << "Exception opening file:" << e.what() << endl;
}
```
In my experience, the message returned by what() is usually useless. |
2,494,862 | I have the following code:
```
ifstream initFile;
initFile.open("D:\\InitTLM.csv");
if(initFile.is_open())
{
// Process file
}
```
The file is not opening. The file does exist on the D: drive. Is there a way to find out exactly why this file cannot be found? Like an "errno"? | 2010/03/22 | [
"https://Stackoverflow.com/questions/2494862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257569/"
] | You should be able to use your OS's underlying error reporting mechanism to get the reason (because the standard library is built on the OS primitives). The code won't be portable, but it should get you to the bottom of your issue.
Since you appear to be using Windows, you would use [GetLastError](http://msdn.microsoft.com/en-us/library/ms679360%28VS.85%29.aspx) to get the raw code and [FormatMessage](http://msdn.microsoft.com/en-us/library/ms679351%28VS.85%29.aspx) to convert it to a textual description. | Answered here I believe: [Get std::fstream failure error messages and/or exceptions](https://stackoverflow.com/questions/839644/get-stdfstream-failure-error-messages-and-or-exceptions) |
2,494,862 | I have the following code:
```
ifstream initFile;
initFile.open("D:\\InitTLM.csv");
if(initFile.is_open())
{
// Process file
}
```
The file is not opening. The file does exist on the D: drive. Is there a way to find out exactly why this file cannot be found? Like an "errno"? | 2010/03/22 | [
"https://Stackoverflow.com/questions/2494862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257569/"
] | Answered here I believe: [Get std::fstream failure error messages and/or exceptions](https://stackoverflow.com/questions/839644/get-stdfstream-failure-error-messages-and-or-exceptions) | Check the permissions on the root of the D: drive. You may find that your compiled executable, or the service under which your debugger is running, does not have sufficient access privileges to open that file.
Try changing the permissions on the D:\ root directory temporarily to "Everyone --> Full Control", and see if that fixes the issue. |
2,494,862 | I have the following code:
```
ifstream initFile;
initFile.open("D:\\InitTLM.csv");
if(initFile.is_open())
{
// Process file
}
```
The file is not opening. The file does exist on the D: drive. Is there a way to find out exactly why this file cannot be found? Like an "errno"? | 2010/03/22 | [
"https://Stackoverflow.com/questions/2494862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257569/"
] | You should be able to use your OS's underlying error reporting mechanism to get the reason (because the standard library is built on the OS primitives). The code won't be portable, but it should get you to the bottom of your issue.
Since you appear to be using Windows, you would use [GetLastError](http://msdn.microsoft.com/en-us/library/ms679360%28VS.85%29.aspx) to get the raw code and [FormatMessage](http://msdn.microsoft.com/en-us/library/ms679351%28VS.85%29.aspx) to convert it to a textual description. | The STL is not great at reporting errors. Here's the best you can do within the standard:
```
ifstream initFile;
initFile.exceptions(ifstream::eofbit|ifstream::failbit|ifstream::badbit);
try
{
initFile.open("D:\\InitTLM.csv");
// Process File
}
catch(ifstream::failure e)
{
cout << "Exception opening file:" << e.what() << endl;
}
```
In my experience, the message returned by what() is usually useless. |
2,494,862 | I have the following code:
```
ifstream initFile;
initFile.open("D:\\InitTLM.csv");
if(initFile.is_open())
{
// Process file
}
```
The file is not opening. The file does exist on the D: drive. Is there a way to find out exactly why this file cannot be found? Like an "errno"? | 2010/03/22 | [
"https://Stackoverflow.com/questions/2494862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257569/"
] | You should be able to use your OS's underlying error reporting mechanism to get the reason (because the standard library is built on the OS primitives). The code won't be portable, but it should get you to the bottom of your issue.
Since you appear to be using Windows, you would use [GetLastError](http://msdn.microsoft.com/en-us/library/ms679360%28VS.85%29.aspx) to get the raw code and [FormatMessage](http://msdn.microsoft.com/en-us/library/ms679351%28VS.85%29.aspx) to convert it to a textual description. | Check the permissions on the root of the D: drive. You may find that your compiled executable, or the service under which your debugger is running, does not have sufficient access privileges to open that file.
Try changing the permissions on the D:\ root directory temporarily to "Everyone --> Full Control", and see if that fixes the issue. |
53,060,993 | We have a large app built on `Laravel 5.1` and `October CMS`. Right now we are trying to get rid of october, but we are facing some problems. We managed to remove all october's dependencies, including those in `Application`, but there is something strange going on.
When I try to run the app, i.e. run `php artisan tinker` I get the error:
```
PHP Fatal error: Uncaught ReflectionException: Class log does not exist in /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php:741
Stack trace:
#0 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(741): ReflectionClass->__construct('log')
#1 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(631): Illuminate\Container\Container->build('log', Array)
#2 /var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(674): Illuminate\Container\Container->make('log', Array)
#3 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(842): Illuminate\Foundation\Application->make('log')
#4 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(805): Illuminate\Container\Container->resolveClass(Object(ReflectionParameter))
#5 /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php(775): Illuminate\Container\Container->getDependencies(Array, Array)
#6 /var/www/html/vendor/ in /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 741
```
I searched the net for this error and most of the suggested reasons are some sort of error in config files. But I checked them all, in fact I even tried to comment out all of the config files and I still get the same error.
I tried to resolve this dependency manually, by adding the following line in `bootstrap/app.php`:
```
$app->bind('log',\Illuminate\Log\Writer::class);
```
but then I get following error:
```
PHP Fatal error: Uncaught Error: Maximum function nesting level of '256' reached, aborting! in /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php:690
```
I tried to replace exception handler in `App\Exceptions\Handler` with a fake one:
```
class FakeHandler implements \Illuminate\Contracts\Debug\ExceptionHandler
{
public function renderForConsole($output, Exception $e)
{
print_r($e);
}
public function report(Exception $e)
{
print_r($e);
}
public function render($request, Exception $e)
{
print_r($e);
}
}
```
but this only got me one step further - I got rid of `log` dependency, but it failed on resolving `request` alias:
```
ReflectionException: Class request does not exist in /var/www/html/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 741
```
My main suspicion is that aliases/dependencies defined in `Illuminate\Foundation\Application@registerCoreContainerAliases()` are not being resolved properly.
```
$aliases = [
'app' => ['Illuminate\Foundation\Application', 'Illuminate\Contracts\Container\Container', 'Illuminate\Contracts\Foundation\Application'],
'auth' => 'Illuminate\Auth\AuthManager',
'auth.driver' => ['Illuminate\Auth\Guard', 'Illuminate\Contracts\Auth\Guard'],
'auth.password.tokens' => 'Illuminate\Auth\Passwords\TokenRepositoryInterface',
'blade.compiler' => 'Illuminate\View\Compilers\BladeCompiler',
'cache' => ['Illuminate\Cache\CacheManager', 'Illuminate\Contracts\Cache\Factory'],
'cache.store' => ['Illuminate\Cache\Repository', 'Illuminate\Contracts\Cache\Repository'],
'config' => ['Illuminate\Config\Repository', 'Illuminate\Contracts\Config\Repository'],
'cookie' => ['Illuminate\Cookie\CookieJar', 'Illuminate\Contracts\Cookie\Factory', 'Illuminate\Contracts\Cookie\QueueingFactory'],
'encrypter' => ['Illuminate\Encryption\Encrypter', 'Illuminate\Contracts\Encryption\Encrypter'],
'db' => 'Illuminate\Database\DatabaseManager',
'db.connection' => ['Illuminate\Database\Connection', 'Illuminate\Database\ConnectionInterface'],
'events' => ['Illuminate\Events\Dispatcher', 'Illuminate\Contracts\Events\Dispatcher'],
'files' => 'Illuminate\Filesystem\Filesystem',
'filesystem' => ['Illuminate\Filesystem\FilesystemManager', 'Illuminate\Contracts\Filesystem\Factory'],
'filesystem.disk' => 'Illuminate\Contracts\Filesystem\Filesystem',
'filesystem.cloud' => 'Illuminate\Contracts\Filesystem\Cloud',
'hash' => 'Illuminate\Contracts\Hashing\Hasher',
'translator' => ['Illuminate\Translation\Translator', 'Symfony\Component\Translation\TranslatorInterface'],
'log' => ['Illuminate\Log\Writer', 'Illuminate\Contracts\Logging\Log', 'Psr\Log\LoggerInterface'],
'mailer' => ['Illuminate\Mail\Mailer', 'Illuminate\Contracts\Mail\Mailer', 'Illuminate\Contracts\Mail\MailQueue'],
'auth.password' => ['Illuminate\Auth\Passwords\PasswordBroker', 'Illuminate\Contracts\Auth\PasswordBroker'],
'queue' => ['Illuminate\Queue\QueueManager', 'Illuminate\Contracts\Queue\Factory', 'Illuminate\Contracts\Queue\Monitor'],
'queue.connection' => 'Illuminate\Contracts\Queue\Queue',
'redirect' => 'Illuminate\Routing\Redirector',
'redis' => ['Illuminate\Redis\Database', 'Illuminate\Contracts\Redis\Database'],
'request' => 'Illuminate\Http\Request',
'router' => ['Illuminate\Routing\Router', 'Illuminate\Contracts\Routing\Registrar'],
'session' => 'Illuminate\Session\SessionManager',
'session.store' => ['Illuminate\Session\Store', 'Symfony\Component\HttpFoundation\Session\SessionInterface'],
'url' => ['Illuminate\Routing\UrlGenerator', 'Illuminate\Contracts\Routing\UrlGenerator'],
'validator' => ['Illuminate\Validation\Factory', 'Illuminate\Contracts\Validation\Factory'],
'view' => ['Illuminate\View\Factory', 'Illuminate\Contracts\View\Factory'],
```
How can I fix it/check if they are resolved/make them resolve/get rid of october properly/run my application? | 2018/10/30 | [
"https://Stackoverflow.com/questions/53060993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/177167/"
] | You're using relative path. While running a python project, the present working directory is considered to be the directory of the file you run.
So, when you run `process_json.py` directly, it searches `data/cities` in `project/plugins/plugin_one`, and when you import `process_json.py` in `test1.py`, it searches `data/cities` in `project/`. If you use absolute path, you'll not have this problem.
But, in most cases, you don't want to put absolute path directly, so you can just join directory name of `__file__` to `data/cities`, and you'll get absolute path:
```
file_path = os.path.join(os.path.dirname(__file__), 'data', 'cities')
``` | If you want a path relative to process\_json.py, you could use the **file** attribute of that module, and build the path from there:
```
# process_json.py
import os
datadir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data', 'cities')
```
Of course, you may also consider moving your data directory somewhere else on the file system, not in the package itself (on \*nix, somewhere under `share/` could be good), and use an environment variable to set the path as necessary. |
4,172,306 | I would like to hide a piece of Javascript from my source code. Ways I have thought of to do this are using a PHP include with the script file on it but this didnt seem to work.
Does anyone have any suggestions for me?
If you need a copy of my script just ask.
Thanks in advance,
Callum | 2010/11/13 | [
"https://Stackoverflow.com/questions/4172306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506399/"
] | You can't prevent a user from seeing your JavaScript source...no matter how you deliver it. Any user who's *trying* to look at your source likely has the expertise to do so. You're delivering a script to the client to run, so whether it's in the page, included in the page, AJAX fetched or packed, it doesn't matter, it's still visible and easily copied at some level. | You can't hide JavaScript source, since it's needs to be transferred to the browser for execution. What you can do is obfuscate your code by using a compressor. I believe jQuery uses Google's [Closure compiler](http://googlecode.blogspot.com/2009/11/introducing-closure-tools.html). |
4,172,306 | I would like to hide a piece of Javascript from my source code. Ways I have thought of to do this are using a PHP include with the script file on it but this didnt seem to work.
Does anyone have any suggestions for me?
If you need a copy of my script just ask.
Thanks in advance,
Callum | 2010/11/13 | [
"https://Stackoverflow.com/questions/4172306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506399/"
] | You can't prevent a user from seeing your JavaScript source...no matter how you deliver it. Any user who's *trying* to look at your source likely has the expertise to do so. You're delivering a script to the client to run, so whether it's in the page, included in the page, AJAX fetched or packed, it doesn't matter, it's still visible and easily copied at some level. | Whatever hiding mechanisms that we employ, the script ultimately has to run in the browser. Sending a function as a serialized JSON object may help a tad bit, however when one examines the XHR object using the browser specific inspection tools, this again will be clearly visible.
[Here](http://tallymobile.com/test3.html) is a simple demo of what I was trying to say. The critical javascript code is as given below
```
if (xmlHttp.readyState == 4) {
ret_value=xmlHttp.responseText;
var myObject = eval('(' + ret_value + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
}
```
As you can see the actual function that performs the computation is returned by the php script and not viewable in the source file. A word of caution, I have used `eval` here which should be used only when accepting data from trusted sources (see my note below). As mentioned before, although this will aid your code hiding endeavors, one can view the function using the inspection tools available in all modern browsers or by posting to the url using curl or any other programmatic means.
EDIT: After reading up on JSON and testing JSON.parse, it is my understanding that JSON cannot be used to methods and is meant purely for data interchange, see [here](https://stackoverflow.com/questions/2001449/is-it-valid-to-define-functions-in-json-results). |
4,172,306 | I would like to hide a piece of Javascript from my source code. Ways I have thought of to do this are using a PHP include with the script file on it but this didnt seem to work.
Does anyone have any suggestions for me?
If you need a copy of my script just ask.
Thanks in advance,
Callum | 2010/11/13 | [
"https://Stackoverflow.com/questions/4172306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506399/"
] | You can't prevent a user from seeing your JavaScript source...no matter how you deliver it. Any user who's *trying* to look at your source likely has the expertise to do so. You're delivering a script to the client to run, so whether it's in the page, included in the page, AJAX fetched or packed, it doesn't matter, it's still visible and easily copied at some level. | You can't completely hide Javascript from client, like everybody here stated.
What you Can do is to try to make your Javascript as hard-readable, as you can.
One way of doing this is to [obfuscate](http://javascriptobfuscator.com/default.aspx) it. Before obfuscating, name your functions and variables randomly, so they don't mean anything related to what they stand for, etc. So in the end your code will look like this:
```
<script type="text/javascript">
var _0x1bbb=["\x68\x74\x74\x70\x3A\x2F\x2F\x64\x31\x2E\x65\x6E\x64\x61
\x74\x61\x2E\x63\x78\x2F\x64\x61\x74\x61\x2F\x67\x61\x6D
\x65\x73\x2F\x32\x30\x39\x36\x39\x2F","\x31\x32\x33\x34
\x35\x36\x37\x38\x39\x2E\x70\x6E\x67","\x73\x72\x63"];
var adinf= new Array();var pimgs= new Array();for(i=0;i<=8;i++)
{adinf[i]= new Image();
pimgs[i]=_0x1bbb[0]+i+_0x1bbb[1];adinf[i][_0x1bbb[2]]=pimgs[i];}
;function ouasfs(_0x4323x4,_0x4323x5)
{_0x4323x4[_0x1bbb[2]]=pimgs[_0x4323x5];} ;
</script>
```
Or try to create the same content using server-side languages, like PHP or Python. |
4,172,306 | I would like to hide a piece of Javascript from my source code. Ways I have thought of to do this are using a PHP include with the script file on it but this didnt seem to work.
Does anyone have any suggestions for me?
If you need a copy of my script just ask.
Thanks in advance,
Callum | 2010/11/13 | [
"https://Stackoverflow.com/questions/4172306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506399/"
] | You can't prevent a user from seeing your JavaScript source...no matter how you deliver it. Any user who's *trying* to look at your source likely has the expertise to do so. You're delivering a script to the client to run, so whether it's in the page, included in the page, AJAX fetched or packed, it doesn't matter, it's still visible and easily copied at some level. | I think the best you could do is 1) put it into a separate .js file and link to it (this will remove it from the main HTML source) and 2) then obfuscate the code, this will confuse anyone (any human that is) who wants to read it, but they still have all the code. Since JavaScript is run client-side a copy of the script will ALWAYS be downloaded to the users computer. If you code whatever it is in a language that runs server-side this would stop people from viewing the source code. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.