qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
72,889,304 | I'm writing a program that detects duplicate frames in h264 encoded video. I'm using the `ac-ffmpeg` crate Here's my code:
```
use std::fs::File;
use ac_ffmpeg::{
codec::{
video::{frame::Planes, VideoDecoder},
CodecParameters, Decoder,
},
format::{
demuxer::{Demuxer, DemuxerWithStreamInfo},
io::IO,
muxer::{Muxer, OutputFormat},
},
Error,
};
fn open_input(path: &str) -> Result<DemuxerWithStreamInfo<File>, Error> {
let input = File::open(path)
.map_err(|err| Error::new(format!("unable to open input file {}: {}", path, err)))?;
let io = IO::from_seekable_read_stream(input);
Demuxer::builder()
.build(io)?
.find_stream_info(None)
.map_err(|(_, err)| err)
}
fn open_output(path: &str, elementary_streams: &[CodecParameters]) -> Result<Muxer<File>, Error> {
let output_format = OutputFormat::guess_from_file_name(path)
.ok_or_else(|| Error::new(format!("unable to guess output format for file: {}", path)))?;
let output = File::create(path)
.map_err(|err| Error::new(format!("unable to create output file {}: {}", path, err)))?;
let io = IO::from_seekable_write_stream(output);
let mut muxer_builder = Muxer::builder();
for codec_parameters in elementary_streams {
muxer_builder.add_stream(codec_parameters)?;
}
muxer_builder.build(io, output_format)
}
fn plane_difference(planes1: &Planes, planes2: &Planes) -> u64 {
6
}
fn remove_duplicate_frames(input: &str, output: &str) -> Result<(), Error> {
let mut demuxer = open_input(input)?;
let (stream_index, (stream, _)) = demuxer
.streams()
.iter()
.map(|stream| (stream, stream.codec_parameters()))
.enumerate()
.find(|(_, (_, params))| params.is_video_codec())
.ok_or_else(|| Error::new("no video stream"))?;
let mut decoder = VideoDecoder::from_stream(stream)?.build()?;
let mut packet_count = 0;
let mut prev_planes: Option<Planes> = None;
let mut diffs = Vec::<(i64, u64)>::new();
while let Some(packet) = demuxer.take()? {
if packet.stream_index() != stream_index {
continue;
}
decoder.push(packet.clone())?;
if let Some(frame) = decoder.take()? {
let planes = frame.planes();
match prev_planes {
Some(prev) => {
let diff = plane_difference(&planes, &prev);
diffs.push((packet.dts().timestamp() / 1000, diff));
}
None => (),
};
prev_planes = Some(planes);
}
if packet_count > 2000 {
break;
}
packet_count += 1;
}
diffs.sort_by(|a, b| b.1.cmp(&a.1));
dbg!(diffs);
Ok(())
}
```
with dependency `ac-ffmpeg = "0.17.4"`.
The problem is this gives an error that `frame` does not live long enough:
```
error[E0597]: `frame` does not live long enough
--> src/main.rs:106:26
|
106 | let planes = frame.planes();
| ^^^^^^^^^^^^^^ borrowed value does not live long enough
107 |
108 | match prev_planes {
| ----------- borrow later used here
...
117 | }
| - `frame` dropped here while still borrowed
```
My understanding of this error is that `frame` is borrowed, which via `planes` ends up in `prev_planes`. But at the end of every loop the value is dropped so it doesn't exist for the next iteration. Is that correct? And how can I solve that? I tried cloning various things in this code but I'm not able to fix the error. | 2022/07/06 | [
"https://Stackoverflow.com/questions/72889304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8422322/"
]
| You need to keep the *frame* itself from one loop iteration to the next instead of the planes. So have a `prev_frame` variable instead of `prev_planes`:
```
let mut prev_frame = None;
let mut diffs = Vec::<(i64, u64)>::new();
while let Some(packet) = demuxer.take()? {
if packet.stream_index() != stream_index {
continue;
}
decoder.push(packet.clone())?;
if let Some(frame) = decoder.take()? {
let planes = frame.planes();
match prev_frame {
Some(prev) => {
let diff = plane_difference(&planes, &prev.planes());
diffs.push((packet.dts().timestamp() / 1000, diff));
}
None => (),
};
prev_frame = Some(frame);
}
}
``` | It's a bit tricky to reproduce this, so I'll try to answer from the top of my head.
Did you try:
```rust
let planes = frame.planes().to_owned();
```
Mainly you're giving ownership of `planes` (i.e. the child), while the parent (`frame`) goes out of scope.
Why `to_owned`? (if the child is a ref, clone will return a ref, so we use `to_owned` instead since it converts a ref type to an owned type where it's allowed to transfer ownership.
The solution *should be* either:
```rust
let planes = frame.planes().to_owned(); // line 106
```
or
```rust
prev_planes = Some(planes.clone()); // line 116
```
If none of these work, try updating your question with their outputs. It'll make it easier to answer. |
72,889,304 | I'm writing a program that detects duplicate frames in h264 encoded video. I'm using the `ac-ffmpeg` crate Here's my code:
```
use std::fs::File;
use ac_ffmpeg::{
codec::{
video::{frame::Planes, VideoDecoder},
CodecParameters, Decoder,
},
format::{
demuxer::{Demuxer, DemuxerWithStreamInfo},
io::IO,
muxer::{Muxer, OutputFormat},
},
Error,
};
fn open_input(path: &str) -> Result<DemuxerWithStreamInfo<File>, Error> {
let input = File::open(path)
.map_err(|err| Error::new(format!("unable to open input file {}: {}", path, err)))?;
let io = IO::from_seekable_read_stream(input);
Demuxer::builder()
.build(io)?
.find_stream_info(None)
.map_err(|(_, err)| err)
}
fn open_output(path: &str, elementary_streams: &[CodecParameters]) -> Result<Muxer<File>, Error> {
let output_format = OutputFormat::guess_from_file_name(path)
.ok_or_else(|| Error::new(format!("unable to guess output format for file: {}", path)))?;
let output = File::create(path)
.map_err(|err| Error::new(format!("unable to create output file {}: {}", path, err)))?;
let io = IO::from_seekable_write_stream(output);
let mut muxer_builder = Muxer::builder();
for codec_parameters in elementary_streams {
muxer_builder.add_stream(codec_parameters)?;
}
muxer_builder.build(io, output_format)
}
fn plane_difference(planes1: &Planes, planes2: &Planes) -> u64 {
6
}
fn remove_duplicate_frames(input: &str, output: &str) -> Result<(), Error> {
let mut demuxer = open_input(input)?;
let (stream_index, (stream, _)) = demuxer
.streams()
.iter()
.map(|stream| (stream, stream.codec_parameters()))
.enumerate()
.find(|(_, (_, params))| params.is_video_codec())
.ok_or_else(|| Error::new("no video stream"))?;
let mut decoder = VideoDecoder::from_stream(stream)?.build()?;
let mut packet_count = 0;
let mut prev_planes: Option<Planes> = None;
let mut diffs = Vec::<(i64, u64)>::new();
while let Some(packet) = demuxer.take()? {
if packet.stream_index() != stream_index {
continue;
}
decoder.push(packet.clone())?;
if let Some(frame) = decoder.take()? {
let planes = frame.planes();
match prev_planes {
Some(prev) => {
let diff = plane_difference(&planes, &prev);
diffs.push((packet.dts().timestamp() / 1000, diff));
}
None => (),
};
prev_planes = Some(planes);
}
if packet_count > 2000 {
break;
}
packet_count += 1;
}
diffs.sort_by(|a, b| b.1.cmp(&a.1));
dbg!(diffs);
Ok(())
}
```
with dependency `ac-ffmpeg = "0.17.4"`.
The problem is this gives an error that `frame` does not live long enough:
```
error[E0597]: `frame` does not live long enough
--> src/main.rs:106:26
|
106 | let planes = frame.planes();
| ^^^^^^^^^^^^^^ borrowed value does not live long enough
107 |
108 | match prev_planes {
| ----------- borrow later used here
...
117 | }
| - `frame` dropped here while still borrowed
```
My understanding of this error is that `frame` is borrowed, which via `planes` ends up in `prev_planes`. But at the end of every loop the value is dropped so it doesn't exist for the next iteration. Is that correct? And how can I solve that? I tried cloning various things in this code but I'm not able to fix the error. | 2022/07/06 | [
"https://Stackoverflow.com/questions/72889304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8422322/"
]
| [VideoFrame](https://docs.rs/ac-ffmpeg/0.17.4/ac_ffmpeg/codec/video/frame/struct.VideoFrame.html) doesn't allow you to *take* the planes, it only allows you to *borrow* them from the `frame`.
You can see that because a lifetime is attached to the planes:
```rust
pub fn planes(&self) -> Planes<'_>
```
The `'_` lifetime says it's identical to the lifetime of the `&self` reference, meaning it is borrowed from `self`.
If you want to store the `planes`, store the `frame` that contains them instead:
```rust
use std::fs::File;
use ac_ffmpeg::{
codec::{
video::{frame::Planes, VideoDecoder, VideoFrame},
CodecParameters, Decoder,
},
format::{
demuxer::{Demuxer, DemuxerWithStreamInfo},
io::IO,
muxer::{Muxer, OutputFormat},
},
Error,
};
fn open_input(path: &str) -> Result<DemuxerWithStreamInfo<File>, Error> {
let input = File::open(path)
.map_err(|err| Error::new(format!("unable to open input file {}: {}", path, err)))?;
let io = IO::from_seekable_read_stream(input);
Demuxer::builder()
.build(io)?
.find_stream_info(None)
.map_err(|(_, err)| err)
}
fn open_output(path: &str, elementary_streams: &[CodecParameters]) -> Result<Muxer<File>, Error> {
let output_format = OutputFormat::guess_from_file_name(path)
.ok_or_else(|| Error::new(format!("unable to guess output format for file: {}", path)))?;
let output = File::create(path)
.map_err(|err| Error::new(format!("unable to create output file {}: {}", path, err)))?;
let io = IO::from_seekable_write_stream(output);
let mut muxer_builder = Muxer::builder();
for codec_parameters in elementary_streams {
muxer_builder.add_stream(codec_parameters)?;
}
muxer_builder.build(io, output_format)
}
fn plane_difference(planes1: &Planes, planes2: &Planes) -> u64 {
6
}
fn remove_duplicate_frames(input: &str, output: &str) -> Result<(), Error> {
let mut demuxer = open_input(input)?;
let (stream_index, (stream, _)) = demuxer
.streams()
.iter()
.map(|stream| (stream, stream.codec_parameters()))
.enumerate()
.find(|(_, (_, params))| params.is_video_codec())
.ok_or_else(|| Error::new("no video stream"))?;
let mut decoder = VideoDecoder::from_stream(stream)?.build()?;
let mut packet_count = 0;
let mut prev_frame: Option<VideoFrame> = None;
let mut diffs = Vec::<(i64, u64)>::new();
while let Some(packet) = demuxer.take()? {
if packet.stream_index() != stream_index {
continue;
}
decoder.push(packet.clone())?;
if let Some(frame) = decoder.take()? {
let planes = frame.planes();
match prev_frame {
Some(prev) => {
let diff = plane_difference(&planes, &prev.planes());
diffs.push((packet.dts().timestamp() / 1000, diff));
}
None => (),
};
prev_frame = Some(frame);
}
if packet_count > 2000 {
break;
}
packet_count += 1;
}
diffs.sort_by(|a, b| b.1.cmp(&a.1));
dbg!(diffs);
Ok(())
}
``` | It's a bit tricky to reproduce this, so I'll try to answer from the top of my head.
Did you try:
```rust
let planes = frame.planes().to_owned();
```
Mainly you're giving ownership of `planes` (i.e. the child), while the parent (`frame`) goes out of scope.
Why `to_owned`? (if the child is a ref, clone will return a ref, so we use `to_owned` instead since it converts a ref type to an owned type where it's allowed to transfer ownership.
The solution *should be* either:
```rust
let planes = frame.planes().to_owned(); // line 106
```
or
```rust
prev_planes = Some(planes.clone()); // line 116
```
If none of these work, try updating your question with their outputs. It'll make it easier to answer. |
72,889,304 | I'm writing a program that detects duplicate frames in h264 encoded video. I'm using the `ac-ffmpeg` crate Here's my code:
```
use std::fs::File;
use ac_ffmpeg::{
codec::{
video::{frame::Planes, VideoDecoder},
CodecParameters, Decoder,
},
format::{
demuxer::{Demuxer, DemuxerWithStreamInfo},
io::IO,
muxer::{Muxer, OutputFormat},
},
Error,
};
fn open_input(path: &str) -> Result<DemuxerWithStreamInfo<File>, Error> {
let input = File::open(path)
.map_err(|err| Error::new(format!("unable to open input file {}: {}", path, err)))?;
let io = IO::from_seekable_read_stream(input);
Demuxer::builder()
.build(io)?
.find_stream_info(None)
.map_err(|(_, err)| err)
}
fn open_output(path: &str, elementary_streams: &[CodecParameters]) -> Result<Muxer<File>, Error> {
let output_format = OutputFormat::guess_from_file_name(path)
.ok_or_else(|| Error::new(format!("unable to guess output format for file: {}", path)))?;
let output = File::create(path)
.map_err(|err| Error::new(format!("unable to create output file {}: {}", path, err)))?;
let io = IO::from_seekable_write_stream(output);
let mut muxer_builder = Muxer::builder();
for codec_parameters in elementary_streams {
muxer_builder.add_stream(codec_parameters)?;
}
muxer_builder.build(io, output_format)
}
fn plane_difference(planes1: &Planes, planes2: &Planes) -> u64 {
6
}
fn remove_duplicate_frames(input: &str, output: &str) -> Result<(), Error> {
let mut demuxer = open_input(input)?;
let (stream_index, (stream, _)) = demuxer
.streams()
.iter()
.map(|stream| (stream, stream.codec_parameters()))
.enumerate()
.find(|(_, (_, params))| params.is_video_codec())
.ok_or_else(|| Error::new("no video stream"))?;
let mut decoder = VideoDecoder::from_stream(stream)?.build()?;
let mut packet_count = 0;
let mut prev_planes: Option<Planes> = None;
let mut diffs = Vec::<(i64, u64)>::new();
while let Some(packet) = demuxer.take()? {
if packet.stream_index() != stream_index {
continue;
}
decoder.push(packet.clone())?;
if let Some(frame) = decoder.take()? {
let planes = frame.planes();
match prev_planes {
Some(prev) => {
let diff = plane_difference(&planes, &prev);
diffs.push((packet.dts().timestamp() / 1000, diff));
}
None => (),
};
prev_planes = Some(planes);
}
if packet_count > 2000 {
break;
}
packet_count += 1;
}
diffs.sort_by(|a, b| b.1.cmp(&a.1));
dbg!(diffs);
Ok(())
}
```
with dependency `ac-ffmpeg = "0.17.4"`.
The problem is this gives an error that `frame` does not live long enough:
```
error[E0597]: `frame` does not live long enough
--> src/main.rs:106:26
|
106 | let planes = frame.planes();
| ^^^^^^^^^^^^^^ borrowed value does not live long enough
107 |
108 | match prev_planes {
| ----------- borrow later used here
...
117 | }
| - `frame` dropped here while still borrowed
```
My understanding of this error is that `frame` is borrowed, which via `planes` ends up in `prev_planes`. But at the end of every loop the value is dropped so it doesn't exist for the next iteration. Is that correct? And how can I solve that? I tried cloning various things in this code but I'm not able to fix the error. | 2022/07/06 | [
"https://Stackoverflow.com/questions/72889304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8422322/"
]
| [VideoFrame](https://docs.rs/ac-ffmpeg/0.17.4/ac_ffmpeg/codec/video/frame/struct.VideoFrame.html) doesn't allow you to *take* the planes, it only allows you to *borrow* them from the `frame`.
You can see that because a lifetime is attached to the planes:
```rust
pub fn planes(&self) -> Planes<'_>
```
The `'_` lifetime says it's identical to the lifetime of the `&self` reference, meaning it is borrowed from `self`.
If you want to store the `planes`, store the `frame` that contains them instead:
```rust
use std::fs::File;
use ac_ffmpeg::{
codec::{
video::{frame::Planes, VideoDecoder, VideoFrame},
CodecParameters, Decoder,
},
format::{
demuxer::{Demuxer, DemuxerWithStreamInfo},
io::IO,
muxer::{Muxer, OutputFormat},
},
Error,
};
fn open_input(path: &str) -> Result<DemuxerWithStreamInfo<File>, Error> {
let input = File::open(path)
.map_err(|err| Error::new(format!("unable to open input file {}: {}", path, err)))?;
let io = IO::from_seekable_read_stream(input);
Demuxer::builder()
.build(io)?
.find_stream_info(None)
.map_err(|(_, err)| err)
}
fn open_output(path: &str, elementary_streams: &[CodecParameters]) -> Result<Muxer<File>, Error> {
let output_format = OutputFormat::guess_from_file_name(path)
.ok_or_else(|| Error::new(format!("unable to guess output format for file: {}", path)))?;
let output = File::create(path)
.map_err(|err| Error::new(format!("unable to create output file {}: {}", path, err)))?;
let io = IO::from_seekable_write_stream(output);
let mut muxer_builder = Muxer::builder();
for codec_parameters in elementary_streams {
muxer_builder.add_stream(codec_parameters)?;
}
muxer_builder.build(io, output_format)
}
fn plane_difference(planes1: &Planes, planes2: &Planes) -> u64 {
6
}
fn remove_duplicate_frames(input: &str, output: &str) -> Result<(), Error> {
let mut demuxer = open_input(input)?;
let (stream_index, (stream, _)) = demuxer
.streams()
.iter()
.map(|stream| (stream, stream.codec_parameters()))
.enumerate()
.find(|(_, (_, params))| params.is_video_codec())
.ok_or_else(|| Error::new("no video stream"))?;
let mut decoder = VideoDecoder::from_stream(stream)?.build()?;
let mut packet_count = 0;
let mut prev_frame: Option<VideoFrame> = None;
let mut diffs = Vec::<(i64, u64)>::new();
while let Some(packet) = demuxer.take()? {
if packet.stream_index() != stream_index {
continue;
}
decoder.push(packet.clone())?;
if let Some(frame) = decoder.take()? {
let planes = frame.planes();
match prev_frame {
Some(prev) => {
let diff = plane_difference(&planes, &prev.planes());
diffs.push((packet.dts().timestamp() / 1000, diff));
}
None => (),
};
prev_frame = Some(frame);
}
if packet_count > 2000 {
break;
}
packet_count += 1;
}
diffs.sort_by(|a, b| b.1.cmp(&a.1));
dbg!(diffs);
Ok(())
}
``` | You need to keep the *frame* itself from one loop iteration to the next instead of the planes. So have a `prev_frame` variable instead of `prev_planes`:
```
let mut prev_frame = None;
let mut diffs = Vec::<(i64, u64)>::new();
while let Some(packet) = demuxer.take()? {
if packet.stream_index() != stream_index {
continue;
}
decoder.push(packet.clone())?;
if let Some(frame) = decoder.take()? {
let planes = frame.planes();
match prev_frame {
Some(prev) => {
let diff = plane_difference(&planes, &prev.planes());
diffs.push((packet.dts().timestamp() / 1000, diff));
}
None => (),
};
prev_frame = Some(frame);
}
}
``` |
42,253,645 | I have a HTML table with several rows. In each row there is a question (text) in the first column, and 3 radio buttons to answer Yes, No, or N/A, in the 2nd, 3rd, and 4th columns, respectively.
I want to be able to change the font color of the text in the first column when either of the radio buttons in the same row is checked.
Other questions here in Stackoverflow refer to changing the background color of the cell where the radio button is located, but in this case I need to modify the attributes of the first column in the same row instead.
PS: You can find the dummy code to play with in [this JSBin fiddle](https://jsbin.com/xajebaxanu/edit?html,output):
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table border=1>
<tr>
<th>Question</th>
<th>Yes</th>
<th>No</th>
<th>N/A</th>
</tr>
<tr>
<td>Are you a student?</td>
<td><input type="radio" name="student"></td>
<td><input type="radio" name="student"></td>
<td><input type="radio" name="student"></td>
</tr>
</table>
</body>
</html>
```
Any tips or suggestions will be more than welcome. Thanks in advance! | 2017/02/15 | [
"https://Stackoverflow.com/questions/42253645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1062227/"
]
| You can set an event listener.
You can also get the selected value to set the color based on the value if you want.
```js
$("input[name='student']").change(function(){
console.log($(this).val());
$(this).closest('tr').children('td').first().css('color', '#455434');
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table border=1>
<tr>
<th>Question</th>
<th>Yes</th>
<th>No</th>
<th>N/A</th>
</tr>
<tr>
<td>Are you a student?</td>
<td><input value="1" type="radio" name="student"></td>
<td><input value="2" type="radio" name="student"></td>
<td><input value="3" type="radio" name="student"></td>
</tr>
</table>
``` | ```
$(document).ready(function() {
$('input[type=radio][name=student]').change(function() {
$("td:first-child").css("color", "red");
});
});
```
This could change the question in the first td cell's font colour when a radio button is selected.
If you wanted you could then add conditional statements to check which checkbox was checked and change the font color, so the text could turn red when no is selected, and green when yes is selected. |
42,253,645 | I have a HTML table with several rows. In each row there is a question (text) in the first column, and 3 radio buttons to answer Yes, No, or N/A, in the 2nd, 3rd, and 4th columns, respectively.
I want to be able to change the font color of the text in the first column when either of the radio buttons in the same row is checked.
Other questions here in Stackoverflow refer to changing the background color of the cell where the radio button is located, but in this case I need to modify the attributes of the first column in the same row instead.
PS: You can find the dummy code to play with in [this JSBin fiddle](https://jsbin.com/xajebaxanu/edit?html,output):
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<table border=1>
<tr>
<th>Question</th>
<th>Yes</th>
<th>No</th>
<th>N/A</th>
</tr>
<tr>
<td>Are you a student?</td>
<td><input type="radio" name="student"></td>
<td><input type="radio" name="student"></td>
<td><input type="radio" name="student"></td>
</tr>
</table>
</body>
</html>
```
Any tips or suggestions will be more than welcome. Thanks in advance! | 2017/02/15 | [
"https://Stackoverflow.com/questions/42253645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1062227/"
]
| You can set an event listener.
You can also get the selected value to set the color based on the value if you want.
```js
$("input[name='student']").change(function(){
console.log($(this).val());
$(this).closest('tr').children('td').first().css('color', '#455434');
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table border=1>
<tr>
<th>Question</th>
<th>Yes</th>
<th>No</th>
<th>N/A</th>
</tr>
<tr>
<td>Are you a student?</td>
<td><input value="1" type="radio" name="student"></td>
<td><input value="2" type="radio" name="student"></td>
<td><input value="3" type="radio" name="student"></td>
</tr>
</table>
``` | You can traverse the DOM to find the first column in the row that is clicked, and change the color based on which radio was selected.
Here is a [Fiddle Demo](https://jsfiddle.net/zephyr_hex/yoyppjda/).
```
$('input:radio').on('click', function() {
//clear any existing background colors in the first column
$('table tr td:first-child').css('background','transparent');
//find the index of the column that contains the clicked radio
var col = $(this).closest('td').index();
//find the first td in that row
var firstTd = $(this).closest('tr').find('td:first-child');
//set the color based on the column index of the clicked radio
var color;
switch (col) {
case 1:
color = 'red';
break;
case 2:
color = 'green';
break;
case 3:
color = 'purple';
break;
}
firstTd.css('background', color);
});
``` |
21,108,762 | I am creating setup of large data approximetly 10 GB with NSIS Script and trying to create a single setup (exe). Its giving an Error -
Internal compiler error #12345: error mmapping file (xxxxxxxxxx, xxxxxxxx) is out of range.
Note: you may have one or two (large) stale temporary file(s) left in your temporary directory (Generally this only happens on Windows 9x).
Please tell me how to solve this issue ?
Is there any other way to create a setup for this kinda situation ? | 2014/01/14 | [
"https://Stackoverflow.com/questions/21108762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1758962/"
]
| NSIS installers are limited to 2Gb.
If you absolutely need it to be one file and you want to continue to use NSIS you have to append the data to the end of the generated setup. I'm not sure I would recommend that approach but it could work if the appended data is a zip file (or some other format with the header at the end) and you use one of the NSIS zip plugins to extract at run-time... | I have used <https://sourceforge.net/projects/nsisbi/> instead of normal NSIS. It solved the problem. |
21,108,762 | I am creating setup of large data approximetly 10 GB with NSIS Script and trying to create a single setup (exe). Its giving an Error -
Internal compiler error #12345: error mmapping file (xxxxxxxxxx, xxxxxxxx) is out of range.
Note: you may have one or two (large) stale temporary file(s) left in your temporary directory (Generally this only happens on Windows 9x).
Please tell me how to solve this issue ?
Is there any other way to create a setup for this kinda situation ? | 2014/01/14 | [
"https://Stackoverflow.com/questions/21108762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1758962/"
]
| NSIS installers are limited to 2Gb.
If you absolutely need it to be one file and you want to continue to use NSIS you have to append the data to the end of the generated setup. I'm not sure I would recommend that approach but it could work if the appended data is a zip file (or some other format with the header at the end) and you use one of the NSIS zip plugins to extract at run-time... | I was using Silent Install Builder 5 and received this same error with a package installer that had LESS that 2 GB total. Once I determined that the NSIS compiler was to blame, I began experimenting with several possible solutions and here's what worked: I downloaded the newer NSISBI compiler from here <https://sourceforge.net/projects/nsisbi/> and then did these 3 steps:
1. Go to C:\Program Files (x86)\Silent Install Builder 5 and renamed the default NSIS folder to a new name.
2. Copied the NSISBI folder into the C:\Program Files (x86)\Silent Install Builder 5 directory and renamed IT to NSIS.
3. Tries to compile some large packages above and just below 2GB and the first few tries I would get missing file errors in the Silent Install Builder 5 compiling box. No worries because the missing files are in the old NSIS folder, that's why y9u don't delete it.
4. Each time find the missing file error displays, find the missing files and copy them into the same folder location in the new NSIS folder. About 3 times you will do this until there are no more errors at all and you can then include the large files without generating the "internal compiler error #12345: error mmapping file xxxx is out of range." error message. NSISBI works! |
21,108,762 | I am creating setup of large data approximetly 10 GB with NSIS Script and trying to create a single setup (exe). Its giving an Error -
Internal compiler error #12345: error mmapping file (xxxxxxxxxx, xxxxxxxx) is out of range.
Note: you may have one or two (large) stale temporary file(s) left in your temporary directory (Generally this only happens on Windows 9x).
Please tell me how to solve this issue ?
Is there any other way to create a setup for this kinda situation ? | 2014/01/14 | [
"https://Stackoverflow.com/questions/21108762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1758962/"
]
| I have used <https://sourceforge.net/projects/nsisbi/> instead of normal NSIS. It solved the problem. | I was using Silent Install Builder 5 and received this same error with a package installer that had LESS that 2 GB total. Once I determined that the NSIS compiler was to blame, I began experimenting with several possible solutions and here's what worked: I downloaded the newer NSISBI compiler from here <https://sourceforge.net/projects/nsisbi/> and then did these 3 steps:
1. Go to C:\Program Files (x86)\Silent Install Builder 5 and renamed the default NSIS folder to a new name.
2. Copied the NSISBI folder into the C:\Program Files (x86)\Silent Install Builder 5 directory and renamed IT to NSIS.
3. Tries to compile some large packages above and just below 2GB and the first few tries I would get missing file errors in the Silent Install Builder 5 compiling box. No worries because the missing files are in the old NSIS folder, that's why y9u don't delete it.
4. Each time find the missing file error displays, find the missing files and copy them into the same folder location in the new NSIS folder. About 3 times you will do this until there are no more errors at all and you can then include the large files without generating the "internal compiler error #12345: error mmapping file xxxx is out of range." error message. NSISBI works! |
50,295 | I want to create a VF page inside which I will have component, where the user will have the flexibility to change the component without touching the code of the page. Dynamic, like this:
```
<apex:page>
<!-- could be defined in a label or custom setting -->
<c:{{{customer_defined_component_name}}} />
</apex:page>
```
I tried using Custom Labels but it doen't seem to work.
My customer uses 'Sites' and this VF page is for a site page. The component is plugged into the VF, but the customer says he wants to change the component look and feel periodically.
So, the best way is to edit the component itself whenever he wants to change. But he wants to dynamically change the component itself.
**Edit**: David's answer is valid if I know what components will be switched up front. But I don't know that as the customer might change the components.
Is there a way to do this? | 2014/09/23 | [
"https://salesforce.stackexchange.com/questions/50295",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/11828/"
]
| You referred to `<c:{[email protected]} />` as the kind of solution you want. While it probably won't involve Custom Labels, you are definitely close with Dynamic Visualforce.
To do this in a package does require a number of moving parts, but the following is probably the most native-friendly and future-proof approach. And it works! Hope this gets you started:

**Inside your managed package, you would have to implement:**
VF.page (you might wanna read up on [apex:dynamicComponent tag](https://www.salesforce.com/us/developer/docs/pages/Content/pages_compref_dynamicComponent.htm))
```
<apex:page controller="PageController">
<!-- your header here -->
<apex:dynamicComponent componentValue="{!CustomComponent}" />
<!-- your footer here -->
</apex:page>
```
PageController.cls (definitely read up on [Type.forName](https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_type.htm))
```
global class PageController {
public ApexPages.Component getCustomComponent() {
//eg 'AcmeComponentProvider'
ComponentSetting__c setting = ComponentSetting__c.getValues();
//take the string that corresponds to the customer class name
Type reflector = Type.forName(setting.FullyQualifiedClassName__c);
//use the returned Type to instantiate the customer class and cast it
IComponentProvider provider = (IComponentProvider)reflector.newInstance();
//give it to the page
return provider.provideComponent();
}
}
```
IComponentProvider.cls (making sneaky use of the [ApexPages.Component](https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_pages_dynamic_components.htm) base class)
```
global interface IComponentProvider {
ApexPages.Component provideComponent();
}
```
ComponentSetting\_\_c.object

**Your customer, in their own organization, would need to implement:**
Acme.component
```
<apex:component >
<!-- special acme specific content -->
</apex:component>
```
AcmeComponentProvider.cls
```
public class AcmeComponentProvider implements IComponentProvider {
public ApexPages.Component provideComponent() {
return new Component.Acme();
}
}
```
Then you need to show them how to Manage the appropriate Custom Setting:
 | You can dynamically display/hide page block sections by having the **rendered** attribute point to true/false checkbox field (this can be editable or calculated). When the checkbox is true, the page block section displays, if false, it's hidden.
apex:pageBlockSection title="My Section Title" id="section1" **rendered=**"{!Opportunity.**My\_Section1\_Checkbox\_\_c**}"
Just add the opening and closing tags around that line |
50,295 | I want to create a VF page inside which I will have component, where the user will have the flexibility to change the component without touching the code of the page. Dynamic, like this:
```
<apex:page>
<!-- could be defined in a label or custom setting -->
<c:{{{customer_defined_component_name}}} />
</apex:page>
```
I tried using Custom Labels but it doen't seem to work.
My customer uses 'Sites' and this VF page is for a site page. The component is plugged into the VF, but the customer says he wants to change the component look and feel periodically.
So, the best way is to edit the component itself whenever he wants to change. But he wants to dynamically change the component itself.
**Edit**: David's answer is valid if I know what components will be switched up front. But I don't know that as the customer might change the components.
Is there a way to do this? | 2014/09/23 | [
"https://salesforce.stackexchange.com/questions/50295",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/11828/"
]
| You referred to `<c:{[email protected]} />` as the kind of solution you want. While it probably won't involve Custom Labels, you are definitely close with Dynamic Visualforce.
To do this in a package does require a number of moving parts, but the following is probably the most native-friendly and future-proof approach. And it works! Hope this gets you started:

**Inside your managed package, you would have to implement:**
VF.page (you might wanna read up on [apex:dynamicComponent tag](https://www.salesforce.com/us/developer/docs/pages/Content/pages_compref_dynamicComponent.htm))
```
<apex:page controller="PageController">
<!-- your header here -->
<apex:dynamicComponent componentValue="{!CustomComponent}" />
<!-- your footer here -->
</apex:page>
```
PageController.cls (definitely read up on [Type.forName](https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_type.htm))
```
global class PageController {
public ApexPages.Component getCustomComponent() {
//eg 'AcmeComponentProvider'
ComponentSetting__c setting = ComponentSetting__c.getValues();
//take the string that corresponds to the customer class name
Type reflector = Type.forName(setting.FullyQualifiedClassName__c);
//use the returned Type to instantiate the customer class and cast it
IComponentProvider provider = (IComponentProvider)reflector.newInstance();
//give it to the page
return provider.provideComponent();
}
}
```
IComponentProvider.cls (making sneaky use of the [ApexPages.Component](https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_pages_dynamic_components.htm) base class)
```
global interface IComponentProvider {
ApexPages.Component provideComponent();
}
```
ComponentSetting\_\_c.object

**Your customer, in their own organization, would need to implement:**
Acme.component
```
<apex:component >
<!-- special acme specific content -->
</apex:component>
```
AcmeComponentProvider.cls
```
public class AcmeComponentProvider implements IComponentProvider {
public ApexPages.Component provideComponent() {
return new Component.Acme();
}
}
```
Then you need to show them how to Manage the appropriate Custom Setting:
 | I would agree with David, there is a lot of capabilities with the rendered attribute, or basic HTML techniques for hiding and showing data. In addition to that, there is an an actual "Dynamic Visualforce Component"
<https://developer.salesforce.com/page/Dynamic_Visualforce_Components>
that could be leveraged to accomplish your requirement. |
378,225 | I have a MacBook Pro with a touchpad, and the only way I can figure out how to use the right click in my remote desktop session is by plugging in a mouse.
`Ctrl`-click (what I usually use for right click), doesn't work, as `ctrl` is used in Windows for other things. Is there an alternative? | 2012/01/14 | [
"https://superuser.com/questions/378225",
"https://superuser.com",
"https://superuser.com/users/113585/"
]
| **Microsoft Remote Desktop Connection Keyboard Shortcuts**
* **CTRL + SHIFT + CLICK:** Right Click (OS X)
* **CTRL + ALT + END :** Opens the Microsoft Widnows NT security dialog box.
* **ALT + PAGEUP :** Switch between programs left to right.
* **ALT + PAGEDOWN :** Switch between programs right to left.
* **ALT + INSERT :** Cycle through programs in most recently used order.
* **ALT + HOME :** Display Start Menu.
* **CTRL + ALT + BREAK :** Switch the client computer between a window and full screen.
* **ALT + DELETE :** Displays the windows menu.
* **CTRL + ALT + Minus Sign (-) :** Place a snapshot of the active window in the client the terminal server, same as PRINT SCREEN on a local computer.
* **CTRL + ALT + Plus Sign (+) :** Place a snapshot of the entire window in the client the terminal server, same as PRINT SCREEN on a local computer. | This is kind of embarrassing, but the real problem was I didn't know how to right click with a touchpad on the macbook (it was still less than a month old). Update: You can do this by clicking or tapping with both fingers at the same time. |
378,225 | I have a MacBook Pro with a touchpad, and the only way I can figure out how to use the right click in my remote desktop session is by plugging in a mouse.
`Ctrl`-click (what I usually use for right click), doesn't work, as `ctrl` is used in Windows for other things. Is there an alternative? | 2012/01/14 | [
"https://superuser.com/questions/378225",
"https://superuser.com",
"https://superuser.com/users/113585/"
]
| **Microsoft Remote Desktop Connection Keyboard Shortcuts**
* **CTRL + SHIFT + CLICK:** Right Click (OS X)
* **CTRL + ALT + END :** Opens the Microsoft Widnows NT security dialog box.
* **ALT + PAGEUP :** Switch between programs left to right.
* **ALT + PAGEDOWN :** Switch between programs right to left.
* **ALT + INSERT :** Cycle through programs in most recently used order.
* **ALT + HOME :** Display Start Menu.
* **CTRL + ALT + BREAK :** Switch the client computer between a window and full screen.
* **ALT + DELETE :** Displays the windows menu.
* **CTRL + ALT + Minus Sign (-) :** Place a snapshot of the active window in the client the terminal server, same as PRINT SCREEN on a local computer.
* **CTRL + ALT + Plus Sign (+) :** Place a snapshot of the entire window in the client the terminal server, same as PRINT SCREEN on a local computer. | Either using two finger tap, or two finger "click" (by pressing down on the touchpad). |
378,225 | I have a MacBook Pro with a touchpad, and the only way I can figure out how to use the right click in my remote desktop session is by plugging in a mouse.
`Ctrl`-click (what I usually use for right click), doesn't work, as `ctrl` is used in Windows for other things. Is there an alternative? | 2012/01/14 | [
"https://superuser.com/questions/378225",
"https://superuser.com",
"https://superuser.com/users/113585/"
]
| **Microsoft Remote Desktop Connection Keyboard Shortcuts**
* **CTRL + SHIFT + CLICK:** Right Click (OS X)
* **CTRL + ALT + END :** Opens the Microsoft Widnows NT security dialog box.
* **ALT + PAGEUP :** Switch between programs left to right.
* **ALT + PAGEDOWN :** Switch between programs right to left.
* **ALT + INSERT :** Cycle through programs in most recently used order.
* **ALT + HOME :** Display Start Menu.
* **CTRL + ALT + BREAK :** Switch the client computer between a window and full screen.
* **ALT + DELETE :** Displays the windows menu.
* **CTRL + ALT + Minus Sign (-) :** Place a snapshot of the active window in the client the terminal server, same as PRINT SCREEN on a local computer.
* **CTRL + ALT + Plus Sign (+) :** Place a snapshot of the entire window in the client the terminal server, same as PRINT SCREEN on a local computer. | I found that you can simulate the RIGHT-CLICK as follows;
use the arrow to position where you wish to right-click
then use the keyboard icon and select SHIFT and F10
When you tap the keyboard pad to disappear you hopefully will have the right-click menu you want. |
378,225 | I have a MacBook Pro with a touchpad, and the only way I can figure out how to use the right click in my remote desktop session is by plugging in a mouse.
`Ctrl`-click (what I usually use for right click), doesn't work, as `ctrl` is used in Windows for other things. Is there an alternative? | 2012/01/14 | [
"https://superuser.com/questions/378225",
"https://superuser.com",
"https://superuser.com/users/113585/"
]
| Either using two finger tap, or two finger "click" (by pressing down on the touchpad). | This is kind of embarrassing, but the real problem was I didn't know how to right click with a touchpad on the macbook (it was still less than a month old). Update: You can do this by clicking or tapping with both fingers at the same time. |
378,225 | I have a MacBook Pro with a touchpad, and the only way I can figure out how to use the right click in my remote desktop session is by plugging in a mouse.
`Ctrl`-click (what I usually use for right click), doesn't work, as `ctrl` is used in Windows for other things. Is there an alternative? | 2012/01/14 | [
"https://superuser.com/questions/378225",
"https://superuser.com",
"https://superuser.com/users/113585/"
]
| This is kind of embarrassing, but the real problem was I didn't know how to right click with a touchpad on the macbook (it was still less than a month old). Update: You can do this by clicking or tapping with both fingers at the same time. | I found that you can simulate the RIGHT-CLICK as follows;
use the arrow to position where you wish to right-click
then use the keyboard icon and select SHIFT and F10
When you tap the keyboard pad to disappear you hopefully will have the right-click menu you want. |
378,225 | I have a MacBook Pro with a touchpad, and the only way I can figure out how to use the right click in my remote desktop session is by plugging in a mouse.
`Ctrl`-click (what I usually use for right click), doesn't work, as `ctrl` is used in Windows for other things. Is there an alternative? | 2012/01/14 | [
"https://superuser.com/questions/378225",
"https://superuser.com",
"https://superuser.com/users/113585/"
]
| Either using two finger tap, or two finger "click" (by pressing down on the touchpad). | I found that you can simulate the RIGHT-CLICK as follows;
use the arrow to position where you wish to right-click
then use the keyboard icon and select SHIFT and F10
When you tap the keyboard pad to disappear you hopefully will have the right-click menu you want. |
62,307,791 | I need to install the RediSearch module on top of a GCP memorystore redis instance.
I followed the steps:
---------------------
`docker run -p 6379:6379 redislabs/redisearch:latest`
I pushed this docker image to a Kubernetes cluster and exposed the external IP. I used that external IP and the 6379 port as [configuration for my application](https://oss.redislabs.com/redisearch/java_client.html) but I'm not able to connect to RediSearch.
code:
-----
```
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.PipelineResult;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.redisearch.client.Client;
import io.redisearch.*;
public class RediSearch {
static Client client = new Client("testdoc1", "clusteripaddress", 8097);
private static final Logger LOG = LoggerFactory.getLogger(RediSearch.class);
public interface Options extends PipelineOptions {
@Description("gcp project id.")
@Default.String("XXXX")
String getProjectId();
void setProjectId(String projectId);
}
public static PipelineResult run(Options options) throws IOException {
Pipeline pipeline = Pipeline.create(options);
pipeline.apply(Create.of("test"))
.apply(ParDo.of(new DoFn<String, String>() {
private static final long serialVersionUID = 1L;
@ProcessElement
public void processElement(ProcessContext c) throws Exception {
String pubsubmsg = c.element();
Schema sc = new Schema()
.addTextField("title", 5.0)
.addTextField("body", 1.0)
.addNumericField("price");
client.createIndex(sc, Client.IndexOptions.Default());
Map<String, Object> fields = new HashMap<String, Object>();
fields.put("title", "hello world");
fields.put("body", "lorem ipsum");
fields.put("price", 800);
fields.put("price", 1337);
fields.put("price", 2000);
client.addDocument("searchdoc3", fields);
SearchResult[] res = client.searchBatch(new Query("hello world").limit(0, 5).setWithScores());
for (Document d : res[0].docs) {
LOG.info("redisearchlog{}",d.getId().startsWith("search"));
LOG.info("redisearchlog1{}",d.getProperties());
LOG.info("redisearchlog2{}",d.toString());
}
}
}));
return pipeline.run();
}
public static void main(String[] args) throws IOException {
Options options = PipelineOptionsFactory.fromArgs(args).as(Options.class);
run(options);
}
}
```
Error :
-------
```
redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at redis.clients.jedis.util.Pool.getResource(Pool.java:59)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:234)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:15)
at io.redisearch.client.Client._conn(Client.java:137)
at io.redisearch.client.Client.getAllConfig(Client.java:275)
at com.testing.redisearch.RediSearch$1.processElement(RediSearch.java:59)
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: Failed connecting to host xxxxxxxxxxx:6379
at redis.clients.jedis.Connection.connect(Connection.java:204)
at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:100)
at redis.clients.jedis.BinaryJedis.connect(BinaryJedis.java:1894)
at redis.clients.jedis.JedisFactory.makeObject(JedisFactory.java:117)
at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:889)
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:424)
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:349)
at redis.clients.jedis.util.Pool.getResource(Pool.java:50)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:234)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:15)
at io.redisearch.client.Client._conn(Client.java:137)
at io.redisearch.client.Client.getAllConfig(Client.java:275)
at com.testing.redisearch.RediSearch$1.processElement(RediSearch.java:59)
at com.testing.redisearch.RediSearch$1$DoFnInvoker.invokeProcessElement(Unknown Source)
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement(SimpleDoFnRunner.java:218)
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement(SimpleDoFnRunner.java:183)
at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement(SimpleParDoFn.java:335)
at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process(ParDoOperation.java:44)
at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process(OutputReceiver.java:49)
at org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.runReadLoop(ReadOperation.java:201)
at org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.start(ReadOperation.java:159)
at org.apache.beam.runners.dataflow.worker.util.common.worker.MapTaskExecutor.execute(MapTaskExecutor.java:77)
at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.executeWork(BatchDataflowWorker.java:411)
at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.doWork(BatchDataflowWorker.java:380)
at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.getAndPerformWork(BatchDataflowWorker.java:305)
at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.doWork(DataflowBatchWorkerHarness.java:140)
at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call(DataflowBatchWorkerHarness.java:120)
at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call(DataflowBatchWorkerHarness.java:107)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at redis.clients.jedis.Connection.connect(Connection.java:181)
... 31 more
```
Any solution is appreciated. | 2020/06/10 | [
"https://Stackoverflow.com/questions/62307791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12186339/"
]
| Since you have 2 different classes, you should have 2 neurons in your final `dense` layer, instead of the number of observations you have. The number of observations should not be specified in your neural network architecture. | Use class\_mode = 'raw' as below:
```
train_generator=datagen.flow_from_dataframe(dataframe=df,
directory="D:\\Milou",
x_col="Path",
y_col=label_names,
subset="training",
class_mode="raw",
target_size=(100,100),
batch_size=64)
``` |
62,307,791 | I need to install the RediSearch module on top of a GCP memorystore redis instance.
I followed the steps:
---------------------
`docker run -p 6379:6379 redislabs/redisearch:latest`
I pushed this docker image to a Kubernetes cluster and exposed the external IP. I used that external IP and the 6379 port as [configuration for my application](https://oss.redislabs.com/redisearch/java_client.html) but I'm not able to connect to RediSearch.
code:
-----
```
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.PipelineResult;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.redisearch.client.Client;
import io.redisearch.*;
public class RediSearch {
static Client client = new Client("testdoc1", "clusteripaddress", 8097);
private static final Logger LOG = LoggerFactory.getLogger(RediSearch.class);
public interface Options extends PipelineOptions {
@Description("gcp project id.")
@Default.String("XXXX")
String getProjectId();
void setProjectId(String projectId);
}
public static PipelineResult run(Options options) throws IOException {
Pipeline pipeline = Pipeline.create(options);
pipeline.apply(Create.of("test"))
.apply(ParDo.of(new DoFn<String, String>() {
private static final long serialVersionUID = 1L;
@ProcessElement
public void processElement(ProcessContext c) throws Exception {
String pubsubmsg = c.element();
Schema sc = new Schema()
.addTextField("title", 5.0)
.addTextField("body", 1.0)
.addNumericField("price");
client.createIndex(sc, Client.IndexOptions.Default());
Map<String, Object> fields = new HashMap<String, Object>();
fields.put("title", "hello world");
fields.put("body", "lorem ipsum");
fields.put("price", 800);
fields.put("price", 1337);
fields.put("price", 2000);
client.addDocument("searchdoc3", fields);
SearchResult[] res = client.searchBatch(new Query("hello world").limit(0, 5).setWithScores());
for (Document d : res[0].docs) {
LOG.info("redisearchlog{}",d.getId().startsWith("search"));
LOG.info("redisearchlog1{}",d.getProperties());
LOG.info("redisearchlog2{}",d.toString());
}
}
}));
return pipeline.run();
}
public static void main(String[] args) throws IOException {
Options options = PipelineOptionsFactory.fromArgs(args).as(Options.class);
run(options);
}
}
```
Error :
-------
```
redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at redis.clients.jedis.util.Pool.getResource(Pool.java:59)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:234)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:15)
at io.redisearch.client.Client._conn(Client.java:137)
at io.redisearch.client.Client.getAllConfig(Client.java:275)
at com.testing.redisearch.RediSearch$1.processElement(RediSearch.java:59)
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: Failed connecting to host xxxxxxxxxxx:6379
at redis.clients.jedis.Connection.connect(Connection.java:204)
at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:100)
at redis.clients.jedis.BinaryJedis.connect(BinaryJedis.java:1894)
at redis.clients.jedis.JedisFactory.makeObject(JedisFactory.java:117)
at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:889)
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:424)
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:349)
at redis.clients.jedis.util.Pool.getResource(Pool.java:50)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:234)
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:15)
at io.redisearch.client.Client._conn(Client.java:137)
at io.redisearch.client.Client.getAllConfig(Client.java:275)
at com.testing.redisearch.RediSearch$1.processElement(RediSearch.java:59)
at com.testing.redisearch.RediSearch$1$DoFnInvoker.invokeProcessElement(Unknown Source)
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.invokeProcessElement(SimpleDoFnRunner.java:218)
at org.apache.beam.runners.dataflow.worker.repackaged.org.apache.beam.runners.core.SimpleDoFnRunner.processElement(SimpleDoFnRunner.java:183)
at org.apache.beam.runners.dataflow.worker.SimpleParDoFn.processElement(SimpleParDoFn.java:335)
at org.apache.beam.runners.dataflow.worker.util.common.worker.ParDoOperation.process(ParDoOperation.java:44)
at org.apache.beam.runners.dataflow.worker.util.common.worker.OutputReceiver.process(OutputReceiver.java:49)
at org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.runReadLoop(ReadOperation.java:201)
at org.apache.beam.runners.dataflow.worker.util.common.worker.ReadOperation.start(ReadOperation.java:159)
at org.apache.beam.runners.dataflow.worker.util.common.worker.MapTaskExecutor.execute(MapTaskExecutor.java:77)
at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.executeWork(BatchDataflowWorker.java:411)
at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.doWork(BatchDataflowWorker.java:380)
at org.apache.beam.runners.dataflow.worker.BatchDataflowWorker.getAndPerformWork(BatchDataflowWorker.java:305)
at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.doWork(DataflowBatchWorkerHarness.java:140)
at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call(DataflowBatchWorkerHarness.java:120)
at org.apache.beam.runners.dataflow.worker.DataflowBatchWorkerHarness$WorkerThread.call(DataflowBatchWorkerHarness.java:107)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at redis.clients.jedis.Connection.connect(Connection.java:181)
... 31 more
```
Any solution is appreciated. | 2020/06/10 | [
"https://Stackoverflow.com/questions/62307791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12186339/"
]
| Since you have 2 different classes, you should have 2 neurons in your final `dense` layer, instead of the number of observations you have. The number of observations should not be specified in your neural network architecture. | you need to flatten your network before final layer, because of this unflatten input you are getting all these kind of error. In reality at the final layer you are passing multi dimensional array
```
tf.keras.layers.Flatten()
``` |
29,774,944 | How can I add big **AND** small letters in a TextView like in the image below:
**Sorry: "nuber" = "number"**
 | 2015/04/21 | [
"https://Stackoverflow.com/questions/29774944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4583267/"
]
| It looks like the button you see in the UI isn't a standard Android Button, but rather a composite View made up of two TextViews.
You should make sure that your composite View is focusable and clickable, (not the two TextViews that its made of) and provide default, focus and pressed states for this View.
```
public class MyCompositeView extends LinearLayout {
private TextView primaryTextView;
private TextView secondaryTextView;
public MyCompositeView(Context context, AttributeSet attrs) {
super(context, attrs);
super.setOrientation(HORIZONTAL);
}
@Override
public final void setOrientation(int orientation) {
if (orientation != HORIZONTAL) {
throw new IllegalArgumentException("MyCompositeView is a button-like widget, not a ViewGroup! Don't change my orientation");
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
View.inflate(getContext(), R.layout.merge_my_composite_view, this);
primaryTextView = (TextView) findViewById(R.id.my_composite_text_primary);
secondaryTextView = (TextView) findViewById(R.id.my_composite_text_secondary);
}
public void setPrimaryText(String text) {
if (valid(text)) {
primaryTextView.setVisibility(VISIBLE);
} else {
primaryTextView.setVisibility(GONE);
}
primaryTextView.setText(text);
}
private static boolean valid(String text) {
return text != null && !text.trim().isEmpty();
}
public void setSecondaryText(String text) {
if (valid(text)) {
secondaryTextView.setVisibility(VISIBLE);
} else {
secondaryTextView.setVisibility(GONE);
}
secondaryTextView.setText(text);
}
}
```
The merge layout:
```
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/my_composite_text_primary"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center" />
<TextView
android:id="@+id/my_composite_text_secondary"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center" />
</merge>
```
And you would use it as:
```
<?xml version="1.0" encoding="utf-8"?>
<com.example.MyCompositeView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
``` | You can try to use `Html.fromHtml` as:
```
button.setText(Html.fromHtml("html_code_with"));
```
instead of html\_code\_with set your html code for big text and small text. |
56,887,810 | I've got nginx to run my (node.js/react) application on the server. But I can't seem to connect to the database.
In the nginx.conf file I've added the following inside http.
```
http {
...
server {
listen 80;
server_name localhost;
...}
...}
```
And above the http section I have the following,
```
stream {
server {
listen 4000;
proxy_connect_timeout 1s;
proxy_timeout 3s;
proxy_pass stream_mongo_backend;
}
upstream stream_mongo_backend {
server 127.0.0.1:27017;
}
}
```
I start the nginx server, the application runs on localhost, opens up the login page but I can't login because it's still not connected to the database (mongodb).
I'm not sure if I've got my port numbers wrong or if I'm missing some configuration line inside nginx.conf.
EDIT: Ok, I had it wrong before. I wasn't supposed to connect to mongodb at this point. I was supposed to connect to the backend server of my application which would run at 4000. So now I've added a new location for /api/ inside http and proxied all requests to 4000. I still have one question though. I have to run my backend server separately for this to work. For the frontend I've created a folder and put all my build files in there so nginx starts up the webserver from there. Doing the same for the backend did not start up the server. Is there a way to get nginx to start the backend server as well?
Also can I get the frontend to run directly without the build files ? Like node would with npm start? | 2019/07/04 | [
"https://Stackoverflow.com/questions/56887810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11561643/"
]
| You wrote `current_profit =+finance.getProfit()` where you meant `current_profit += finance.getProfit()`. You just assign the value, with unary `+` called on it, which does nothing. The operator of adding a value to the previous value is `+=`. | The corrected method, the problem was =+, changed into +=
```
public MutableLiveData<Integer> getProfit() {
//the method getFinanceList returns a financeList of size 2 as illustrated above in the debug code.
getFinanceList();
int current_profit = 0;
for (int i = 0; i < financeList.size(); i++) {
Finance finance = financeList.get(i);
current_profit +=finance.getProfit();
}
Log.d(TAG, "getProfit: " + current_profit);
MutableLiveData<Integer> profit_data = new MutableLiveData<>();
profit_data.setValue(current_profit);
return profit_data;
}
``` |
27,204,952 | I have a list of Object **Product** :
```
public Class Product
{
public int ID { get; set; }
public string Title { get; set; }
public string Status { get; set; }
}
```
I have a list of the above product :
```
List<Product> p ;
```
I am trying to filter this List , based on Search Criteria `ID, Title, Status.`
```
Example :
Id Title Status
1 ABC OPEN
2 CDE CLOSED
3 FGH RESOLVED
4 IJK PROPOSED
5 LMN SET
6 OPQ CLOSED
7 MNO OPEN
8 STU CLOSED.
```
If Search Fields **ID 1** is entered : It should return
```
1 ABC OPEN
```
If search Fields **Status OPEN** is entered : It should return
```
1 ABC OPEN
7 MNO OPEN
```
If Search Fields **Title "MNO"** and **Status "OPEN"** are entered it should return :
**7 MNO OPEN**
If **Id = ""** and **Title = ""** and **Status = "ALL"** it should return all the elements.
I am going to bind this List of objects to an asp.net grid view.
So far the code I have is below :
```
var results = new List<Product>();
foreach (var prod in Product)
{
if (prod.ID == txtProd)
{
results.Add(prod);
}
if (prod.Title.ToUpper() == txtTitle)
{
results.Add(prod);
}
if (prod.Status.ToUpper() == strStatus)
{
results.Add(prod);
}
}
```
Can you please tell me how I can modify this code to achieve my results ? | 2014/11/29 | [
"https://Stackoverflow.com/questions/27204952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1408809/"
]
| Basically you want to use `AND` between your conditions, what you are currently doing is an OR, and you will add the same item twice when it satisfies more than one condition.
You could built a dynamic linq query based on parameters:
```
var query = Product.AsQueryable();
query = txtProd != string.Empty ? query.Where(x => x.ID == txtProd) : query;
query = txtTitle != string.Empty ? query.Where(x => x.Title == txtTitle) : query;
query = strStatus != string.Empty ? query.Where(x => x.Status == strStatus) : query;
var results = query.ToList();
``` | Try this:
```
results = p.Where(((product.ID < yourIDLowerBound) || (product.ID == yourID))
&& (string.IsNullOrEmpty(product.yourTitle) || product.Title == yourTitle)
&& (string.IsNullOrEmpty(product.yourStatus) || product.Status == yourStatus)).ToList();
``` |
27,204,952 | I have a list of Object **Product** :
```
public Class Product
{
public int ID { get; set; }
public string Title { get; set; }
public string Status { get; set; }
}
```
I have a list of the above product :
```
List<Product> p ;
```
I am trying to filter this List , based on Search Criteria `ID, Title, Status.`
```
Example :
Id Title Status
1 ABC OPEN
2 CDE CLOSED
3 FGH RESOLVED
4 IJK PROPOSED
5 LMN SET
6 OPQ CLOSED
7 MNO OPEN
8 STU CLOSED.
```
If Search Fields **ID 1** is entered : It should return
```
1 ABC OPEN
```
If search Fields **Status OPEN** is entered : It should return
```
1 ABC OPEN
7 MNO OPEN
```
If Search Fields **Title "MNO"** and **Status "OPEN"** are entered it should return :
**7 MNO OPEN**
If **Id = ""** and **Title = ""** and **Status = "ALL"** it should return all the elements.
I am going to bind this List of objects to an asp.net grid view.
So far the code I have is below :
```
var results = new List<Product>();
foreach (var prod in Product)
{
if (prod.ID == txtProd)
{
results.Add(prod);
}
if (prod.Title.ToUpper() == txtTitle)
{
results.Add(prod);
}
if (prod.Status.ToUpper() == strStatus)
{
results.Add(prod);
}
}
```
Can you please tell me how I can modify this code to achieve my results ? | 2014/11/29 | [
"https://Stackoverflow.com/questions/27204952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1408809/"
]
| Basically you want to use `AND` between your conditions, what you are currently doing is an OR, and you will add the same item twice when it satisfies more than one condition.
You could built a dynamic linq query based on parameters:
```
var query = Product.AsQueryable();
query = txtProd != string.Empty ? query.Where(x => x.ID == txtProd) : query;
query = txtTitle != string.Empty ? query.Where(x => x.Title == txtTitle) : query;
query = strStatus != string.Empty ? query.Where(x => x.Status == strStatus) : query;
var results = query.ToList();
``` | As a single Linq query it would look like this:
```
var results = p.Where(x =>
(string.IsNullOrEmpty(txtProd) || x.ID == Convert.ToInt32(txtProd))
&& (string.IsNullOrEmpty(txtTitle) || x.Title == txtTitle)
&& (string.IsNullOrEmpty(strStatus) || x.Status == strStatus)).ToList();
```
By the way, in the question the List `results` is of type `Task` and you try to add `Products`, this is not possible. |
27,204,952 | I have a list of Object **Product** :
```
public Class Product
{
public int ID { get; set; }
public string Title { get; set; }
public string Status { get; set; }
}
```
I have a list of the above product :
```
List<Product> p ;
```
I am trying to filter this List , based on Search Criteria `ID, Title, Status.`
```
Example :
Id Title Status
1 ABC OPEN
2 CDE CLOSED
3 FGH RESOLVED
4 IJK PROPOSED
5 LMN SET
6 OPQ CLOSED
7 MNO OPEN
8 STU CLOSED.
```
If Search Fields **ID 1** is entered : It should return
```
1 ABC OPEN
```
If search Fields **Status OPEN** is entered : It should return
```
1 ABC OPEN
7 MNO OPEN
```
If Search Fields **Title "MNO"** and **Status "OPEN"** are entered it should return :
**7 MNO OPEN**
If **Id = ""** and **Title = ""** and **Status = "ALL"** it should return all the elements.
I am going to bind this List of objects to an asp.net grid view.
So far the code I have is below :
```
var results = new List<Product>();
foreach (var prod in Product)
{
if (prod.ID == txtProd)
{
results.Add(prod);
}
if (prod.Title.ToUpper() == txtTitle)
{
results.Add(prod);
}
if (prod.Status.ToUpper() == strStatus)
{
results.Add(prod);
}
}
```
Can you please tell me how I can modify this code to achieve my results ? | 2014/11/29 | [
"https://Stackoverflow.com/questions/27204952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1408809/"
]
| Basically you want to use `AND` between your conditions, what you are currently doing is an OR, and you will add the same item twice when it satisfies more than one condition.
You could built a dynamic linq query based on parameters:
```
var query = Product.AsQueryable();
query = txtProd != string.Empty ? query.Where(x => x.ID == txtProd) : query;
query = txtTitle != string.Empty ? query.Where(x => x.Title == txtTitle) : query;
query = strStatus != string.Empty ? query.Where(x => x.Status == strStatus) : query;
var results = query.ToList();
``` | ```
var results = new List < Product > ();
if (strStatus == "ALL" || txtProd == "" || txtTitle == "")
results = p;
else
foreach(var prod in p) {
if (prod.ID == Int32.Parse(txtProd)) {
results.Add(prod);
}
if (prod.Title.ToUpper() == txtTitle) {
results.Add(prod);
}
if (prod.Status.ToUpper() == strStatus) {
results.Add(prod);
}
}
results = results.Distinct()
.ToList();
``` |
27,204,952 | I have a list of Object **Product** :
```
public Class Product
{
public int ID { get; set; }
public string Title { get; set; }
public string Status { get; set; }
}
```
I have a list of the above product :
```
List<Product> p ;
```
I am trying to filter this List , based on Search Criteria `ID, Title, Status.`
```
Example :
Id Title Status
1 ABC OPEN
2 CDE CLOSED
3 FGH RESOLVED
4 IJK PROPOSED
5 LMN SET
6 OPQ CLOSED
7 MNO OPEN
8 STU CLOSED.
```
If Search Fields **ID 1** is entered : It should return
```
1 ABC OPEN
```
If search Fields **Status OPEN** is entered : It should return
```
1 ABC OPEN
7 MNO OPEN
```
If Search Fields **Title "MNO"** and **Status "OPEN"** are entered it should return :
**7 MNO OPEN**
If **Id = ""** and **Title = ""** and **Status = "ALL"** it should return all the elements.
I am going to bind this List of objects to an asp.net grid view.
So far the code I have is below :
```
var results = new List<Product>();
foreach (var prod in Product)
{
if (prod.ID == txtProd)
{
results.Add(prod);
}
if (prod.Title.ToUpper() == txtTitle)
{
results.Add(prod);
}
if (prod.Status.ToUpper() == strStatus)
{
results.Add(prod);
}
}
```
Can you please tell me how I can modify this code to achieve my results ? | 2014/11/29 | [
"https://Stackoverflow.com/questions/27204952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1408809/"
]
| Basically you want to use `AND` between your conditions, what you are currently doing is an OR, and you will add the same item twice when it satisfies more than one condition.
You could built a dynamic linq query based on parameters:
```
var query = Product.AsQueryable();
query = txtProd != string.Empty ? query.Where(x => x.ID == txtProd) : query;
query = txtTitle != string.Empty ? query.Where(x => x.Title == txtTitle) : query;
query = strStatus != string.Empty ? query.Where(x => x.Status == strStatus) : query;
var results = query.ToList();
``` | How about creating a product query method. I think this meets all of requirements, I don't think any other covered the "ALL" requirement.
```
public List<Product> ProductQuery(List<Product> Products
, int? IDCriteria
, string TitleCriteria
, string StatusCriteria)
{
var query = Products.AsQueryable();
if (IDCriteria != null)
{
query.Where(x => x.ID == IDCriteria);
}
if (!String.IsNullOrEmpty(TitleCriteria))
{
query.Where(x => x.Title == TitleCriteria);
}
if (!String.IsNullOrEmpty(StatusCriteria))
{
if (StatusCriteria.Equals("all", StringComparison.CurrentCultureIgnoreCase))
{
query.Where(x => x.Status.Length > 0 || String.IsNullOrEmpty(x.Status)); //will return any status
}
else
{
query.Where(x => x.Status == StatusCriteria);
}
}
return query.ToList();
}
``` |
16,280,784 | Im in windows 7 cmd prompt,,, Im trying to instal by: `npm install node-mysql`
Im getting this:
```
C:\Program Files\nodejs>npm install node-mysql
npm http GET https://registry.npmjs.org/node-mysql
npm http 404 https://registry.npmjs.org/node-mysql
npm ERR! 404 'node-mysql' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404
npm ERR! 404 Maybe try 'npm search mysql'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.
npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "node-mysql"
npm ERR! cwd C:\Program Files\nodejs
npm ERR! node -v v0.10.4
npm ERR! npm -v 1.2.18
npm ERR! code E404
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! C:\Program Files\nodejs\npm-debug.log
npm ERR! not ok code 0
```
How to fix it? Im trying to search `npm search node-mysql`,, and I cant found it in the list | 2013/04/29 | [
"https://Stackoverflow.com/questions/16280784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1606928/"
]
| Try:
```
npm install mysql
```
Node-msql (<https://github.com/felixge/node-mysql/blob/master/package.json>) is named simply mysql in package.json and it exists under that name in npm registry. | Try
```
npm install felixge/node-mysql
```
Reference : readme.md from <https://github.com/felixge/node-mysql> |
16,280,784 | Im in windows 7 cmd prompt,,, Im trying to instal by: `npm install node-mysql`
Im getting this:
```
C:\Program Files\nodejs>npm install node-mysql
npm http GET https://registry.npmjs.org/node-mysql
npm http 404 https://registry.npmjs.org/node-mysql
npm ERR! 404 'node-mysql' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404
npm ERR! 404 Maybe try 'npm search mysql'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.
npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "node-mysql"
npm ERR! cwd C:\Program Files\nodejs
npm ERR! node -v v0.10.4
npm ERR! npm -v 1.2.18
npm ERR! code E404
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! C:\Program Files\nodejs\npm-debug.log
npm ERR! not ok code 0
```
How to fix it? Im trying to search `npm search node-mysql`,, and I cant found it in the list | 2013/04/29 | [
"https://Stackoverflow.com/questions/16280784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1606928/"
]
| Try:
```
npm install mysql
```
Node-msql (<https://github.com/felixge/node-mysql/blob/master/package.json>) is named simply mysql in package.json and it exists under that name in npm registry. | Following are the steps for adding the mysql module for node js
1 Open your command prompt
==========================
>
> type npm install g-mysql for global use.
>
>
>
It will take time. mysql module will not get installed in the nodejs module directory. Please copy the module from the administrator directory to nodejs module folder.
To check the module is installed or not please go to node js command line and type
>
> require\_resolve('mysql');
>
>
>
path to the module will be shown |
16,280,784 | Im in windows 7 cmd prompt,,, Im trying to instal by: `npm install node-mysql`
Im getting this:
```
C:\Program Files\nodejs>npm install node-mysql
npm http GET https://registry.npmjs.org/node-mysql
npm http 404 https://registry.npmjs.org/node-mysql
npm ERR! 404 'node-mysql' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404
npm ERR! 404 Maybe try 'npm search mysql'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.
npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "node-mysql"
npm ERR! cwd C:\Program Files\nodejs
npm ERR! node -v v0.10.4
npm ERR! npm -v 1.2.18
npm ERR! code E404
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! C:\Program Files\nodejs\npm-debug.log
npm ERR! not ok code 0
```
How to fix it? Im trying to search `npm search node-mysql`,, and I cant found it in the list | 2013/04/29 | [
"https://Stackoverflow.com/questions/16280784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1606928/"
]
| Try:
```
npm install mysql
```
Node-msql (<https://github.com/felixge/node-mysql/blob/master/package.json>) is named simply mysql in package.json and it exists under that name in npm registry. | Please follow the given steps, which work for me:
1. Make a folder named `mysql` in this location:
```
C:\Users\newusers\AppData\Roaming\npm\node_modules
```
2. Then run the command `npm -g install mysql` |
16,280,784 | Im in windows 7 cmd prompt,,, Im trying to instal by: `npm install node-mysql`
Im getting this:
```
C:\Program Files\nodejs>npm install node-mysql
npm http GET https://registry.npmjs.org/node-mysql
npm http 404 https://registry.npmjs.org/node-mysql
npm ERR! 404 'node-mysql' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404
npm ERR! 404 Maybe try 'npm search mysql'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.
npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "node-mysql"
npm ERR! cwd C:\Program Files\nodejs
npm ERR! node -v v0.10.4
npm ERR! npm -v 1.2.18
npm ERR! code E404
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! C:\Program Files\nodejs\npm-debug.log
npm ERR! not ok code 0
```
How to fix it? Im trying to search `npm search node-mysql`,, and I cant found it in the list | 2013/04/29 | [
"https://Stackoverflow.com/questions/16280784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1606928/"
]
| Try:
```
npm install mysql
```
Node-msql (<https://github.com/felixge/node-mysql/blob/master/package.json>) is named simply mysql in package.json and it exists under that name in npm registry. | You can use below commands to use mysql globally
```
npm install mysql -g
``` |
16,280,784 | Im in windows 7 cmd prompt,,, Im trying to instal by: `npm install node-mysql`
Im getting this:
```
C:\Program Files\nodejs>npm install node-mysql
npm http GET https://registry.npmjs.org/node-mysql
npm http 404 https://registry.npmjs.org/node-mysql
npm ERR! 404 'node-mysql' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404
npm ERR! 404 Maybe try 'npm search mysql'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.
npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "node-mysql"
npm ERR! cwd C:\Program Files\nodejs
npm ERR! node -v v0.10.4
npm ERR! npm -v 1.2.18
npm ERR! code E404
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! C:\Program Files\nodejs\npm-debug.log
npm ERR! not ok code 0
```
How to fix it? Im trying to search `npm search node-mysql`,, and I cant found it in the list | 2013/04/29 | [
"https://Stackoverflow.com/questions/16280784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1606928/"
]
| Try
```
npm install felixge/node-mysql
```
Reference : readme.md from <https://github.com/felixge/node-mysql> | You can use below commands to use mysql globally
```
npm install mysql -g
``` |
16,280,784 | Im in windows 7 cmd prompt,,, Im trying to instal by: `npm install node-mysql`
Im getting this:
```
C:\Program Files\nodejs>npm install node-mysql
npm http GET https://registry.npmjs.org/node-mysql
npm http 404 https://registry.npmjs.org/node-mysql
npm ERR! 404 'node-mysql' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404
npm ERR! 404 Maybe try 'npm search mysql'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.
npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "node-mysql"
npm ERR! cwd C:\Program Files\nodejs
npm ERR! node -v v0.10.4
npm ERR! npm -v 1.2.18
npm ERR! code E404
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! C:\Program Files\nodejs\npm-debug.log
npm ERR! not ok code 0
```
How to fix it? Im trying to search `npm search node-mysql`,, and I cant found it in the list | 2013/04/29 | [
"https://Stackoverflow.com/questions/16280784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1606928/"
]
| Following are the steps for adding the mysql module for node js
1 Open your command prompt
==========================
>
> type npm install g-mysql for global use.
>
>
>
It will take time. mysql module will not get installed in the nodejs module directory. Please copy the module from the administrator directory to nodejs module folder.
To check the module is installed or not please go to node js command line and type
>
> require\_resolve('mysql');
>
>
>
path to the module will be shown | You can use below commands to use mysql globally
```
npm install mysql -g
``` |
16,280,784 | Im in windows 7 cmd prompt,,, Im trying to instal by: `npm install node-mysql`
Im getting this:
```
C:\Program Files\nodejs>npm install node-mysql
npm http GET https://registry.npmjs.org/node-mysql
npm http 404 https://registry.npmjs.org/node-mysql
npm ERR! 404 'node-mysql' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it
npm ERR! 404
npm ERR! 404 Maybe try 'npm search mysql'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, or http url, or git url.
npm ERR! System Windows_NT 6.1.7600
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "node-mysql"
npm ERR! cwd C:\Program Files\nodejs
npm ERR! node -v v0.10.4
npm ERR! npm -v 1.2.18
npm ERR! code E404
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! C:\Program Files\nodejs\npm-debug.log
npm ERR! not ok code 0
```
How to fix it? Im trying to search `npm search node-mysql`,, and I cant found it in the list | 2013/04/29 | [
"https://Stackoverflow.com/questions/16280784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1606928/"
]
| Please follow the given steps, which work for me:
1. Make a folder named `mysql` in this location:
```
C:\Users\newusers\AppData\Roaming\npm\node_modules
```
2. Then run the command `npm -g install mysql` | You can use below commands to use mysql globally
```
npm install mysql -g
``` |
18,783,734 | i have made a small code for html form and trying to validate it with javascript but it is not working and not even giving any error...
I am not getting whats the problem behind....
i have seen [javascript simple validation not working?
here is my code..
```
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>A simple Input Form</title>
<script type="text/javascript">
function validateEmail() {
//var emailID = document.myForm.email.value;
if(!validateNonEmpty(inputField, helpText))
return false;
return validateRegEx(/^\d{2}\/\d{2}\/\d{4}$/, inputField.value, helpText,
"please enter an email address i.e. [email protected]");
}
function validatedob(inputField, helpText){
if(!validateNonEmpty(inputField, helpText))
return false;
return validateRegEx(/^\d{2}\/\d{2}\/\d{4}$/, inputField.value, helpText,
"please enter an email address i.e. [email protected]");
}
function age(){
var currentDate = new Date()
var day = currentDate.getDay()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
}
function formValidate(){
if( document.myForm.dob.value == "" )
{
alert( "Please provide your date of birth!" );
document.myForm.dob.focus() ;
return false;
}
else {
var dateformat = validatedate();
if (dateformat == false)
{
return false;
}
}
if( document.myForm.email.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.email.focus() ;
return false;
}else{
var ret = validateEmail();
if( ret == false )
{
return false;
}
}
if (document.myForm.age.value="")
{
alert("please provide your age");
document.myForm.age.focus();
return false;
}
else
{
var ageformat = validateage();
if (ageformat == false)
{
return false;
}
}
}
</script>
</head>
<body>
<div id="left">
<input type="button" value="previous">
<img src="/images/jump2" alt="Just-in-time" />
</div>
<input type="button" value="next">
<form name="myForm" method="post" action="success.html" onsubmit="formValidate();">
Date of Birth: <input id="dob" type="text" name="dob" size=10><br>
Age: <input id="age" type="text" name="age"><br>
Email: <input id="email" type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18783734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1049600/"
]
| And add `method="post"` to your `form` tag. | Change this in formValidate()
`document.myForm.Name.value == ""` to `document.myForm.dob.value == ""`
```
document.myForm.EMail.value == "" to document.myForm.email.value == ""
```
**Do not use**
```
document.write("<b>" + day + "/" + month + "/" + year + "</b>");
```
It will replace the whole contents of your body |
18,783,734 | i have made a small code for html form and trying to validate it with javascript but it is not working and not even giving any error...
I am not getting whats the problem behind....
i have seen [javascript simple validation not working?
here is my code..
```
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>A simple Input Form</title>
<script type="text/javascript">
function validateEmail() {
//var emailID = document.myForm.email.value;
if(!validateNonEmpty(inputField, helpText))
return false;
return validateRegEx(/^\d{2}\/\d{2}\/\d{4}$/, inputField.value, helpText,
"please enter an email address i.e. [email protected]");
}
function validatedob(inputField, helpText){
if(!validateNonEmpty(inputField, helpText))
return false;
return validateRegEx(/^\d{2}\/\d{2}\/\d{4}$/, inputField.value, helpText,
"please enter an email address i.e. [email protected]");
}
function age(){
var currentDate = new Date()
var day = currentDate.getDay()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
}
function formValidate(){
if( document.myForm.dob.value == "" )
{
alert( "Please provide your date of birth!" );
document.myForm.dob.focus() ;
return false;
}
else {
var dateformat = validatedate();
if (dateformat == false)
{
return false;
}
}
if( document.myForm.email.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.email.focus() ;
return false;
}else{
var ret = validateEmail();
if( ret == false )
{
return false;
}
}
if (document.myForm.age.value="")
{
alert("please provide your age");
document.myForm.age.focus();
return false;
}
else
{
var ageformat = validateage();
if (ageformat == false)
{
return false;
}
}
}
</script>
</head>
<body>
<div id="left">
<input type="button" value="previous">
<img src="/images/jump2" alt="Just-in-time" />
</div>
<input type="button" value="next">
<form name="myForm" method="post" action="success.html" onsubmit="formValidate();">
Date of Birth: <input id="dob" type="text" name="dob" size=10><br>
Age: <input id="age" type="text" name="age"><br>
Email: <input id="email" type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18783734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1049600/"
]
| And add `method="post"` to your `form` tag. | First of all,in your `formValidate(),`
**First** if condition is incorrect.Your form does not have a "name" element, it should either be "dob" or "age" or "value".
**Secondly**, in the second if instead of this
`if( document.myForm.EMail.value == "" )`, it should be `if( document.myForm.email.value == "" )`. |
14,565,366 | I'm trying to plot data in a barchart using lattice graphics. I'd like to sort the bars by one factor and group by another (i.e., position by the first factor and contrast within position by the second). However, I'd like to color the bars by the first (i.e., position) factor.
In the following example, the plot is rendered with paired red and blue bars. Instead, I'd like two adjacent red bars, two adjacent blue bars, and two adjacent green bars.
```
library(lattice)
data = runif( 6 )
facA = rep( c( "a", "b", "c" ), each = 2 )
facB = rep( c( "1", "2" ), 3 )
df = data.frame( "FactorA" = facA, "FactorB" = facB, "Data" = data )
df$FactorA = = as.factor( FactorA )
df$FactorB = = as.factor( FactorB )
test_colors = c( "red", "blue", "green" )
test_plot = barchart(FactorA ~ Data, groups = FactorB, data = df,
horizontal = TRUE, col = test_colors, origin = 0 )
plot( test_plot )
```
Thanks in advance! | 2013/01/28 | [
"https://Stackoverflow.com/questions/14565366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719469/"
]
| This is not perfect but I think it does the trick (if I understood correctly your question).
```
barchart( FactorB ~ Data | FactorA, data = df, groups=FactorA,
horizontal = TRUE, col = test_colors, origin = 0, layout=c(1,3))
```
`Factor B ~ Data | FactorA` means it divides your data in panels corresponding to `FactorA` and inside each of these group, split according to `FactorB`. The color follows what have been defined as the `groups`.
 | If you wanted to do this with 'ggplot2', you would write it like so:
```
ggplot(df, aes(x=FactorA, y=data, group=FactorB, fill=FactorA)) +
geom_bar(stat="identity", position="dodge") +
coord_flip()
```
From there, it's just cosmetic tailoring to suit your tastes, including picking the colors for the fill. |
115,297 | You are playing a game on the following 4x4 grid. Each turn you can slide **all** the orange balls into one of four directions: left, up, right or down. A ball will continue sliding along a direction until it hits a wall (solid blue squares), boundary of the grid or another ball. All the balls move at once. Walls do not move. Can you get the balls to finish on the target (T) cells?
[](https://i.stack.imgur.com/0hKRM.png) | 2022/03/15 | [
"https://puzzling.stackexchange.com/questions/115297",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/62537/"
]
| Is this a trick question? (New here)
Is the answer just
>
> "yes"?
>
>
>
Otherwise,
>
> up left up right
>
>
>
>
> up right up right
>
>
>
>
> down right down left
>
>
>
>
> up right down
>
>
>
>
> The trick is to "disrupt" the alignment of two balls that the instinctive approach wants to line up against the right wall.
>
>
> | @user already posted a [solution](https://puzzling.stackexchange.com/a/115298/36023), mine differs slightly at the end:
>
> ULU RURUR DR ULURD
>
>
>
(spaces inserted at the points where I was mentally switching to another task; the final 5 moves are where the solution differs from @user's)
This is what it looks like:
>
> [](https://i.stack.imgur.com/xvhsJ.gif)
>
>
> |
115,297 | You are playing a game on the following 4x4 grid. Each turn you can slide **all** the orange balls into one of four directions: left, up, right or down. A ball will continue sliding along a direction until it hits a wall (solid blue squares), boundary of the grid or another ball. All the balls move at once. Walls do not move. Can you get the balls to finish on the target (T) cells?
[](https://i.stack.imgur.com/0hKRM.png) | 2022/03/15 | [
"https://puzzling.stackexchange.com/questions/115297",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/62537/"
]
| Is this a trick question? (New here)
Is the answer just
>
> "yes"?
>
>
>
Otherwise,
>
> up left up right
>
>
>
>
> up right up right
>
>
>
>
> down right down left
>
>
>
>
> up right down
>
>
>
>
> The trick is to "disrupt" the alignment of two balls that the instinctive approach wants to line up against the right wall.
>
>
> | I have a completely different solution, the same length as the [other](https://puzzling.stackexchange.com/a/115301/79147) [two](https://puzzling.stackexchange.com/a/115298/79147) at time of posting - still 15 moves. I am wondering if there is a way to solve this in less than 15 moves.
>
> URURD LUR DRD LURD
>
>
>
After the first five moves, the grid looks like this:
>
> URURD (one of the orange balls has not moved as no left move has been made): [](https://i.stack.imgur.com/qo0Yy.png)
>
>
>
After the next three, it looks like this:
>
> LUR: [](https://i.stack.imgur.com/bLd6J.png)
>
>
>
After the next three:
>
> DRD: [](https://i.stack.imgur.com/FBDqF.png)
>
>
>
And the final four moves complete it:
>
> LURD: [](https://i.stack.imgur.com/CkKTw.png)
>
>
> |
115,297 | You are playing a game on the following 4x4 grid. Each turn you can slide **all** the orange balls into one of four directions: left, up, right or down. A ball will continue sliding along a direction until it hits a wall (solid blue squares), boundary of the grid or another ball. All the balls move at once. Walls do not move. Can you get the balls to finish on the target (T) cells?
[](https://i.stack.imgur.com/0hKRM.png) | 2022/03/15 | [
"https://puzzling.stackexchange.com/questions/115297",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/62537/"
]
| @user already posted a [solution](https://puzzling.stackexchange.com/a/115298/36023), mine differs slightly at the end:
>
> ULU RURUR DR ULURD
>
>
>
(spaces inserted at the points where I was mentally switching to another task; the final 5 moves are where the solution differs from @user's)
This is what it looks like:
>
> [](https://i.stack.imgur.com/xvhsJ.gif)
>
>
> | I have a completely different solution, the same length as the [other](https://puzzling.stackexchange.com/a/115301/79147) [two](https://puzzling.stackexchange.com/a/115298/79147) at time of posting - still 15 moves. I am wondering if there is a way to solve this in less than 15 moves.
>
> URURD LUR DRD LURD
>
>
>
After the first five moves, the grid looks like this:
>
> URURD (one of the orange balls has not moved as no left move has been made): [](https://i.stack.imgur.com/qo0Yy.png)
>
>
>
After the next three, it looks like this:
>
> LUR: [](https://i.stack.imgur.com/bLd6J.png)
>
>
>
After the next three:
>
> DRD: [](https://i.stack.imgur.com/FBDqF.png)
>
>
>
And the final four moves complete it:
>
> LURD: [](https://i.stack.imgur.com/CkKTw.png)
>
>
> |
38,627,184 | When viewing VCS window in Pycharm IDE, I have no idea what *git local branch* I'm working on as well as its mapped *git remote branch*.
So how to show **current working branch name** in Pycharm?
p.s.
I'm using PyCharm Community Edition 2016.2 | 2016/07/28 | [
"https://Stackoverflow.com/questions/38627184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248616/"
]
| Local Working Branch
====================
The section "[Which branch we are working in?](https://confluence.jetbrains.com/display/PYH/Using+PyCharm%27s+Git+integration+locally#UsingPyCharm%27sGitintegrationlocally-Whichbranchweareworkingin?)" is quite clear:
>
> Actually, this information is available in the Logs tab, but there are two another ways to see the current branch.
>
>
> First, there is a special command on the main menu VCS→Git→Branches. The pop-up window of existing branches appears
>
>
>
[](https://i.stack.imgur.com/CO2kE.png)
>
> Second (and most handy) is to use the **Git widget in the Status bar**:
>
>
>
[](https://i.stack.imgur.com/4W9CK.png)
Remote mapped branch
====================
The remote tracking branch though, does not seem to be displayed, except when you are pushing the branch via menu *VCS - Git - Push*
[](https://i.stack.imgur.com/NBGYO.jpg)
For that, a `git branch -avv` in command line remains the most complete source of information. | A small update to the wonderful answer by @VonC: there is an option to show the git branch in the git widget in the bottom of the screen. It's called `Show Git Branch` and you can turn it on either using the command lookup or from `View > Appearance > Status Bar Widgets > Git Branch`.
[](https://i.stack.imgur.com/X19iu.png) |
19,139,001 | I have got a strange problem with the styling of my pivot control.
I edited a copy of the default template in Expression Blend because I want to remove the entire header.
The adapted style:
```
<Style x:Key="PivotWithoutHeader" TargetType="phone:Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="phone:Pivot">
<Grid HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Background="{TemplateBinding Background}" Grid.RowSpan="3"/>
<!--<ContentControl ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" HorizontalAlignment="Left" Margin="24,17,0,-7" Style="{StaticResource PivotTitleStyle}"/>-->
<Primitives:PivotHeadersControl x:Name="HeadersListElement" Grid.Row="1"/>
<ItemsPresenter x:Name="PivotItemPresenter" Margin="{TemplateBinding Padding}" Grid.Row="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
And the usage of my style:
```
<phone:Pivot Grid.Row="1" x:Name="Objects" ItemsSource="{Binding Profiles}"
Style="{StaticResource PivotWithoutHeader}">
<phone:Pivot.ItemContainerStyle>
<Style TargetType="phone:PivotItem">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</phone:Pivot.ItemContainerStyle>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="Resources/homer.png"/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="#Sample" />
<Button Margin="347,0,0,0" Command="{Binding DataContext.SettingsCommand, ElementName=Objects}" CommandParameter="{Binding .}" />
</Grid>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
```
My thought was just to remove or set the visibility of `<Primitives:PivotHeadersControl>` to collapsed but then my app crashes without any exception and the following message in my output window: "The program '[2332] TaskHost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'" appears.
I read some posts to move up the pivot so that the header is out of the screen but I need my customized pivot at the bottom of my page with some other controls above it.
Does anybody have an idea how to remove the header?
**EDIT:** For clarity I want to remove title and header. | 2013/10/02 | [
"https://Stackoverflow.com/questions/19139001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211299/"
]
| The template of the Pivot control was changed in WP8 and it now requires that the `PivotHeadersControl` be present in the template. (You could remove it in WP7.x)
Just have a zero height or other "empty" content in your header instead.
I'm not aware of this having been publically documented as most people who've upgraded to WP8 are using the shim to the old version of the control. However, I Noted this at the end of a blog article at <http://blog.mrlacey.co.uk/2013/01/pivot-and-panorama-have-moved-and.html> | dBlisse's solution worked for me to hide the header template but for title I played with margins and the below trick worked for me, not sure if this is a good idea, but checked on different resolutions and looks fine.
Notice the `Margin="0,-39,0,0"` for stack panel below:
```
<phone:Pivot Background="Transparent" Margin="-12,0">
<phone:Pivot.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,-39,0,0">
YOUR CONTROLS HERE
</StackPanel>
</DataTemplate>
</phone:Pivot.ItemTemplate>
<phone:Pivot.HeaderTemplate>
<DataTemplate/>
</phone:Pivot.HeaderTemplate>
</phone:Pivot>
``` |
19,139,001 | I have got a strange problem with the styling of my pivot control.
I edited a copy of the default template in Expression Blend because I want to remove the entire header.
The adapted style:
```
<Style x:Key="PivotWithoutHeader" TargetType="phone:Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="phone:Pivot">
<Grid HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Background="{TemplateBinding Background}" Grid.RowSpan="3"/>
<!--<ContentControl ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" HorizontalAlignment="Left" Margin="24,17,0,-7" Style="{StaticResource PivotTitleStyle}"/>-->
<Primitives:PivotHeadersControl x:Name="HeadersListElement" Grid.Row="1"/>
<ItemsPresenter x:Name="PivotItemPresenter" Margin="{TemplateBinding Padding}" Grid.Row="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
And the usage of my style:
```
<phone:Pivot Grid.Row="1" x:Name="Objects" ItemsSource="{Binding Profiles}"
Style="{StaticResource PivotWithoutHeader}">
<phone:Pivot.ItemContainerStyle>
<Style TargetType="phone:PivotItem">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</phone:Pivot.ItemContainerStyle>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="Resources/homer.png"/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="#Sample" />
<Button Margin="347,0,0,0" Command="{Binding DataContext.SettingsCommand, ElementName=Objects}" CommandParameter="{Binding .}" />
</Grid>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
```
My thought was just to remove or set the visibility of `<Primitives:PivotHeadersControl>` to collapsed but then my app crashes without any exception and the following message in my output window: "The program '[2332] TaskHost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'" appears.
I read some posts to move up the pivot so that the header is out of the screen but I need my customized pivot at the bottom of my page with some other controls above it.
Does anybody have an idea how to remove the header?
**EDIT:** For clarity I want to remove title and header. | 2013/10/02 | [
"https://Stackoverflow.com/questions/19139001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211299/"
]
| Try this one:
```
<UserControl.Resources>
<ResourceDictionary>
<Thickness x:Key="PivotPortraitThemePadding">0,0,0,0</Thickness>
<Thickness x:Key="PivotLandscapeThemePadding">0,0,0,0</Thickness>
<Style x:Key="PivotWithoutHeaderStyle" TargetType="Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{ThemeResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Pivot">
<Grid x:Name="RootElement" Background="{TemplateBinding Background}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="Orientation">
<VisualState x:Name="Portrait">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Margin" Storyboard.TargetName="TitleContentControl">
<DiscreteObjectKeyFrame KeyTime="0" Value="0"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Landscape">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Margin" Storyboard.TargetName="TitleContentControl">
<DiscreteObjectKeyFrame KeyTime="0" Value="0"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ContentControl x:Name="TitleContentControl" ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" Style="{StaticResource PivotTitleContentControlStyle}" Height="0"/>
<ScrollViewer x:Name="ScrollViewer" HorizontalSnapPointsAlignment="Center" HorizontalSnapPointsType="MandatorySingle" HorizontalScrollBarVisibility="Hidden" Margin="0" Grid.Row="1" Template="{StaticResource ScrollViewerScrollBarlessTemplate}" VerticalSnapPointsType="None" VerticalScrollBarVisibility="Disabled" VerticalScrollMode="Disabled" VerticalContentAlignment="Stretch" ZoomMode="Disabled">
<PivotPanel x:Name="Panel" VerticalAlignment="Stretch">
<PivotHeaderPanel x:Name="Header" Background="{TemplateBinding BorderBrush}" Height="0" Margin="0" Visibility="Collapsed">
<PivotHeaderPanel.RenderTransform>
<CompositeTransform x:Name="HeaderTranslateTransform" TranslateX="0"/>
</PivotHeaderPanel.RenderTransform>
</PivotHeaderPanel>
<ItemsPresenter x:Name="PivotItemPresenter">
<ItemsPresenter.RenderTransform>
<TranslateTransform x:Name="ItemsPresenterTranslateTransform" X="0"/>
</ItemsPresenter.RenderTransform>
</ItemsPresenter>
</PivotPanel>
</ScrollViewer>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</UserControl.Resources>
```
...
```
<Pivot Style="{StaticResource PivotWithoutHeaderStyle}">
```
... | dBlisse's solution worked for me to hide the header template but for title I played with margins and the below trick worked for me, not sure if this is a good idea, but checked on different resolutions and looks fine.
Notice the `Margin="0,-39,0,0"` for stack panel below:
```
<phone:Pivot Background="Transparent" Margin="-12,0">
<phone:Pivot.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,-39,0,0">
YOUR CONTROLS HERE
</StackPanel>
</DataTemplate>
</phone:Pivot.ItemTemplate>
<phone:Pivot.HeaderTemplate>
<DataTemplate/>
</phone:Pivot.HeaderTemplate>
</phone:Pivot>
``` |
19,139,001 | I have got a strange problem with the styling of my pivot control.
I edited a copy of the default template in Expression Blend because I want to remove the entire header.
The adapted style:
```
<Style x:Key="PivotWithoutHeader" TargetType="phone:Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="phone:Pivot">
<Grid HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Background="{TemplateBinding Background}" Grid.RowSpan="3"/>
<!--<ContentControl ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" HorizontalAlignment="Left" Margin="24,17,0,-7" Style="{StaticResource PivotTitleStyle}"/>-->
<Primitives:PivotHeadersControl x:Name="HeadersListElement" Grid.Row="1"/>
<ItemsPresenter x:Name="PivotItemPresenter" Margin="{TemplateBinding Padding}" Grid.Row="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
And the usage of my style:
```
<phone:Pivot Grid.Row="1" x:Name="Objects" ItemsSource="{Binding Profiles}"
Style="{StaticResource PivotWithoutHeader}">
<phone:Pivot.ItemContainerStyle>
<Style TargetType="phone:PivotItem">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</phone:Pivot.ItemContainerStyle>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="Resources/homer.png"/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="#Sample" />
<Button Margin="347,0,0,0" Command="{Binding DataContext.SettingsCommand, ElementName=Objects}" CommandParameter="{Binding .}" />
</Grid>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
```
My thought was just to remove or set the visibility of `<Primitives:PivotHeadersControl>` to collapsed but then my app crashes without any exception and the following message in my output window: "The program '[2332] TaskHost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'" appears.
I read some posts to move up the pivot so that the header is out of the screen but I need my customized pivot at the bottom of my page with some other controls above it.
Does anybody have an idea how to remove the header?
**EDIT:** For clarity I want to remove title and header. | 2013/10/02 | [
"https://Stackoverflow.com/questions/19139001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211299/"
]
| You can remove the PivotItem header on the Pivot Control by replacing the Pivot.HeaderTemplate property with a blank DataTemplate. If you're trying to remove the Title rather than the Header, then I would like to know the solution too. ^^
```
<phone:Pivot ItemsSource="{Binding Data}" ItemTemplate="{StaticResource CustomPivotItemTemplate}">
<phone:Pivot.HeaderTemplate>
<DataTemplate/>
</phone:Pivot.HeaderTemplate>
</phone:Pivot>
``` | So removing the header AND the title doesn't work anymore on Windows Phone 8.
So I ported an existing control from: <http://www.codeproject.com/Articles/136786/Creating-an-Animated-ContentControl> to Windows Phone 8. |
19,139,001 | I have got a strange problem with the styling of my pivot control.
I edited a copy of the default template in Expression Blend because I want to remove the entire header.
The adapted style:
```
<Style x:Key="PivotWithoutHeader" TargetType="phone:Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="phone:Pivot">
<Grid HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Background="{TemplateBinding Background}" Grid.RowSpan="3"/>
<!--<ContentControl ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" HorizontalAlignment="Left" Margin="24,17,0,-7" Style="{StaticResource PivotTitleStyle}"/>-->
<Primitives:PivotHeadersControl x:Name="HeadersListElement" Grid.Row="1"/>
<ItemsPresenter x:Name="PivotItemPresenter" Margin="{TemplateBinding Padding}" Grid.Row="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
And the usage of my style:
```
<phone:Pivot Grid.Row="1" x:Name="Objects" ItemsSource="{Binding Profiles}"
Style="{StaticResource PivotWithoutHeader}">
<phone:Pivot.ItemContainerStyle>
<Style TargetType="phone:PivotItem">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</phone:Pivot.ItemContainerStyle>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="Resources/homer.png"/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="#Sample" />
<Button Margin="347,0,0,0" Command="{Binding DataContext.SettingsCommand, ElementName=Objects}" CommandParameter="{Binding .}" />
</Grid>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
```
My thought was just to remove or set the visibility of `<Primitives:PivotHeadersControl>` to collapsed but then my app crashes without any exception and the following message in my output window: "The program '[2332] TaskHost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'" appears.
I read some posts to move up the pivot so that the header is out of the screen but I need my customized pivot at the bottom of my page with some other controls above it.
Does anybody have an idea how to remove the header?
**EDIT:** For clarity I want to remove title and header. | 2013/10/02 | [
"https://Stackoverflow.com/questions/19139001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211299/"
]
| So removing the header AND the title doesn't work anymore on Windows Phone 8.
So I ported an existing control from: <http://www.codeproject.com/Articles/136786/Creating-an-Animated-ContentControl> to Windows Phone 8. | I finally figured it out! (I'm building a Universal Windows 10 App and had the same question.)
Add a blank HeaderTemplate to your Pivot controls as dBlisse suggested:
```
<Pivot ItemsPanel="{StaticResource ItemsPanelTemplate1}">
<Pivot.HeaderTemplate>
<DataTemplate/>
</Pivot.HeaderTemplate>
</Pivot>
```
And add this template in App.xaml:
```
<ItemsPanelTemplate x:Key="ItemsPanelTemplate1">
<Grid Margin="0,-48,0,0"/>
</ItemsPanelTemplate>
``` |
19,139,001 | I have got a strange problem with the styling of my pivot control.
I edited a copy of the default template in Expression Blend because I want to remove the entire header.
The adapted style:
```
<Style x:Key="PivotWithoutHeader" TargetType="phone:Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="phone:Pivot">
<Grid HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Background="{TemplateBinding Background}" Grid.RowSpan="3"/>
<!--<ContentControl ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" HorizontalAlignment="Left" Margin="24,17,0,-7" Style="{StaticResource PivotTitleStyle}"/>-->
<Primitives:PivotHeadersControl x:Name="HeadersListElement" Grid.Row="1"/>
<ItemsPresenter x:Name="PivotItemPresenter" Margin="{TemplateBinding Padding}" Grid.Row="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
And the usage of my style:
```
<phone:Pivot Grid.Row="1" x:Name="Objects" ItemsSource="{Binding Profiles}"
Style="{StaticResource PivotWithoutHeader}">
<phone:Pivot.ItemContainerStyle>
<Style TargetType="phone:PivotItem">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</phone:Pivot.ItemContainerStyle>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="Resources/homer.png"/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="#Sample" />
<Button Margin="347,0,0,0" Command="{Binding DataContext.SettingsCommand, ElementName=Objects}" CommandParameter="{Binding .}" />
</Grid>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
```
My thought was just to remove or set the visibility of `<Primitives:PivotHeadersControl>` to collapsed but then my app crashes without any exception and the following message in my output window: "The program '[2332] TaskHost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'" appears.
I read some posts to move up the pivot so that the header is out of the screen but I need my customized pivot at the bottom of my page with some other controls above it.
Does anybody have an idea how to remove the header?
**EDIT:** For clarity I want to remove title and header. | 2013/10/02 | [
"https://Stackoverflow.com/questions/19139001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211299/"
]
| Try this one:
```
<UserControl.Resources>
<ResourceDictionary>
<Thickness x:Key="PivotPortraitThemePadding">0,0,0,0</Thickness>
<Thickness x:Key="PivotLandscapeThemePadding">0,0,0,0</Thickness>
<Style x:Key="PivotWithoutHeaderStyle" TargetType="Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{ThemeResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Pivot">
<Grid x:Name="RootElement" Background="{TemplateBinding Background}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="Orientation">
<VisualState x:Name="Portrait">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Margin" Storyboard.TargetName="TitleContentControl">
<DiscreteObjectKeyFrame KeyTime="0" Value="0"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Landscape">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Margin" Storyboard.TargetName="TitleContentControl">
<DiscreteObjectKeyFrame KeyTime="0" Value="0"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ContentControl x:Name="TitleContentControl" ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" Style="{StaticResource PivotTitleContentControlStyle}" Height="0"/>
<ScrollViewer x:Name="ScrollViewer" HorizontalSnapPointsAlignment="Center" HorizontalSnapPointsType="MandatorySingle" HorizontalScrollBarVisibility="Hidden" Margin="0" Grid.Row="1" Template="{StaticResource ScrollViewerScrollBarlessTemplate}" VerticalSnapPointsType="None" VerticalScrollBarVisibility="Disabled" VerticalScrollMode="Disabled" VerticalContentAlignment="Stretch" ZoomMode="Disabled">
<PivotPanel x:Name="Panel" VerticalAlignment="Stretch">
<PivotHeaderPanel x:Name="Header" Background="{TemplateBinding BorderBrush}" Height="0" Margin="0" Visibility="Collapsed">
<PivotHeaderPanel.RenderTransform>
<CompositeTransform x:Name="HeaderTranslateTransform" TranslateX="0"/>
</PivotHeaderPanel.RenderTransform>
</PivotHeaderPanel>
<ItemsPresenter x:Name="PivotItemPresenter">
<ItemsPresenter.RenderTransform>
<TranslateTransform x:Name="ItemsPresenterTranslateTransform" X="0"/>
</ItemsPresenter.RenderTransform>
</ItemsPresenter>
</PivotPanel>
</ScrollViewer>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</UserControl.Resources>
```
...
```
<Pivot Style="{StaticResource PivotWithoutHeaderStyle}">
```
... | I finally figured it out! (I'm building a Universal Windows 10 App and had the same question.)
Add a blank HeaderTemplate to your Pivot controls as dBlisse suggested:
```
<Pivot ItemsPanel="{StaticResource ItemsPanelTemplate1}">
<Pivot.HeaderTemplate>
<DataTemplate/>
</Pivot.HeaderTemplate>
</Pivot>
```
And add this template in App.xaml:
```
<ItemsPanelTemplate x:Key="ItemsPanelTemplate1">
<Grid Margin="0,-48,0,0"/>
</ItemsPanelTemplate>
``` |
19,139,001 | I have got a strange problem with the styling of my pivot control.
I edited a copy of the default template in Expression Blend because I want to remove the entire header.
The adapted style:
```
<Style x:Key="PivotWithoutHeader" TargetType="phone:Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="phone:Pivot">
<Grid HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Background="{TemplateBinding Background}" Grid.RowSpan="3"/>
<!--<ContentControl ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" HorizontalAlignment="Left" Margin="24,17,0,-7" Style="{StaticResource PivotTitleStyle}"/>-->
<Primitives:PivotHeadersControl x:Name="HeadersListElement" Grid.Row="1"/>
<ItemsPresenter x:Name="PivotItemPresenter" Margin="{TemplateBinding Padding}" Grid.Row="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
And the usage of my style:
```
<phone:Pivot Grid.Row="1" x:Name="Objects" ItemsSource="{Binding Profiles}"
Style="{StaticResource PivotWithoutHeader}">
<phone:Pivot.ItemContainerStyle>
<Style TargetType="phone:PivotItem">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</phone:Pivot.ItemContainerStyle>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="Resources/homer.png"/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="#Sample" />
<Button Margin="347,0,0,0" Command="{Binding DataContext.SettingsCommand, ElementName=Objects}" CommandParameter="{Binding .}" />
</Grid>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
```
My thought was just to remove or set the visibility of `<Primitives:PivotHeadersControl>` to collapsed but then my app crashes without any exception and the following message in my output window: "The program '[2332] TaskHost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'" appears.
I read some posts to move up the pivot so that the header is out of the screen but I need my customized pivot at the bottom of my page with some other controls above it.
Does anybody have an idea how to remove the header?
**EDIT:** For clarity I want to remove title and header. | 2013/10/02 | [
"https://Stackoverflow.com/questions/19139001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211299/"
]
| You can remove the PivotItem header on the Pivot Control by replacing the Pivot.HeaderTemplate property with a blank DataTemplate. If you're trying to remove the Title rather than the Header, then I would like to know the solution too. ^^
```
<phone:Pivot ItemsSource="{Binding Data}" ItemTemplate="{StaticResource CustomPivotItemTemplate}">
<phone:Pivot.HeaderTemplate>
<DataTemplate/>
</phone:Pivot.HeaderTemplate>
</phone:Pivot>
``` | dBlisse's solution worked for me to hide the header template but for title I played with margins and the below trick worked for me, not sure if this is a good idea, but checked on different resolutions and looks fine.
Notice the `Margin="0,-39,0,0"` for stack panel below:
```
<phone:Pivot Background="Transparent" Margin="-12,0">
<phone:Pivot.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,-39,0,0">
YOUR CONTROLS HERE
</StackPanel>
</DataTemplate>
</phone:Pivot.ItemTemplate>
<phone:Pivot.HeaderTemplate>
<DataTemplate/>
</phone:Pivot.HeaderTemplate>
</phone:Pivot>
``` |
19,139,001 | I have got a strange problem with the styling of my pivot control.
I edited a copy of the default template in Expression Blend because I want to remove the entire header.
The adapted style:
```
<Style x:Key="PivotWithoutHeader" TargetType="phone:Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="phone:Pivot">
<Grid HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Background="{TemplateBinding Background}" Grid.RowSpan="3"/>
<!--<ContentControl ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" HorizontalAlignment="Left" Margin="24,17,0,-7" Style="{StaticResource PivotTitleStyle}"/>-->
<Primitives:PivotHeadersControl x:Name="HeadersListElement" Grid.Row="1"/>
<ItemsPresenter x:Name="PivotItemPresenter" Margin="{TemplateBinding Padding}" Grid.Row="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
And the usage of my style:
```
<phone:Pivot Grid.Row="1" x:Name="Objects" ItemsSource="{Binding Profiles}"
Style="{StaticResource PivotWithoutHeader}">
<phone:Pivot.ItemContainerStyle>
<Style TargetType="phone:PivotItem">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</phone:Pivot.ItemContainerStyle>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="Resources/homer.png"/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="#Sample" />
<Button Margin="347,0,0,0" Command="{Binding DataContext.SettingsCommand, ElementName=Objects}" CommandParameter="{Binding .}" />
</Grid>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
```
My thought was just to remove or set the visibility of `<Primitives:PivotHeadersControl>` to collapsed but then my app crashes without any exception and the following message in my output window: "The program '[2332] TaskHost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'" appears.
I read some posts to move up the pivot so that the header is out of the screen but I need my customized pivot at the bottom of my page with some other controls above it.
Does anybody have an idea how to remove the header?
**EDIT:** For clarity I want to remove title and header. | 2013/10/02 | [
"https://Stackoverflow.com/questions/19139001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211299/"
]
| The template of the Pivot control was changed in WP8 and it now requires that the `PivotHeadersControl` be present in the template. (You could remove it in WP7.x)
Just have a zero height or other "empty" content in your header instead.
I'm not aware of this having been publically documented as most people who've upgraded to WP8 are using the shim to the old version of the control. However, I Noted this at the end of a blog article at <http://blog.mrlacey.co.uk/2013/01/pivot-and-panorama-have-moved-and.html> | I finally figured it out! (I'm building a Universal Windows 10 App and had the same question.)
Add a blank HeaderTemplate to your Pivot controls as dBlisse suggested:
```
<Pivot ItemsPanel="{StaticResource ItemsPanelTemplate1}">
<Pivot.HeaderTemplate>
<DataTemplate/>
</Pivot.HeaderTemplate>
</Pivot>
```
And add this template in App.xaml:
```
<ItemsPanelTemplate x:Key="ItemsPanelTemplate1">
<Grid Margin="0,-48,0,0"/>
</ItemsPanelTemplate>
``` |
19,139,001 | I have got a strange problem with the styling of my pivot control.
I edited a copy of the default template in Expression Blend because I want to remove the entire header.
The adapted style:
```
<Style x:Key="PivotWithoutHeader" TargetType="phone:Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="phone:Pivot">
<Grid HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Background="{TemplateBinding Background}" Grid.RowSpan="3"/>
<!--<ContentControl ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" HorizontalAlignment="Left" Margin="24,17,0,-7" Style="{StaticResource PivotTitleStyle}"/>-->
<Primitives:PivotHeadersControl x:Name="HeadersListElement" Grid.Row="1"/>
<ItemsPresenter x:Name="PivotItemPresenter" Margin="{TemplateBinding Padding}" Grid.Row="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
And the usage of my style:
```
<phone:Pivot Grid.Row="1" x:Name="Objects" ItemsSource="{Binding Profiles}"
Style="{StaticResource PivotWithoutHeader}">
<phone:Pivot.ItemContainerStyle>
<Style TargetType="phone:PivotItem">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</phone:Pivot.ItemContainerStyle>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="Resources/homer.png"/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="#Sample" />
<Button Margin="347,0,0,0" Command="{Binding DataContext.SettingsCommand, ElementName=Objects}" CommandParameter="{Binding .}" />
</Grid>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
```
My thought was just to remove or set the visibility of `<Primitives:PivotHeadersControl>` to collapsed but then my app crashes without any exception and the following message in my output window: "The program '[2332] TaskHost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'" appears.
I read some posts to move up the pivot so that the header is out of the screen but I need my customized pivot at the bottom of my page with some other controls above it.
Does anybody have an idea how to remove the header?
**EDIT:** For clarity I want to remove title and header. | 2013/10/02 | [
"https://Stackoverflow.com/questions/19139001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211299/"
]
| You can remove the PivotItem header on the Pivot Control by replacing the Pivot.HeaderTemplate property with a blank DataTemplate. If you're trying to remove the Title rather than the Header, then I would like to know the solution too. ^^
```
<phone:Pivot ItemsSource="{Binding Data}" ItemTemplate="{StaticResource CustomPivotItemTemplate}">
<phone:Pivot.HeaderTemplate>
<DataTemplate/>
</phone:Pivot.HeaderTemplate>
</phone:Pivot>
``` | The template of the Pivot control was changed in WP8 and it now requires that the `PivotHeadersControl` be present in the template. (You could remove it in WP7.x)
Just have a zero height or other "empty" content in your header instead.
I'm not aware of this having been publically documented as most people who've upgraded to WP8 are using the shim to the old version of the control. However, I Noted this at the end of a blog article at <http://blog.mrlacey.co.uk/2013/01/pivot-and-panorama-have-moved-and.html> |
19,139,001 | I have got a strange problem with the styling of my pivot control.
I edited a copy of the default template in Expression Blend because I want to remove the entire header.
The adapted style:
```
<Style x:Key="PivotWithoutHeader" TargetType="phone:Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="phone:Pivot">
<Grid HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Background="{TemplateBinding Background}" Grid.RowSpan="3"/>
<!--<ContentControl ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" HorizontalAlignment="Left" Margin="24,17,0,-7" Style="{StaticResource PivotTitleStyle}"/>-->
<Primitives:PivotHeadersControl x:Name="HeadersListElement" Grid.Row="1"/>
<ItemsPresenter x:Name="PivotItemPresenter" Margin="{TemplateBinding Padding}" Grid.Row="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
And the usage of my style:
```
<phone:Pivot Grid.Row="1" x:Name="Objects" ItemsSource="{Binding Profiles}"
Style="{StaticResource PivotWithoutHeader}">
<phone:Pivot.ItemContainerStyle>
<Style TargetType="phone:PivotItem">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</phone:Pivot.ItemContainerStyle>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="Resources/homer.png"/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="#Sample" />
<Button Margin="347,0,0,0" Command="{Binding DataContext.SettingsCommand, ElementName=Objects}" CommandParameter="{Binding .}" />
</Grid>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
```
My thought was just to remove or set the visibility of `<Primitives:PivotHeadersControl>` to collapsed but then my app crashes without any exception and the following message in my output window: "The program '[2332] TaskHost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'" appears.
I read some posts to move up the pivot so that the header is out of the screen but I need my customized pivot at the bottom of my page with some other controls above it.
Does anybody have an idea how to remove the header?
**EDIT:** For clarity I want to remove title and header. | 2013/10/02 | [
"https://Stackoverflow.com/questions/19139001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211299/"
]
| You can remove the PivotItem header on the Pivot Control by replacing the Pivot.HeaderTemplate property with a blank DataTemplate. If you're trying to remove the Title rather than the Header, then I would like to know the solution too. ^^
```
<phone:Pivot ItemsSource="{Binding Data}" ItemTemplate="{StaticResource CustomPivotItemTemplate}">
<phone:Pivot.HeaderTemplate>
<DataTemplate/>
</phone:Pivot.HeaderTemplate>
</phone:Pivot>
``` | Try this one:
```
<UserControl.Resources>
<ResourceDictionary>
<Thickness x:Key="PivotPortraitThemePadding">0,0,0,0</Thickness>
<Thickness x:Key="PivotLandscapeThemePadding">0,0,0,0</Thickness>
<Style x:Key="PivotWithoutHeaderStyle" TargetType="Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{ThemeResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Pivot">
<Grid x:Name="RootElement" Background="{TemplateBinding Background}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="Orientation">
<VisualState x:Name="Portrait">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Margin" Storyboard.TargetName="TitleContentControl">
<DiscreteObjectKeyFrame KeyTime="0" Value="0"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Landscape">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Margin" Storyboard.TargetName="TitleContentControl">
<DiscreteObjectKeyFrame KeyTime="0" Value="0"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ContentControl x:Name="TitleContentControl" ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" Style="{StaticResource PivotTitleContentControlStyle}" Height="0"/>
<ScrollViewer x:Name="ScrollViewer" HorizontalSnapPointsAlignment="Center" HorizontalSnapPointsType="MandatorySingle" HorizontalScrollBarVisibility="Hidden" Margin="0" Grid.Row="1" Template="{StaticResource ScrollViewerScrollBarlessTemplate}" VerticalSnapPointsType="None" VerticalScrollBarVisibility="Disabled" VerticalScrollMode="Disabled" VerticalContentAlignment="Stretch" ZoomMode="Disabled">
<PivotPanel x:Name="Panel" VerticalAlignment="Stretch">
<PivotHeaderPanel x:Name="Header" Background="{TemplateBinding BorderBrush}" Height="0" Margin="0" Visibility="Collapsed">
<PivotHeaderPanel.RenderTransform>
<CompositeTransform x:Name="HeaderTranslateTransform" TranslateX="0"/>
</PivotHeaderPanel.RenderTransform>
</PivotHeaderPanel>
<ItemsPresenter x:Name="PivotItemPresenter">
<ItemsPresenter.RenderTransform>
<TranslateTransform x:Name="ItemsPresenterTranslateTransform" X="0"/>
</ItemsPresenter.RenderTransform>
</ItemsPresenter>
</PivotPanel>
</ScrollViewer>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
</UserControl.Resources>
```
...
```
<Pivot Style="{StaticResource PivotWithoutHeaderStyle}">
```
... |
19,139,001 | I have got a strange problem with the styling of my pivot control.
I edited a copy of the default template in Expression Blend because I want to remove the entire header.
The adapted style:
```
<Style x:Key="PivotWithoutHeader" TargetType="phone:Pivot">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="phone:Pivot">
<Grid HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Background="{TemplateBinding Background}" Grid.RowSpan="3"/>
<!--<ContentControl ContentTemplate="{TemplateBinding TitleTemplate}" Content="{TemplateBinding Title}" HorizontalAlignment="Left" Margin="24,17,0,-7" Style="{StaticResource PivotTitleStyle}"/>-->
<Primitives:PivotHeadersControl x:Name="HeadersListElement" Grid.Row="1"/>
<ItemsPresenter x:Name="PivotItemPresenter" Margin="{TemplateBinding Padding}" Grid.Row="2"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
And the usage of my style:
```
<phone:Pivot Grid.Row="1" x:Name="Objects" ItemsSource="{Binding Profiles}"
Style="{StaticResource PivotWithoutHeader}">
<phone:Pivot.ItemContainerStyle>
<Style TargetType="phone:PivotItem">
<Setter Property="HorizontalAlignment" Value="Stretch" />
</Style>
</phone:Pivot.ItemContainerStyle>
<phone:Pivot.ItemTemplate>
<DataTemplate>
<Grid>
<Image Source="Resources/homer.png"/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="#Sample" />
<Button Margin="347,0,0,0" Command="{Binding DataContext.SettingsCommand, ElementName=Objects}" CommandParameter="{Binding .}" />
</Grid>
</DataTemplate>
</phone:Pivot.ItemTemplate>
</phone:Pivot>
```
My thought was just to remove or set the visibility of `<Primitives:PivotHeadersControl>` to collapsed but then my app crashes without any exception and the following message in my output window: "The program '[2332] TaskHost.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'" appears.
I read some posts to move up the pivot so that the header is out of the screen but I need my customized pivot at the bottom of my page with some other controls above it.
Does anybody have an idea how to remove the header?
**EDIT:** For clarity I want to remove title and header. | 2013/10/02 | [
"https://Stackoverflow.com/questions/19139001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1211299/"
]
| So removing the header AND the title doesn't work anymore on Windows Phone 8.
So I ported an existing control from: <http://www.codeproject.com/Articles/136786/Creating-an-Animated-ContentControl> to Windows Phone 8. | dBlisse's solution worked for me to hide the header template but for title I played with margins and the below trick worked for me, not sure if this is a good idea, but checked on different resolutions and looks fine.
Notice the `Margin="0,-39,0,0"` for stack panel below:
```
<phone:Pivot Background="Transparent" Margin="-12,0">
<phone:Pivot.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,-39,0,0">
YOUR CONTROLS HERE
</StackPanel>
</DataTemplate>
</phone:Pivot.ItemTemplate>
<phone:Pivot.HeaderTemplate>
<DataTemplate/>
</phone:Pivot.HeaderTemplate>
</phone:Pivot>
``` |
307,916 | I've just installed a fresh install of WordPress and before doing anything else I've tried to setup a multisite, which I would like to do with subdirectories.
But when I click on Network Setup I get the notification:
>
> Because your installation is not new, the sites in your WordPress
> network must use sub-domains. The main site in a sub-directory
> installation will need to use a modified permalink structure,
> potentially breaking existing links.
>
>
>
Can anyone tell me what I'm doing wrong, or what I need to change to allow subdirectories? | 2018/07/07 | [
"https://wordpress.stackexchange.com/questions/307916",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59568/"
]
| You don't need to do anything just past this code in your activated theme's `functions.php`
```
add_filter( 'allow_subdirectory_install', '__return_true' );
``` | [This thread](https://premium.wpmudev.org/forums/topic/enabling-network-because-your-install-is-not-new-the-sites-in-your-wordpress-network-must-use-sub-domains) might be helpful.
In essence: try to delete sample post and page. |
51,180,359 | I have an array:
```
let numbers = [8,4,2,1,7,5,3,0];
```
I want to send this array to the client using socket.emit.
But when i send this data using:
```
var numbers1 = JSON.stringify(numbers);
socket.emit('new',{num:numbers1});
```
And listen it on the client side using:
```
socket.on('new',(data)=>{
var aa = data.num ;
console.log(aa);
});
```
It says undefined on the DevTools for the console of aa.
Edit
====
I had written an incomplete code.
The complete client side code is:
```
socket.on('new',(data)=>{
var numbers = JSON.parse(data.num); //this will retrieve your array.
console.log(numbers);
```
});
It says as the error
```
VM42:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
```
which means the data which is trying to parse is undefined. | 2018/07/04 | [
"https://Stackoverflow.com/questions/51180359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10033940/"
]
| OK so I found this, which says it's not possible at the moment:
<https://github.com/aws/aws-lambda-dotnet/issues/246>
Am moving to NodeJs and the Serverless package to do this for now:
<https://www.npmjs.com/package/serverless>
Will update this if / when things change for dotnet core | processId it should be set to 1, because Docker assigns entry point executable PID of 1. It is in launch.json of VS Code. |
15,375,987 | I need to search a string for a list of several different matches, let's say I have this list:
```
['this', 'is', 'a', 'regex', 'test']
```
I want to see if any of those items is within a string, either using regex or any other method in Python.
I tried first just doing `string in list`, but that proved to be insufficient, so I tried concatenating the conditions in a regex like:
```
(this|is)(a|regex)(text)
```
But that tries to match several of the items as if they were concatenated. | 2013/03/13 | [
"https://Stackoverflow.com/questions/15375987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478108/"
]
| You can use the built-in function `any()`:
```
In [1]: strs="I am a string"
In [2]: lis=['this', 'is', 'a', 'regex', 'test']
In [3]: any(x in strs for x in lis)
Out[3]: True
```
This will return `True` for something like `"thisisafoobar"` as well.
But if you want to match the exact word, then try `re.search()` or `str.split()`:
```
In [4]: import re
In [5]: any(re.search(r"\b{0}\b".format(x),strs) for x in lis)
Out[5]: True
In [6]: strs="foo bar"
In [7]: any(re.search(r"\b{0}\b".format(x),strs) for x in lis)
Out[7]: False
```
Using `str.split()`:
```
In [12]: strs="I am a string"
In [13]: spl=strs.split() #use set(strs.split()) if the list returned is huge
In [14]: any(x in spl for x in lis)
Out[14]: True
In [15]: strs="Iamastring"
In [16]: spl=strs.split()
In [17]: any(x in spl for x in lis)
Out[17]: False
``` | You could do:
```
if any(test in your_string for test in tests):
...
``` |
15,375,987 | I need to search a string for a list of several different matches, let's say I have this list:
```
['this', 'is', 'a', 'regex', 'test']
```
I want to see if any of those items is within a string, either using regex or any other method in Python.
I tried first just doing `string in list`, but that proved to be insufficient, so I tried concatenating the conditions in a regex like:
```
(this|is)(a|regex)(text)
```
But that tries to match several of the items as if they were concatenated. | 2013/03/13 | [
"https://Stackoverflow.com/questions/15375987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478108/"
]
| ```
>>> l = ['this', 'is', 'a', 'regex', 'test']
>>> s = 'this is a test string'
>>> def check(elements, string):
... for element in elements:
... if element in string:
... return True
... return False
...
>>> check(l, s)
True
```
Apparently this function has better performance than `any()`
```
import time
def main():
# Making a huge list
l = ['this', 'is', 'a', 'regex', 'test'] * 10000
s = 'this is a test string'
def check(elements, string):
for element in elements:
if element in string:
return True
return False
def test_a(elements, string):
"""Testing check()"""
start = time.time()
check(elements, string)
end = time.time()
return end - start
def test_b(elements, string):
"""Testing any()"""
start = time.time()
any(element in string for element in elements)
end = time.time()
return end - start
print 'Using check(): %s' % test_a(l, s)
print 'Using any(): %s' % test_b(l, s)
if __name__ == '__main__':
main()
```
Results:
```
pearl:~ pato$ python test.py
Using check(): 3.09944152832e-06
Using any(): 5.96046447754e-06
pearl:~ pato$ python test.py
Using check(): 1.90734863281e-06
Using any(): 7.15255737305e-06
pearl:~ pato$ python test.py
Using check(): 2.86102294922e-06
Using any(): 6.91413879395e-06
```
But if you combine `any()` with `map()` in something like `any(map(lambda element: element in string, elements))`, these are the results:
```
pearl:~ pato$ python test.py
Using check(): 3.09944152832e-06
Using any(): 0.00903916358948
pearl:~ pato$ python test.py
Using check(): 2.86102294922e-06
Using any(): 0.00799989700317
pearl:~ pato$ python test.py
Using check(): 3.09944152832e-06
Using any(): 0.00829982757568
``` | You could do:
```
if any(test in your_string for test in tests):
...
``` |
15,375,987 | I need to search a string for a list of several different matches, let's say I have this list:
```
['this', 'is', 'a', 'regex', 'test']
```
I want to see if any of those items is within a string, either using regex or any other method in Python.
I tried first just doing `string in list`, but that proved to be insufficient, so I tried concatenating the conditions in a regex like:
```
(this|is)(a|regex)(text)
```
But that tries to match several of the items as if they were concatenated. | 2013/03/13 | [
"https://Stackoverflow.com/questions/15375987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/478108/"
]
| You can use the built-in function `any()`:
```
In [1]: strs="I am a string"
In [2]: lis=['this', 'is', 'a', 'regex', 'test']
In [3]: any(x in strs for x in lis)
Out[3]: True
```
This will return `True` for something like `"thisisafoobar"` as well.
But if you want to match the exact word, then try `re.search()` or `str.split()`:
```
In [4]: import re
In [5]: any(re.search(r"\b{0}\b".format(x),strs) for x in lis)
Out[5]: True
In [6]: strs="foo bar"
In [7]: any(re.search(r"\b{0}\b".format(x),strs) for x in lis)
Out[7]: False
```
Using `str.split()`:
```
In [12]: strs="I am a string"
In [13]: spl=strs.split() #use set(strs.split()) if the list returned is huge
In [14]: any(x in spl for x in lis)
Out[14]: True
In [15]: strs="Iamastring"
In [16]: spl=strs.split()
In [17]: any(x in spl for x in lis)
Out[17]: False
``` | ```
>>> l = ['this', 'is', 'a', 'regex', 'test']
>>> s = 'this is a test string'
>>> def check(elements, string):
... for element in elements:
... if element in string:
... return True
... return False
...
>>> check(l, s)
True
```
Apparently this function has better performance than `any()`
```
import time
def main():
# Making a huge list
l = ['this', 'is', 'a', 'regex', 'test'] * 10000
s = 'this is a test string'
def check(elements, string):
for element in elements:
if element in string:
return True
return False
def test_a(elements, string):
"""Testing check()"""
start = time.time()
check(elements, string)
end = time.time()
return end - start
def test_b(elements, string):
"""Testing any()"""
start = time.time()
any(element in string for element in elements)
end = time.time()
return end - start
print 'Using check(): %s' % test_a(l, s)
print 'Using any(): %s' % test_b(l, s)
if __name__ == '__main__':
main()
```
Results:
```
pearl:~ pato$ python test.py
Using check(): 3.09944152832e-06
Using any(): 5.96046447754e-06
pearl:~ pato$ python test.py
Using check(): 1.90734863281e-06
Using any(): 7.15255737305e-06
pearl:~ pato$ python test.py
Using check(): 2.86102294922e-06
Using any(): 6.91413879395e-06
```
But if you combine `any()` with `map()` in something like `any(map(lambda element: element in string, elements))`, these are the results:
```
pearl:~ pato$ python test.py
Using check(): 3.09944152832e-06
Using any(): 0.00903916358948
pearl:~ pato$ python test.py
Using check(): 2.86102294922e-06
Using any(): 0.00799989700317
pearl:~ pato$ python test.py
Using check(): 3.09944152832e-06
Using any(): 0.00829982757568
``` |
571,212 | Say I have a set of 10 values I want to draw 3 values from, uniformly, without replacement. For instance:
$$S = \{0,0,0,0,22.95,0,0,0,19.125,25.5\}$$
With replacement, this seems simple, you just add all the values up and divide by $10$, giving $6.7575$, and multiplying by $3$ you get $20.2725$. However, if you don't replace values, I imagine it could effect the expected value, but uncertain how to figure out the specifics.
I guess thinking about it as discrete distributions means that the distribution changes every time a value is drawn, and maybe isn't the best way to think about this problem? | 2022/04/11 | [
"https://stats.stackexchange.com/questions/571212",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/354446/"
]
| @BruceET's answer has some nice information, and simulations are often a good starting place for this sort of thing in practice. In this answer, I'll detail an exact approach, which demonstrates that the exact answer is actually $20.275$, **the same as in the sampling without replacement approach**.
Note that this is unsurprising due to the linearity of expectation and the fact that, marginally, each $X\_i$ has the same distribution in either case. Note that the variances will NOT be the same for each approach, as @BruceET points out in his answer.
---
In the sampling with replacement case, you can view each draw as an *independent* draw from the given discrete distribution $X\_1, X\_2, X\_3 \stackrel{\text{iid}}{\sim} p(x)$. In the sampling *without replacement* case, you have to consider the *joint* distribution of the random variables ${\bf X} = (X\_1, X\_2, X\_3) \sim p(x\_1, x\_2, x\_3)$. Then the expected value of $Y = X\_1 + X\_2 + X\_3$ is taken as the weighted average with weights given by $p(x\_1, x\_2, x\_3)$.
---
More generally, let $S = \{s\_1, s\_2, \ldots s\_n\}$. A general strategy for finding $E(X\_1+X\_2+X\_3)$ starts by listing all of the possible outcomes,
$$\mathcal S = \{(x\_1, x\_2, x\_3) | x\_1 = s\_i, x\_2 = s\_j, x\_3 = s\_k, i \neq j \neq k),$$
of which there are $n(n-1)(n-2)$. Since the sum doesn't care about the order in which each number is drawn, we can simplify things a bit by looking at the set of all combinations:
$$\mathcal S = \{(x\_1, x\_2, x\_3) | x\_1 = s\_i, x\_2 = s\_j, x\_3 = s\_k, i < j < k),$$
of which there are $\binom{n}{3}$ options. Then the expected value can be computed as
\begin{align\*}
E(X\_1+X\_2+X\_3) &= \sum\_{k=3}^n\sum\_{j=2}^k\sum\_{i=1}^j(s\_i + s\_j + s\_k)\times 6 \times p(s\_i, s\_j, s\_k)\\
&= \frac{6}{10\cdot9\cdot8}\sum\_{k=3}^n\sum\_{j=2}^k\sum\_{i=1}^j(s\_i + s\_j + s\_k) \\
&= \ldots \\
&= \frac{3}{n}\sum\_{i=1}^n s\_i
\end{align\*}
where the $6$ comes from the various orderings of $s\_i, s\_j, s\_k$. Since each element $s\_i (i=1,\ldots n)$ has the same probability of being selected, we have $p(s\_i, s\_j, s\_k) = \frac{1}{10\cdot 9\cdot 8}$ for each combination.
---
Example R Code
--------------
Based on a suggestion by @BruceET, this R code has been edited to compute the expected value and variance. Note that the variance is significantly smaller than the case of sampling with replacement.
```
compute_expected_value <- function(S){
n <- length(S)
E1 <- E2 <- 0
for(i in 3:n){
for(j in 2:(i-1)){
for(k in 1:(j-1)){
E1 <- E1 + 6*(S[i] + S[j] + S[k])/10/9/8
E2 <- E2 + 6*(S[i] + S[j] + S[k])^2/10/9/8
}
}
}
res <- c(E1, E2-E1^2)
names(res) <- c("mean", "variance")
return(res)
}
S <- c(0,0,0,0, 22.95, 0,0,0, 19.125,25.5)
compute_expected_value(S)
> mean variance
> 20.2725 253.4187
``` | The mean of the values in $S$ is $6.7576,$ as you say. So, with replacement, each of the three chosen values has an expected value of $6.7575$ and
thus the average of the three is again
$\bar X\_3 = 6.7575.$
```
s = c(0,0,0,0, 22.95, 0,0,0, 19.125,25.5)
mean(s)
[1] 6.7575
```
In sampling without replacement, the mean $E(\bar X\_3)= 6.7575$ and the variance $V(\bar X\_3)$ of the sample mean will be
somewhat smaller because there are fewer possible samples
of size three that may be drawn. (For example, once value $25.5$ is chosen, it can't be chosen again.)
Without working through the combinatorial detains, it
is possible to get a good idea of the sampling
distribution of $\bar X\_3$ according to each
sampling method by doing a simple simulation in R.
With 10 million iterations one can expect about three place accuracy.
```
set.seed(3033)
s = c(0,0,0,0,22.95,0,0,0,19.125,25.5)
a.wo = replicate(10^7, mean(sample(s, 4)))
mean(a.wo); sd(a.wo)
[1] 6.760266 # aprx 6.7575
[1] 4.254535
summary(a.wo)
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.000 4.781 6.375 6.760 10.519 16.894
a.with = replicate(10^7, mean(sample(s, 3, rep=T)))
mean(a.with); sd(a.with)
[1] 6.757315 # aprx 6.7575
[1] 6.017261
summary(a.with)
Min. 1st Qu. Median Mean 3rd Qu. Max.
0.000 0.000 7.650 6.757 8.500 25.500
par(mfrow=c(1,2))
hist(a.wo, prob=T, xlim=c(0,26), col="skyblue2")
hist(a.with, prob=T, xlim=c(0,26), col="skyblue2")
par(mfrow=c(1,1))
```
[](https://i.stack.imgur.com/uAyGm.png) |
571,212 | Say I have a set of 10 values I want to draw 3 values from, uniformly, without replacement. For instance:
$$S = \{0,0,0,0,22.95,0,0,0,19.125,25.5\}$$
With replacement, this seems simple, you just add all the values up and divide by $10$, giving $6.7575$, and multiplying by $3$ you get $20.2725$. However, if you don't replace values, I imagine it could effect the expected value, but uncertain how to figure out the specifics.
I guess thinking about it as discrete distributions means that the distribution changes every time a value is drawn, and maybe isn't the best way to think about this problem? | 2022/04/11 | [
"https://stats.stackexchange.com/questions/571212",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/354446/"
]
| @BruceET's answer has some nice information, and simulations are often a good starting place for this sort of thing in practice. In this answer, I'll detail an exact approach, which demonstrates that the exact answer is actually $20.275$, **the same as in the sampling without replacement approach**.
Note that this is unsurprising due to the linearity of expectation and the fact that, marginally, each $X\_i$ has the same distribution in either case. Note that the variances will NOT be the same for each approach, as @BruceET points out in his answer.
---
In the sampling with replacement case, you can view each draw as an *independent* draw from the given discrete distribution $X\_1, X\_2, X\_3 \stackrel{\text{iid}}{\sim} p(x)$. In the sampling *without replacement* case, you have to consider the *joint* distribution of the random variables ${\bf X} = (X\_1, X\_2, X\_3) \sim p(x\_1, x\_2, x\_3)$. Then the expected value of $Y = X\_1 + X\_2 + X\_3$ is taken as the weighted average with weights given by $p(x\_1, x\_2, x\_3)$.
---
More generally, let $S = \{s\_1, s\_2, \ldots s\_n\}$. A general strategy for finding $E(X\_1+X\_2+X\_3)$ starts by listing all of the possible outcomes,
$$\mathcal S = \{(x\_1, x\_2, x\_3) | x\_1 = s\_i, x\_2 = s\_j, x\_3 = s\_k, i \neq j \neq k),$$
of which there are $n(n-1)(n-2)$. Since the sum doesn't care about the order in which each number is drawn, we can simplify things a bit by looking at the set of all combinations:
$$\mathcal S = \{(x\_1, x\_2, x\_3) | x\_1 = s\_i, x\_2 = s\_j, x\_3 = s\_k, i < j < k),$$
of which there are $\binom{n}{3}$ options. Then the expected value can be computed as
\begin{align\*}
E(X\_1+X\_2+X\_3) &= \sum\_{k=3}^n\sum\_{j=2}^k\sum\_{i=1}^j(s\_i + s\_j + s\_k)\times 6 \times p(s\_i, s\_j, s\_k)\\
&= \frac{6}{10\cdot9\cdot8}\sum\_{k=3}^n\sum\_{j=2}^k\sum\_{i=1}^j(s\_i + s\_j + s\_k) \\
&= \ldots \\
&= \frac{3}{n}\sum\_{i=1}^n s\_i
\end{align\*}
where the $6$ comes from the various orderings of $s\_i, s\_j, s\_k$. Since each element $s\_i (i=1,\ldots n)$ has the same probability of being selected, we have $p(s\_i, s\_j, s\_k) = \frac{1}{10\cdot 9\cdot 8}$ for each combination.
---
Example R Code
--------------
Based on a suggestion by @BruceET, this R code has been edited to compute the expected value and variance. Note that the variance is significantly smaller than the case of sampling with replacement.
```
compute_expected_value <- function(S){
n <- length(S)
E1 <- E2 <- 0
for(i in 3:n){
for(j in 2:(i-1)){
for(k in 1:(j-1)){
E1 <- E1 + 6*(S[i] + S[j] + S[k])/10/9/8
E2 <- E2 + 6*(S[i] + S[j] + S[k])^2/10/9/8
}
}
}
res <- c(E1, E2-E1^2)
names(res) <- c("mean", "variance")
return(res)
}
S <- c(0,0,0,0, 22.95, 0,0,0, 19.125,25.5)
compute_expected_value(S)
> mean variance
> 20.2725 253.4187
``` | When sampling without replacement from the set $S=\{s\_1,s\_2,\dots,s\_n\}$, the sampled values $X\_1,X\_2,\dots,X\_m$ have an exchangeable distribution. Hence,
for any $k$, $E(X\_k)=\frac1n\sum s\_i=\bar s$ and $\operatorname{Var}X\_k=\frac1n\sum\_{i=1}^n s\_i^2-\bar{s}^2=\bar{s^2}-{\bar s}^2$. Furthermore, for any pair $k\neq l$,
\begin{align}
E(X\_kX\_l)
&=\sum\_{i \neq j} s\_is\_j\frac{1}{n(n-1)}
\\&=\frac1{n(n-1)}\sum\_{i\neq j} s\_is\_j
\\&=\frac1{n(n-1)}\left(\sum\_{i,j} s\_is\_j-\sum\_i s\_i^2\right)
\\&=\frac{n}{n-1}\sum\_{i,j} s\_is\_j\frac1{n^2}-\frac{1}{n-1}\sum\_i s\_i^2\frac1n
\\&=\frac{n}{n-1}\bar{s}^2-\frac{1}{n-1}\bar{s^2}. \tag{1}
\end{align}
Hence,
\begin{align}
\operatorname{Cov}(X\_k,X\_l)
&=E(X\_kX\_l)-(EX\_k)(EX\_l)
\\&=\frac{n}{n-1}\bar{s}^2-\frac{1}{n-1}\bar{s^2}-\bar{s}^2
\\&=\frac{1}{n-1}\bar{s}^2-\frac{1}{n-1}\bar{s^2}
\\&=-\frac{1}{n-1}\operatorname{Var}X\_k, \tag{2}
\end{align}
and
\begin{align}
\operatorname{Var}(X\_1+X\_2+\dots+X\_m)
&=m\operatorname{Var}(X\_k)+m(m-1)\operatorname{Cov}(X\_k,X\_l)
\\&=m\operatorname{Var}(X\_k)\frac{n-m}{n-1}. \tag{3}
\end{align}
Thus, relative to sampling with replacement, the effect of sampling without replacement is to reduce the variance of $\sum\_{k=1}^m X\_k$ (and $\bar X$) by a factor of $\frac{n-m}{n-1}$.
It can also be noted that (2) can be derived more directly by setting $m=n$ in (3) such that the variance of the sum on the left hand side is zero and solving for the covariance.
Unsurprisingly, the variances of the [hypergeometric](https://en.wikipedia.org/wiki/Hypergeometric_distribution) and [binomial](https://en.wikipedia.org/wiki/Binomial_distribution) distributions differ by the exact same factor. |
59,270,456 | I'm in college and I've been granted a task to make an app that calculates and shows the hash of a file in UWP application. Every time when I want to compute the hash of the file that I picked, I get "Access to path is denied." error. I want to compute the hash passing a filestream as a parameter. I've tried to run Visual Studio as administrator but with no success. Below is the code.
```
public partial class MainPage : Page
{
byte[] result;
string[] algorithms = { "MD5", "SHA-1", "SHA256", "SHA384", "SHA512" };
string algorithm = "", path = "";
HashAlgorithm hash;
public MainPage()
{
this.InitializeComponent();
AlgorithmsList.ItemsSource = algorithms;
}
/* Browse for file */
private async void BrowseButton(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add("*");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
resultTextBlock.Text = "Result";
pathTextBlock.Text = file.Path;
path = file.Path;
}
}
/* Method that shows the hash after computing it */
private async void GoButton(object sender, RoutedEventArgs e)
{
if (path == "" || AlgorithmsList.SelectedIndex == -1)
{
MessageDialog dialog;
if (path == "")
dialog = new MessageDialog("You have to select a file");
else
dialog = new MessageDialog("You have to select an algorithm");
await dialog.ShowAsync();
}
else
{
algorithm = AlgorithmsList.Text;
string hash = await Task.Run(() => CalculateHash());
resultTextBlock.Text = hash;
}
}
private string CalculateHash()
{
string exception = "";
hash = InitAlgorithm();
try
{
using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
fileStream.Position = 0;
result = hash.ComputeHash(fileStream);
}
StringBuilder sb = new StringBuilder(result.Length * 2);
foreach (byte b in result)
{
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
catch (Exception e)
{
exception = e.ToString();
}
return exception;
}
private HashAlgorithm InitAlgorithm()
{
HashAlgorithm hash = null;
switch (algorithm)
{
case ("MD5"):
hash = MD5.Create();
break;
case ("SHA-1"):
hash = SHA1.Create();
break;
case ("SHA256"):
hash = SHA256.Create();
break;
case ("SHA384"):
hash = SHA384.Create();
break;
case ("SHA512"):
hash = SHA512.Create();
break;
}
return hash;
}
}
``` | 2019/12/10 | [
"https://Stackoverflow.com/questions/59270456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8418905/"
]
| Your input string is UTF8-encoded, which means each character is encoded by anything from one to four bytes. You cannot just scan through the string and convert them, unless your loop has an understanding of how Unicode characters are encoded in UTF8.
**You need a UTF8 decoder.**
Fortunately there are really lightweight ones you can use, if all you need is decoding. [UTF8-CPP](http://utfcpp.sourceforge.net/) is pretty much one header, and has a feature to provide you with individual Unicode characters. `utf8::next` will feed you `uint32_t` (the "largest" character's codepoint fits into an object of this type). Now you can simply see whether the value is less than 128: if it is, cast to `char` and append; if it isn't, serialise the integer in whatever way you see fit.
I implore you to consider whether this is really want you want to do, though. Your output will be ambiguous. It'll be impossible to determine whether a bunch of numbers in it are actual numbers, or the representation of some non-ASCII character. Why not just stick with the original UTF8 encoding, or use something like HTML entity encoding or quoted-printable? These encodings are widely understood and widely supported. | I just solved the issue:
```cpp
std::string Tools::encode_utf8(const std::wstring &wstr)
{
std::string utf8_encoded;
//iterate through the whole string
for(size_t j = 0; j < wstr.size(); ++j)
{
if(wstr.at(j) <= 0x7F)
utf8_encoded += wstr.at(j);
else if(wstr.at(j) <= 0x7FF)
{
//our template for unicode of 2 bytes
int utf8 = 0b11000000'10000000;
//get the first 6 bits and save them
utf8 += wstr.at(j) & 0b00111111;
/*
* get the last 5 remaining bits
* put them 2 to the left so that the 10 from 10xxxxxx (first byte) is not overwritten
*/
utf8 += (wstr.at(j) & 0b00000111'11000000) << 2;
//append to the result
std::string temp = Tools::to_hex(utf8);
utf8_encoded.append(temp.insert(0, "\\x").insert(4, "\\x"));
}
else if(wstr.at(j) <= 0xFFFF)
{
//our template for unicode of 3 bytes
int utf8 = 0b11100000'10000000'10000000;
//get the first 6 bits and save them
utf8 += wstr.at(j) & 0b00111111;
/*
* get the next 6 bits
* put them 2 to the left so that the 10 from 10xxxxxx (first byte) is not overwritten
*/
utf8 += (wstr.at(j) & 0b00001111'11000000) << 2;
/*
* get the last 4 remaining bits
* put them 4 to the left so that the 10xx from 10xxxxxx (second byte) is not overwritten
*/
utf8 += (wstr.at(j) & 0b11110000'00000000) << 4;
//append to the result
std::string temp = Tools::to_hex(utf8);
utf8_encoded.append(temp.insert(0, "\\x").insert(4, "\\x").insert(8, "\\x"));
}
else if(wstr.at(j) <= 0x10FFFF)
{
//our template for unicode of 4 bytes
int utf8 = 0b11110000'10000000'10000000'10000000;
//get the first 6 bits and save them
utf8 += wstr.at(j) & 0b00111111;
/*
* get the next 6 bits
* put them 2 to the left so that the 10 from 10xxxxxx (first byte) is not overwritten
*/
utf8 += (wstr.at(j) & 0b00001111'11000000) << 2;
/*
* get the next 6 bits
* put them 4 to the left so that the 10xx from 10xxxxxx (second byte) is not overwritten
*/
utf8 += (wstr.at(j) & 0b00000011'11110000'00000000) << 4;
/*
* get the last 3 remaining bits
* put them 6 to the left so that the 10xxxx from 10xxxxxx (third byte) is not overwritten
*/
utf8 += (wstr.at(j) & 0b00011100'00000000'00000000) << 4;
//append to the result
std::string temp = Tools::to_hex(utf8);
utf8_encoded.append(temp.insert(0, "\\x").insert(4, "\\x").insert(8, "\\x").insert(12, "\\x"));
}
}
return utf8_encoded;
}
``` |
23,691 | I've started to hear creaking/clicking sounds from the saddle tube. **Is the frame giving up?**
I could look for [a longer saddle post](http://www.amazon.de/XXL-ALU-SATTELST%C3%9CTZE-%C3%9CBERL%C3%84NGE-50/dp/B003IB77WC/ref=sr_1_9?ie=UTF8&qid=1405670710&sr=8-9&keywords=fahrrad%20sattelstange), if that would relieve some of the strain on this part of the frame, but I'm not sure what length to get.
I've measured the outer diameter of the post to be approx. 27mm -- but what is the proper name/size for this dimension?
It's a 58 (cm/in?) aluminum frame with 28" wheels, roughly 10 years old. I've got the saddle fairly high, but I'm a tall guy (192cm, 95kg) so it needs to be like this. When I put a heel on the lowest pedal, my leg is practically straight. Perhaps I should buy a bike with a bigger frame, if that exists, but I am hoping to avoid significant expenses. The bike is otherwise in good condition.
**Updates to comments:**
* Saddle post is 1cm lower than its "max" mark. Close, but okay - perhaps too close, given my weight? (95kg)
* frame and post is metal, presumably both aluminum.
* Creaking goes away when standing. That's why I suspect this area.
* Saddle clamp and rails seem good on visual inspection.
 | 2014/07/18 | [
"https://bicycles.stackexchange.com/questions/23691",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/275/"
]
| Often, dirt gets between the seat post and seat tube. Remove the seat post. Clean the post. Clean inside the seat tube. Grease the post and re-install. Hopefully the noise will be gone. You say the post is close to the max mark. For a little added safety, longer seat posts are available. | Try to put tube lower enough and check how it sounds in that position. If any sounds don't appear then just replace with new longer tube. It saves your frame.
Or it might be sand or dirt cause noise. So try to clean up tube and frame. |
23,691 | I've started to hear creaking/clicking sounds from the saddle tube. **Is the frame giving up?**
I could look for [a longer saddle post](http://www.amazon.de/XXL-ALU-SATTELST%C3%9CTZE-%C3%9CBERL%C3%84NGE-50/dp/B003IB77WC/ref=sr_1_9?ie=UTF8&qid=1405670710&sr=8-9&keywords=fahrrad%20sattelstange), if that would relieve some of the strain on this part of the frame, but I'm not sure what length to get.
I've measured the outer diameter of the post to be approx. 27mm -- but what is the proper name/size for this dimension?
It's a 58 (cm/in?) aluminum frame with 28" wheels, roughly 10 years old. I've got the saddle fairly high, but I'm a tall guy (192cm, 95kg) so it needs to be like this. When I put a heel on the lowest pedal, my leg is practically straight. Perhaps I should buy a bike with a bigger frame, if that exists, but I am hoping to avoid significant expenses. The bike is otherwise in good condition.
**Updates to comments:**
* Saddle post is 1cm lower than its "max" mark. Close, but okay - perhaps too close, given my weight? (95kg)
* frame and post is metal, presumably both aluminum.
* Creaking goes away when standing. That's why I suspect this area.
* Saddle clamp and rails seem good on visual inspection.
 | 2014/07/18 | [
"https://bicycles.stackexchange.com/questions/23691",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/275/"
]
| Most probably, the seatpost just needs to be cleaned (dust gets in) AND/OR tightened a little bit. Don't overdo it, it's best to stay within the 5-6 Nm range so as not to bust your seatpost ring or seat tube. Greasing the seatpost might also help. I wouldn't recommend any actual grease for this (messy, tends to get the seatpost stuck after a year of riding), powdered graphite is more appropriate. | Try to put tube lower enough and check how it sounds in that position. If any sounds don't appear then just replace with new longer tube. It saves your frame.
Or it might be sand or dirt cause noise. So try to clean up tube and frame. |
23,691 | I've started to hear creaking/clicking sounds from the saddle tube. **Is the frame giving up?**
I could look for [a longer saddle post](http://www.amazon.de/XXL-ALU-SATTELST%C3%9CTZE-%C3%9CBERL%C3%84NGE-50/dp/B003IB77WC/ref=sr_1_9?ie=UTF8&qid=1405670710&sr=8-9&keywords=fahrrad%20sattelstange), if that would relieve some of the strain on this part of the frame, but I'm not sure what length to get.
I've measured the outer diameter of the post to be approx. 27mm -- but what is the proper name/size for this dimension?
It's a 58 (cm/in?) aluminum frame with 28" wheels, roughly 10 years old. I've got the saddle fairly high, but I'm a tall guy (192cm, 95kg) so it needs to be like this. When I put a heel on the lowest pedal, my leg is practically straight. Perhaps I should buy a bike with a bigger frame, if that exists, but I am hoping to avoid significant expenses. The bike is otherwise in good condition.
**Updates to comments:**
* Saddle post is 1cm lower than its "max" mark. Close, but okay - perhaps too close, given my weight? (95kg)
* frame and post is metal, presumably both aluminum.
* Creaking goes away when standing. That's why I suspect this area.
* Saddle clamp and rails seem good on visual inspection.
 | 2014/07/18 | [
"https://bicycles.stackexchange.com/questions/23691",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/275/"
]
| As a fellow tall guy, try temporarily lowering your seat by half and see if the creaking goes away. If yes, your seatpost is simply too high and unsupported, so buy a longer one. 350mm and 400mm are available now, not overly expensive.
Have a good close look at the frame for cracks too - I broke a frame by having the seat too high. | Try to put tube lower enough and check how it sounds in that position. If any sounds don't appear then just replace with new longer tube. It saves your frame.
Or it might be sand or dirt cause noise. So try to clean up tube and frame. |
23,691 | I've started to hear creaking/clicking sounds from the saddle tube. **Is the frame giving up?**
I could look for [a longer saddle post](http://www.amazon.de/XXL-ALU-SATTELST%C3%9CTZE-%C3%9CBERL%C3%84NGE-50/dp/B003IB77WC/ref=sr_1_9?ie=UTF8&qid=1405670710&sr=8-9&keywords=fahrrad%20sattelstange), if that would relieve some of the strain on this part of the frame, but I'm not sure what length to get.
I've measured the outer diameter of the post to be approx. 27mm -- but what is the proper name/size for this dimension?
It's a 58 (cm/in?) aluminum frame with 28" wheels, roughly 10 years old. I've got the saddle fairly high, but I'm a tall guy (192cm, 95kg) so it needs to be like this. When I put a heel on the lowest pedal, my leg is practically straight. Perhaps I should buy a bike with a bigger frame, if that exists, but I am hoping to avoid significant expenses. The bike is otherwise in good condition.
**Updates to comments:**
* Saddle post is 1cm lower than its "max" mark. Close, but okay - perhaps too close, given my weight? (95kg)
* frame and post is metal, presumably both aluminum.
* Creaking goes away when standing. That's why I suspect this area.
* Saddle clamp and rails seem good on visual inspection.
 | 2014/07/18 | [
"https://bicycles.stackexchange.com/questions/23691",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/275/"
]
| Often, dirt gets between the seat post and seat tube. Remove the seat post. Clean the post. Clean inside the seat tube. Grease the post and re-install. Hopefully the noise will be gone. You say the post is close to the max mark. For a little added safety, longer seat posts are available. | As a fellow tall guy, try temporarily lowering your seat by half and see if the creaking goes away. If yes, your seatpost is simply too high and unsupported, so buy a longer one. 350mm and 400mm are available now, not overly expensive.
Have a good close look at the frame for cracks too - I broke a frame by having the seat too high. |
23,691 | I've started to hear creaking/clicking sounds from the saddle tube. **Is the frame giving up?**
I could look for [a longer saddle post](http://www.amazon.de/XXL-ALU-SATTELST%C3%9CTZE-%C3%9CBERL%C3%84NGE-50/dp/B003IB77WC/ref=sr_1_9?ie=UTF8&qid=1405670710&sr=8-9&keywords=fahrrad%20sattelstange), if that would relieve some of the strain on this part of the frame, but I'm not sure what length to get.
I've measured the outer diameter of the post to be approx. 27mm -- but what is the proper name/size for this dimension?
It's a 58 (cm/in?) aluminum frame with 28" wheels, roughly 10 years old. I've got the saddle fairly high, but I'm a tall guy (192cm, 95kg) so it needs to be like this. When I put a heel on the lowest pedal, my leg is practically straight. Perhaps I should buy a bike with a bigger frame, if that exists, but I am hoping to avoid significant expenses. The bike is otherwise in good condition.
**Updates to comments:**
* Saddle post is 1cm lower than its "max" mark. Close, but okay - perhaps too close, given my weight? (95kg)
* frame and post is metal, presumably both aluminum.
* Creaking goes away when standing. That's why I suspect this area.
* Saddle clamp and rails seem good on visual inspection.
 | 2014/07/18 | [
"https://bicycles.stackexchange.com/questions/23691",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/275/"
]
| Most probably, the seatpost just needs to be cleaned (dust gets in) AND/OR tightened a little bit. Don't overdo it, it's best to stay within the 5-6 Nm range so as not to bust your seatpost ring or seat tube. Greasing the seatpost might also help. I wouldn't recommend any actual grease for this (messy, tends to get the seatpost stuck after a year of riding), powdered graphite is more appropriate. | As a fellow tall guy, try temporarily lowering your seat by half and see if the creaking goes away. If yes, your seatpost is simply too high and unsupported, so buy a longer one. 350mm and 400mm are available now, not overly expensive.
Have a good close look at the frame for cracks too - I broke a frame by having the seat too high. |
2,525 | I want a "product shot" style photo of several small objects without any background (pure white background).
Knowing the hours of work involved in properly deep-etching, but not having nice lighting or a curved-white-matte background, I photographed them on white paper. My hope was that instead of laboriously removing the BG with a selection tool, I could somehow **"whiten the whites" of the images** use "curves" or something like that.
However, I played with the curves tool but couldn't figure it out. How do I do this? (or any better suggestions?) | 2010/08/16 | [
"https://photo.stackexchange.com/questions/2525",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1065/"
]
| I'll show how you can do this in GIMP, it should be similar in photoshop.
We start with our object on paper. Curves dialog basically shows us histogram of the image. When I click into the image, I can see where in the histogram given area is. This way I can find out where approximately my future white point is going to be.
[](https://i.stack.imgur.com/roogM.jpg)
Then I modify the curve in way that makes tones even a bit darker than our projected point go completely white. The curve basically sets brigtness tone mapping in our image. Original curve projected every tone to the same one, so did not change anything. The curve we have now makes everything above 55% brightness completely white, the second point in the middle tries to keep tones that were originally dark relatively unchanged.
[](https://i.stack.imgur.com/kyMXb.jpg)
As you can see this curve didn't work completely. I could have pushed the brightness a bit further (e.g. the curve a bit left, to eat out more of middle tones), but I think that would destroy original image too much. If I needed to go through with this I'd probably create another layer in which I'd push it all the way to eliminate the shadow, and than mask it in a way that would only show up in shadow area where I need it, without affecting a low of the object.
Or, our can simply take this as a a starting point and use white brush to kill the rest of the background. | Unless it's a terribly complex item, I would suggest just going and removing the background. You may get somewhere first with using a magic wand selection.
Removing the background manually either with a selection tool or an eraser will give you the cleanest result without affecting the item itself.
That's how I would go about it anyway. |
2,525 | I want a "product shot" style photo of several small objects without any background (pure white background).
Knowing the hours of work involved in properly deep-etching, but not having nice lighting or a curved-white-matte background, I photographed them on white paper. My hope was that instead of laboriously removing the BG with a selection tool, I could somehow **"whiten the whites" of the images** use "curves" or something like that.
However, I played with the curves tool but couldn't figure it out. How do I do this? (or any better suggestions?) | 2010/08/16 | [
"https://photo.stackexchange.com/questions/2525",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1065/"
]
| I'll show how you can do this in GIMP, it should be similar in photoshop.
We start with our object on paper. Curves dialog basically shows us histogram of the image. When I click into the image, I can see where in the histogram given area is. This way I can find out where approximately my future white point is going to be.
[](https://i.stack.imgur.com/roogM.jpg)
Then I modify the curve in way that makes tones even a bit darker than our projected point go completely white. The curve basically sets brigtness tone mapping in our image. Original curve projected every tone to the same one, so did not change anything. The curve we have now makes everything above 55% brightness completely white, the second point in the middle tries to keep tones that were originally dark relatively unchanged.
[](https://i.stack.imgur.com/kyMXb.jpg)
As you can see this curve didn't work completely. I could have pushed the brightness a bit further (e.g. the curve a bit left, to eat out more of middle tones), but I think that would destroy original image too much. If I needed to go through with this I'd probably create another layer in which I'd push it all the way to eliminate the shadow, and than mask it in a way that would only show up in shadow area where I need it, without affecting a low of the object.
Or, our can simply take this as a a starting point and use white brush to kill the rest of the background. | If there is no bright areas on your products, then you can use curves to blow all the highlights until the paper is all white. Go near the top right and experiment with bringing a spot near the top up, but it will probably change the lighter areas of your product noticeably. |
2,525 | I want a "product shot" style photo of several small objects without any background (pure white background).
Knowing the hours of work involved in properly deep-etching, but not having nice lighting or a curved-white-matte background, I photographed them on white paper. My hope was that instead of laboriously removing the BG with a selection tool, I could somehow **"whiten the whites" of the images** use "curves" or something like that.
However, I played with the curves tool but couldn't figure it out. How do I do this? (or any better suggestions?) | 2010/08/16 | [
"https://photo.stackexchange.com/questions/2525",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1065/"
]
| I'll show how you can do this in GIMP, it should be similar in photoshop.
We start with our object on paper. Curves dialog basically shows us histogram of the image. When I click into the image, I can see where in the histogram given area is. This way I can find out where approximately my future white point is going to be.
[](https://i.stack.imgur.com/roogM.jpg)
Then I modify the curve in way that makes tones even a bit darker than our projected point go completely white. The curve basically sets brigtness tone mapping in our image. Original curve projected every tone to the same one, so did not change anything. The curve we have now makes everything above 55% brightness completely white, the second point in the middle tries to keep tones that were originally dark relatively unchanged.
[](https://i.stack.imgur.com/kyMXb.jpg)
As you can see this curve didn't work completely. I could have pushed the brightness a bit further (e.g. the curve a bit left, to eat out more of middle tones), but I think that would destroy original image too much. If I needed to go through with this I'd probably create another layer in which I'd push it all the way to eliminate the shadow, and than mask it in a way that would only show up in shadow area where I need it, without affecting a low of the object.
Or, our can simply take this as a a starting point and use white brush to kill the rest of the background. | I would recommend reading through [How do I properly do shadowless product photos?](https://photo.stackexchange.com/questions/14991) as a lot of the same principles there apply here.
In general: 1) Use a back-splash light which is brighter than the product.
or
2) Post-process fix it up.
For 2, you can use Photoshop or Gimp and the selection wand like you mentioned. There are also other resources online available, such as <http://fotofuze.com>, which can do the selection and cut-out part for you.
Photoshop can be bought here: <http://www.adobe.com/products/photoshop.html>
GIMP can be downloaded here: <http://www.gimp.org/> |
17,299,915 | My question is pretty like [my last topic](https://stackoverflow.com/questions/17298413/div-backgroundcolor-change-to-element-backgroundcolor-using-javascript), but it's not the same.
---
I have several buttons and styled by CSS.
HTML codes is here :
```
<button class="Btn red">Btn1</button>
<button class="Btn blue">Btn2</button>
<button class="Btn green">Btn3</button>
<div id="Content"></div>
```
And CSS codes is here :
```
.red {
background-color: #ff0000;
}
.blue {
background-color: #0000ff;
}
.green {
background-color: #00ff00;
}
#Content {
background-color: #ccc;
width: 150px;
height: 150px;
}
```
My question is :
How do i change `(#Content).backgroundcolor` to `(Clicked_Btn).backgroundcolor` using Javascript.
I have tried below JS commands, i think it has a lot of problems :
```
$(".Btn").click(function(){
document.getElementById("Content").style.backgroundColor = getComputedStyle(this).backgroundColor;
);
```
[DEMO in JsFiddle.](http://jsfiddle.net/4nYsH/)
---
P.S :
As i mentioned above please don't suggest something like :
```
// HTML
<button class="Btn red" onClick="changeColor(this);">Btn1</button>
...
//JavaScript
function changeColor(elem){
document.getElementById("Content").style.backgroundColor = getComputedStyle(elem).backgroundColor;
}
```
I don't want to use `onClick("function();")` inside HTML button tags.
Any help would be awesome. | 2013/06/25 | [
"https://Stackoverflow.com/questions/17299915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1345050/"
]
| Pure Javascript (no jQuery dependency):
```
var buttons = document.getElementsByTagName("button");
for(var i=0; i<buttons.length; i++){
buttons[i].onclick = function(){
document.getElementById("Content").style.backgroundColor = getComputedStyle(this).backgroundColor;
}
}
```
[Demo](http://jsfiddle.net/YE3mj/4/) | if you are using $(".Btn").click then you are using jquery. This means that you can simplify a lot the subsequent line.
```
$(".Btn").click(function(){
$("#Content").css('background-color',$(this).css('background-color'));
});
```
and here is your fiddle edited: [DEMO](http://jsfiddle.net/AFBTp/) |
10,543,561 | I made a simple quiz scoring using PHP but its coming up with unidentifed offset errors, but it works fine.
errors:
```
Notice: Undefined offset: 0 in C:\Users\scorequiz1.php on line 17
Notice: Undefined offset: 1 in C:\Users\scorequiz1.php on line 18
Notice: Undefined offset: 2 in C:\Users\scorequiz1.php on line 19
Notice: Undefined offset: 3 in C:\Users\scorequiz1.php on line 20
Notice: Undefined offset: 4 in C:\Users\scorequiz1.php on line 21
Notice: Undefined offset: 0 in C:\Users\scorequiz1.php on line 52
Question 1. Correct.
Notice: Undefined offset: 1 in C:\Users\scorequiz1.php on line 52
Question 2. Incorrect.
Notice: Undefined offset: 2 in C:\Users\scorequiz1.php on line 52
Question 3. Correct.
Notice: Undefined offset: 3 in C:\Users\scorequiz1.php on line 52
Question 4. Correct.
Notice: Undefined offset: 4 in C:\Users\scorequiz1.php on line 52
Question 5. Incorrect.
```
line 17 to 21:
```
$data[0] = $_POST["a"];
$data[1] = $_POST["b"];
$data[2] = $_POST["c"];
$data[3] = $_POST["d"];
$data[4] = $_POST["e"];
```
line 50-56:
```
for($i = 0; $i < 5; $i++)
{
if($answer[$i] == 1)
echo "Question " . ($i+1) . ". " . "Correct.<br/>";
else
echo "Question " . ($i+1) . ". " . "Incorrect.<br/>";
}
```
my quiz is just like this. The options for question has the name "a" to "e" and the value to check for the right answer
```
<!-- question 1---->
<INPUT TYPE="radio" NAME="a" VALUE="1">10 days<BR>
<INPUT TYPE="radio" NAME="a" VALUE="1">40 days<BR>
<!-- question 2---->
<INPUT TYPE="radio" NAME="b" VALUE="1">True<BR>
<INPUT TYPE="radio" NAME="b" VALUE="1">False<BR>
```
I'm not sure whats wrong | 2012/05/10 | [
"https://Stackoverflow.com/questions/10543561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365708/"
]
| The `ls -l` command gave a list of all the subdirectories in your current present-working-directory (PWD).
The `rm` command can delete multiple files/directories if you pass them to it as a list.
eg: `rm test1.txt test2.txt myApp` will delete all three of the files with names:
```
test1.txt
test2.txt
myApp
```
Also, the flags for the `rm` command you used are common in many a folly.
`rm -f` - Force deletion of files without asking or confirming
`rm -r` - Recurse into all subdirectories and delete all their contents and subdirectories
So, let's say you are in /home/user, and the directory structure looks like so:
```
/home/user
|->dir1
|->dir2
`->file1.txt
```
the `ls -l` command will provide the list containing `"dir1 dir2 file1.txt"`, and the result of the command `ls -l | xargs rm -rf` will look like this:
`rm -rf dir1 dir2 file1.txt`
If we expand your original question with the example above, the final command that gets passed to the system becomes:
`rm -rf di1 dir2 file1.txt bark.*`
So, everything in the current directory gets wiped out, so the `bark.*` is redundant (you effectively told the machine to destroy everything in the current directory anyway).
I think what you meant to do was delete all files in the current directory and all subdirectories (recurse) that start with `bark.` To do that, you just have to do:
`find -iname bark.* | xargs rm`
The command above means "find all files in this directory and subdirectories, ignoring UPPERCASE/lowercase/mIxEdCaSe, that start with the characters "bark.", and delete them". This could still be a bad command if you have a typo, so to be sure, you should always test before you do a batch-deletion like this.
In the future, first do the following to get a list of all the files you will be deleting first to confirm they are the ones you want deleted.
`find -iname bark.* | xargs echo`
Then if you are sure, delete them via
`find -iname bark.* | xargs rm`
Hope this helps.
As a humorous note, one of the most famous instances of "rm -rf" can be found here:
<https://github.com/MrMEEE/bumblebee-Old-and-abbandoned/commit/a047be85247755cdbe0acce6f1dafc8beb84f2ac>
An automated script runs something like `rm -rf /usr/local/.........`, but due to accidentally inserting a space, the command became `rm -rf /usr /local/......`, so this effectively means "delete all root folders that start with usr or local", effectively destroying the system of anyone who uses it. I feel bad for that developer.
You can avoid these kinds of bugs by quoting your strings, ie:
`rm -rf "/usr/ local/...."` would have provided an error message and avoided this bug, because the quotes mean that everything between them is the full path, NOT a list of separate paths/files (ie: you are telling rm that the file/folder has a SPACE character in its name). | The `-r` argument means "delete recursively" (ie descend into subdirectories). The `-f` command means "force" (in other words, don't ask for confirmation). `-rf` means "descend recursively into subdirectories without asking for confirmation"
`ls -l` lists all files in the directory. `xargs` takes the input from `ls -l` and appends it to the command you pass to `xargs`
The final command that got executed looked like this:
```
rm -rf bark.* <output of ls -l>
```
This essentially removed `bark.*` **and** all files in the current directory. Moral of the story: be very careful with `rm -rf`. (You can use `rm -ri` to ask before deleting files instead) |
10,543,561 | I made a simple quiz scoring using PHP but its coming up with unidentifed offset errors, but it works fine.
errors:
```
Notice: Undefined offset: 0 in C:\Users\scorequiz1.php on line 17
Notice: Undefined offset: 1 in C:\Users\scorequiz1.php on line 18
Notice: Undefined offset: 2 in C:\Users\scorequiz1.php on line 19
Notice: Undefined offset: 3 in C:\Users\scorequiz1.php on line 20
Notice: Undefined offset: 4 in C:\Users\scorequiz1.php on line 21
Notice: Undefined offset: 0 in C:\Users\scorequiz1.php on line 52
Question 1. Correct.
Notice: Undefined offset: 1 in C:\Users\scorequiz1.php on line 52
Question 2. Incorrect.
Notice: Undefined offset: 2 in C:\Users\scorequiz1.php on line 52
Question 3. Correct.
Notice: Undefined offset: 3 in C:\Users\scorequiz1.php on line 52
Question 4. Correct.
Notice: Undefined offset: 4 in C:\Users\scorequiz1.php on line 52
Question 5. Incorrect.
```
line 17 to 21:
```
$data[0] = $_POST["a"];
$data[1] = $_POST["b"];
$data[2] = $_POST["c"];
$data[3] = $_POST["d"];
$data[4] = $_POST["e"];
```
line 50-56:
```
for($i = 0; $i < 5; $i++)
{
if($answer[$i] == 1)
echo "Question " . ($i+1) . ". " . "Correct.<br/>";
else
echo "Question " . ($i+1) . ". " . "Incorrect.<br/>";
}
```
my quiz is just like this. The options for question has the name "a" to "e" and the value to check for the right answer
```
<!-- question 1---->
<INPUT TYPE="radio" NAME="a" VALUE="1">10 days<BR>
<INPUT TYPE="radio" NAME="a" VALUE="1">40 days<BR>
<!-- question 2---->
<INPUT TYPE="radio" NAME="b" VALUE="1">True<BR>
<INPUT TYPE="radio" NAME="b" VALUE="1">False<BR>
```
I'm not sure whats wrong | 2012/05/10 | [
"https://Stackoverflow.com/questions/10543561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365708/"
]
| The `ls -l` command gave a list of all the subdirectories in your current present-working-directory (PWD).
The `rm` command can delete multiple files/directories if you pass them to it as a list.
eg: `rm test1.txt test2.txt myApp` will delete all three of the files with names:
```
test1.txt
test2.txt
myApp
```
Also, the flags for the `rm` command you used are common in many a folly.
`rm -f` - Force deletion of files without asking or confirming
`rm -r` - Recurse into all subdirectories and delete all their contents and subdirectories
So, let's say you are in /home/user, and the directory structure looks like so:
```
/home/user
|->dir1
|->dir2
`->file1.txt
```
the `ls -l` command will provide the list containing `"dir1 dir2 file1.txt"`, and the result of the command `ls -l | xargs rm -rf` will look like this:
`rm -rf dir1 dir2 file1.txt`
If we expand your original question with the example above, the final command that gets passed to the system becomes:
`rm -rf di1 dir2 file1.txt bark.*`
So, everything in the current directory gets wiped out, so the `bark.*` is redundant (you effectively told the machine to destroy everything in the current directory anyway).
I think what you meant to do was delete all files in the current directory and all subdirectories (recurse) that start with `bark.` To do that, you just have to do:
`find -iname bark.* | xargs rm`
The command above means "find all files in this directory and subdirectories, ignoring UPPERCASE/lowercase/mIxEdCaSe, that start with the characters "bark.", and delete them". This could still be a bad command if you have a typo, so to be sure, you should always test before you do a batch-deletion like this.
In the future, first do the following to get a list of all the files you will be deleting first to confirm they are the ones you want deleted.
`find -iname bark.* | xargs echo`
Then if you are sure, delete them via
`find -iname bark.* | xargs rm`
Hope this helps.
As a humorous note, one of the most famous instances of "rm -rf" can be found here:
<https://github.com/MrMEEE/bumblebee-Old-and-abbandoned/commit/a047be85247755cdbe0acce6f1dafc8beb84f2ac>
An automated script runs something like `rm -rf /usr/local/.........`, but due to accidentally inserting a space, the command became `rm -rf /usr /local/......`, so this effectively means "delete all root folders that start with usr or local", effectively destroying the system of anyone who uses it. I feel bad for that developer.
You can avoid these kinds of bugs by quoting your strings, ie:
`rm -rf "/usr/ local/...."` would have provided an error message and avoided this bug, because the quotes mean that everything between them is the full path, NOT a list of separate paths/files (ie: you are telling rm that the file/folder has a SPACE character in its name). | `rm(1)` deleted every file and directory in the current working directory because you asked it to.
To see roughly what happened, run this:
```
cd /etc ; ls -l | xargs echo
```
Pay careful attention to the output.
I strongly recommend using `echo` in place of `rm -rf` when constructing command lines. Only if the output looks fine should you then re-run the command with `rm -rf`. When in doubt, maybe just use `rm -r` so that you do not accidentally blow away too much. `rm -ir` if you are *very* skeptical of your command line. (I have been using Linux since 1994 and I *still* use this `echo` trick when constructing slightly complicated command lines to selectively delete a pile of files.)
Incidentally, I would avoid parsing `ls(1)` output in any fashion -- filenames can contain *any* character except ASCII `NUL` and `/` chars -- including newlines, tabs, and output that *looks* like `ls -l` output. Trying to *parse* this with tools such as `xargs(1)` can be dangerous.
Instead, use `find(1)` for these sorts of things. To delete all files in all directories named `bark.*`, I'd run a command like this:
```
find . -type d -name 'bark.*' -print0 | xargs -0 rm -r
```
Again, I'd use `echo` in place of `rm -r` for the first execution -- and if it looked fine, then I'd re-run with `rm -r`. |
6,786,106 | I've recently converted a highly threaded, unmanaged Win32 C++ console application (MediaServer.exe) to an unmanaged Win32 DLL (MediaServer.dll). I'm hosting and debugging this DLL in a separate unmanaged Win32 console app, and everything compiles and runs, but after a minute or so, I'll get a random crash, in a place that makes no sense, with an apparently corrupt call stack. These crashes happen in a variety of different places, and at somewhat random times: but the commonality is that the (apparently corrupt) call stack always has various libxml2.dll functions somewhere on it, e.g., the crash might be on a line that looks like this:
```
xmlDoc * document = xmlReadMemory(message.c_str(), message.length(), "noname.xml", NULL, 0);
```
Or like this:
```
xmlBufferPtr buffer = xmlBufferCreate();
```
And the call stack might look like this:
```
feeefeee()
libxml2.dll!000eeec9()
[Frames below may be incorrect and/or missing, no symbols loaded for libxml2.dll]
libxml2.dll!00131714()
libxml2.dll!001466b6()
libxml2.dll!00146bf9()
libxml2.dll!00146c3c()
libxml2.dll!0018419e()
```
Or if you're lucky, like this:
```
ntdll.dll!_RtlpWaitOnCriticalSection@8() + 0x99 bytes
ntdll.dll!_RtlEnterCriticalSection@4() - 0x15658 bytes
libxml2.dll!1004dc6d()
[Frames below may be incorrect and/or missing, no symbols loaded for libxml2.dll]
libxml2.dll!10012034()
libxml2.dll!1004b7f7()
libxml2.dll!1003904c()
libxml2.dll!100393a9()
libxml2.dll!10024621()
libxml2.dll!10036e8f()
MediaServer.dll!Controller::parse(std::basic_string<char,std::char_traits<char>,std::allocator<char> > message) Line 145 + 0x20 bytes C++
MediaServer.dll!Controller::receiveCommands() Line 90 + 0x25 bytes C++
MediaServer.dll!MediaServer::processCommands() Line 88 + 0xb bytes C++
MediaServer.dll!MediaServer::processCommandsFunction(void * mediaServerInstance) Line 450 + 0x8 bytes C++
MediaServer.dll!CustomThread::callThreadFunction() Line 79 + 0x11 bytes C++
MediaServer.dll!threadFunctionCallback(void * threadInstance) Line 10 + 0x8 bytes C++
kernel32.dll!@BaseThreadInitThunk@12() + 0x12 bytes
ntdll.dll!___RtlUserThreadStart@8() + 0x27 bytes
ntdll.dll!__RtlUserThreadStart@8() + 0x1b bytes
```
The crash itself will typically say something like "Unhandled exception at 0x77cd2239 (ntdll.dll) in MediaServerConsole.exe: 0xC000005: Access violation writing location 0x00000014."
Needless to say, this didn't happen when I was compiling the module as a console application.
Is there anything that I may have overlooked when converting the project over to a DLL? It's not something I've done before, so I wouldn't be at all surprised if there's something obvious I've neglected. Any help is appreciated. | 2011/07/22 | [
"https://Stackoverflow.com/questions/6786106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68231/"
]
| I would say you are initializing memory in DLL\_THREAD\_ATTACH instead of DLL\_PROCESS\_ATTACH. The situation would cause you to use a pointer or memory that has been allocated in another thread than the executing thread.
The other thing would be to check your loading of your dependencies for the DLL.
Let me explain. The CRT does global memory allocation when your DLL is loaded with loadlibrary. This is to initialize all the global variable ranging from C primitive types that initialize them to zero as default. Then it allocates the memory for struct/classes and if necessary call's their constructors.
The CRT then calls your DLLMain method with DLL\_PROCESS\_ATTACH to tell the DLL that is been loaded by your process. For each thread inside that process the CRT then calls your DLL with DLL\_THREAD\_ATTACH.
You've said these are left empty, and then you call your exported C function. Though I can see that you're dll is getting caught in a critical section. This tells me, that you have a dead lock situation occur with your global allocated variables and your thread allocating memory within Start().
I recommend to move your initialization code within Process\_Attached, this will ensure that all your memory is allocated on the main process thread, similar how the application worked as a single executable. | I'll leave the other answer as the "accepted" answer, but it might be helpful for people to know that a key part of the problem was the fact that I was initializing libxml2 on the wrong thread. Specifically, you need to call xmlInitParser() on your main thread, before making any calls. For me, this meant:
```
MediaServer::MediaServer() : mProvidePolicyThread (0),
mProcessCommandsThread(0),
mAcceptMemberThread (0)
{
xmlInitParser();
}
```
And similarly, you need to call xmlCleanupParser() when you exit:
```
MediaServer::~MediaServer()
{
xmlCleanupParser();
}
```
This is all documented here: <http://xmlsoft.org/threads.html> |
68,428,761 | ```
from random import randint
class Card:
suits = ["spades", "hearts", "diamonds", "clubs"]
values = [None, None, "2", "3", "4", "5", "6", "7", "8",
"9", "10", "Jack", "Queen", "King", "Ace"]
def __init__(self, v, s):
"""suit + value are ints"""
self.value = v
self.suit = s
def __gt__(self, c2):
if self.value > c2.value:
return True
if self.value == c2.value:
if self.suit > c2.suit:
return True
else:
return False
return False
def __repr__(self):
v = self.values[self.value] + " of " + self.suits[self.suit]
return v
class Player:
def __init__(self, name):
self.wins = 0
self.card = None
self.name = name
class Deck:
def __init__(self):
self.cards = []
for i in range(2, 15):
for j in range(4):
self.cards.append(Card(i, j))
self.random_cards = []
for x in range(len(self.cards)):
self.x = randint(0, len(self.cards) - 1)
self.random_cards.append(self.cards[self.x])
self.cards.pop(self.x)
def rm_card(self):
if len(self.random_cards) == 0:
return
return self.random_cards.pop()
class Game:
def __init__(self):
name1 = input("p1 name ")
name2 = input("p2 name ")
self.deck = Deck()
self.p1 = Player(name1)
self.p2 = Player(name2)
def wins(self, winner):
w = "{} wins this round"
w = w.format(winner)
print(w)
def draw(self, p1n, p1c, p2n, p2c):
d = "{} drew {} {} drew {}"
d = d.format(p1n, p1c, p2n, p2c)
print(d)
def play_game(self):
cards = self.deck.random_cards
print("beginning War!")
while len(cards) >= 2:
m = "q to quit. Any key to play:"
response = input(m)
if response == 'q':
break
p1c = self.deck.rm_card()
p2c = self.deck.rm_card()
p1n = self.p1.name
p2n = self.p2.name
self.draw(p1n, p1c, p2n, p2c)
if p1c.__gt__(p2c):
self.p1.wins += 1
self.wins(p1n)
else:
self.p2.wins += 1
self.wins(p2n)
win = self.winner(self.p1, self.p2)
if win == "It was a tie!":
print("It was a tie!")
else:
print("War is over.{} wins".format(win))
def winner(self, p1, p2):
if p1.wins > p2.wins:
return p1.name
if p1.wins < p2.wins:
return p2.name
return "It was a tie!"
game = Game()
game.play_game()
```
Instance Variables get defined in the init method, so they can get initialized. But I couldnt define the win (class Game, play\_game method) variable in it, since I didnt have all the arguments in the init method yet. So whats the difference between the win variable and the instance Variables and why dont I use a self there? | 2021/07/18 | [
"https://Stackoverflow.com/questions/68428761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16401725/"
]
| The reason you don't use 'self' for win is because it only needs to exist inside the method it was created in, whereas the other variables(i.e. things that are defined outside of the method) have to exhist in more than one function always (the **init** and also in whatever function you implement those values). With the win variable it is only needed in your play\_game() method, so it doesn't need self. | >
> Instance Variables get defined in the init method, so they can get initialized.
>
>
>
They are **attributes**, getting initialised and not variables. There is a difference.
>
> So whats the difference between the win variable and the instance Variables
>
>
>
The difference is that once you initialise the attributes, you give them an initial value so that you can change them later on.
>
> why dont I use a self there?
>
>
>
You do not need to use self when calling the method because you are telling - `self.winner(args)`. So it is the same as `winner(self,args)` |
27,539,419 | I was trying to convert my 2D String into 2D Integer ArrayList, but I don't know how to. I have read some reference but didn't find anything related.
Here is my method:
```
public static ArrayList<int[]> convert2DStringTo2DIntArrayList(String[][] originalString, int lengthOfRow, int lengthOfColumn) {
ArrayList<int[]> targetList = new ArrayList<int[]>();
if (lengthOfRow == -1) {
lengthOfRow = originalString.length - 1;
}
if (lengthOfColumn == -1) {
lengthOfColumn = originalString[0].length - 1;
}
for (int i = 0; i <= lengthOfRow - 1; i++) {
for (int j = 0; j <= lengthOfColumn - 1; j++) {
//targetList.addAll(Integer.parseInt(Arrays.asList(originalString)));
}
}
return targetList;
}
```
When lengthOfRow and lengthOfColumn all equal to -1 this method will fully convert 2D String to 2D Integer ArrayList. No problem with String because the String array to be proceed is partially filled by integer. I met this problem is because my original methods are all written in basic types and string. On the mid way I found I cannot handle several problem with string array. By this reason I have to write several method to convert string to ArrayList. | 2014/12/18 | [
"https://Stackoverflow.com/questions/27539419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4372809/"
]
| You may need to start the `couchdb` process as the `couchdb` user, with `su couchdb -c ./couchdb` (assuming the current directory contains the executable) - double-check the `su` command options for your system.
Also, check the permissions on `/usr/local/var/log/couchdb/couch.log` - make sure it is writeable by the `couchdb` user. | You can start couchdb using below command
sudo couchdb stop
sudo couchdb start |
27,539,419 | I was trying to convert my 2D String into 2D Integer ArrayList, but I don't know how to. I have read some reference but didn't find anything related.
Here is my method:
```
public static ArrayList<int[]> convert2DStringTo2DIntArrayList(String[][] originalString, int lengthOfRow, int lengthOfColumn) {
ArrayList<int[]> targetList = new ArrayList<int[]>();
if (lengthOfRow == -1) {
lengthOfRow = originalString.length - 1;
}
if (lengthOfColumn == -1) {
lengthOfColumn = originalString[0].length - 1;
}
for (int i = 0; i <= lengthOfRow - 1; i++) {
for (int j = 0; j <= lengthOfColumn - 1; j++) {
//targetList.addAll(Integer.parseInt(Arrays.asList(originalString)));
}
}
return targetList;
}
```
When lengthOfRow and lengthOfColumn all equal to -1 this method will fully convert 2D String to 2D Integer ArrayList. No problem with String because the String array to be proceed is partially filled by integer. I met this problem is because my original methods are all written in basic types and string. On the mid way I found I cannot handle several problem with string array. By this reason I have to write several method to convert string to ArrayList. | 2014/12/18 | [
"https://Stackoverflow.com/questions/27539419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4372809/"
]
| You may need to start the `couchdb` process as the `couchdb` user, with `su couchdb -c ./couchdb` (assuming the current directory contains the executable) - double-check the `su` command options for your system.
Also, check the permissions on `/usr/local/var/log/couchdb/couch.log` - make sure it is writeable by the `couchdb` user. | Although on CentOS, the "problem" is avoided using `service couchdb [start|status|stop|restart]`. |
27,539,419 | I was trying to convert my 2D String into 2D Integer ArrayList, but I don't know how to. I have read some reference but didn't find anything related.
Here is my method:
```
public static ArrayList<int[]> convert2DStringTo2DIntArrayList(String[][] originalString, int lengthOfRow, int lengthOfColumn) {
ArrayList<int[]> targetList = new ArrayList<int[]>();
if (lengthOfRow == -1) {
lengthOfRow = originalString.length - 1;
}
if (lengthOfColumn == -1) {
lengthOfColumn = originalString[0].length - 1;
}
for (int i = 0; i <= lengthOfRow - 1; i++) {
for (int j = 0; j <= lengthOfColumn - 1; j++) {
//targetList.addAll(Integer.parseInt(Arrays.asList(originalString)));
}
}
return targetList;
}
```
When lengthOfRow and lengthOfColumn all equal to -1 this method will fully convert 2D String to 2D Integer ArrayList. No problem with String because the String array to be proceed is partially filled by integer. I met this problem is because my original methods are all written in basic types and string. On the mid way I found I cannot handle several problem with string array. By this reason I have to write several method to convert string to ArrayList. | 2014/12/18 | [
"https://Stackoverflow.com/questions/27539419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4372809/"
]
| You may need to start the `couchdb` process as the `couchdb` user, with `su couchdb -c ./couchdb` (assuming the current directory contains the executable) - double-check the `su` command options for your system.
Also, check the permissions on `/usr/local/var/log/couchdb/couch.log` - make sure it is writeable by the `couchdb` user. | <https://medium.com/@tomiwatech_45998/installing-couchdb-on-ubuntu-17-10-18148e2eb846>
Hi there,
this helped me resolve the issue and solved the problem. My ubuntu version is 16.04 and i downloaded couchdb-1.7.0 version. |
27,539,419 | I was trying to convert my 2D String into 2D Integer ArrayList, but I don't know how to. I have read some reference but didn't find anything related.
Here is my method:
```
public static ArrayList<int[]> convert2DStringTo2DIntArrayList(String[][] originalString, int lengthOfRow, int lengthOfColumn) {
ArrayList<int[]> targetList = new ArrayList<int[]>();
if (lengthOfRow == -1) {
lengthOfRow = originalString.length - 1;
}
if (lengthOfColumn == -1) {
lengthOfColumn = originalString[0].length - 1;
}
for (int i = 0; i <= lengthOfRow - 1; i++) {
for (int j = 0; j <= lengthOfColumn - 1; j++) {
//targetList.addAll(Integer.parseInt(Arrays.asList(originalString)));
}
}
return targetList;
}
```
When lengthOfRow and lengthOfColumn all equal to -1 this method will fully convert 2D String to 2D Integer ArrayList. No problem with String because the String array to be proceed is partially filled by integer. I met this problem is because my original methods are all written in basic types and string. On the mid way I found I cannot handle several problem with string array. By this reason I have to write several method to convert string to ArrayList. | 2014/12/18 | [
"https://Stackoverflow.com/questions/27539419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4372809/"
]
| Although on CentOS, the "problem" is avoided using `service couchdb [start|status|stop|restart]`. | You can start couchdb using below command
sudo couchdb stop
sudo couchdb start |
27,539,419 | I was trying to convert my 2D String into 2D Integer ArrayList, but I don't know how to. I have read some reference but didn't find anything related.
Here is my method:
```
public static ArrayList<int[]> convert2DStringTo2DIntArrayList(String[][] originalString, int lengthOfRow, int lengthOfColumn) {
ArrayList<int[]> targetList = new ArrayList<int[]>();
if (lengthOfRow == -1) {
lengthOfRow = originalString.length - 1;
}
if (lengthOfColumn == -1) {
lengthOfColumn = originalString[0].length - 1;
}
for (int i = 0; i <= lengthOfRow - 1; i++) {
for (int j = 0; j <= lengthOfColumn - 1; j++) {
//targetList.addAll(Integer.parseInt(Arrays.asList(originalString)));
}
}
return targetList;
}
```
When lengthOfRow and lengthOfColumn all equal to -1 this method will fully convert 2D String to 2D Integer ArrayList. No problem with String because the String array to be proceed is partially filled by integer. I met this problem is because my original methods are all written in basic types and string. On the mid way I found I cannot handle several problem with string array. By this reason I have to write several method to convert string to ArrayList. | 2014/12/18 | [
"https://Stackoverflow.com/questions/27539419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4372809/"
]
| I would like to make a note here for how I fixed this problem in my environment. In my case, the `/opt/couchdb/data` folder was a symlink to `/var/lib/couchdb`. No matter what I tried I would get a permission denied error at startup, even though all the files seemed to be owned by user `couchdb`.
I eventually figured out that the "execute" permission was not set on `/var/lib`. Without this permission the symlink would not work. If you run into this problem, start by setting `chmod -R a+x /var` as I did, to prevent this from happening. | You can start couchdb using below command
sudo couchdb stop
sudo couchdb start |
27,539,419 | I was trying to convert my 2D String into 2D Integer ArrayList, but I don't know how to. I have read some reference but didn't find anything related.
Here is my method:
```
public static ArrayList<int[]> convert2DStringTo2DIntArrayList(String[][] originalString, int lengthOfRow, int lengthOfColumn) {
ArrayList<int[]> targetList = new ArrayList<int[]>();
if (lengthOfRow == -1) {
lengthOfRow = originalString.length - 1;
}
if (lengthOfColumn == -1) {
lengthOfColumn = originalString[0].length - 1;
}
for (int i = 0; i <= lengthOfRow - 1; i++) {
for (int j = 0; j <= lengthOfColumn - 1; j++) {
//targetList.addAll(Integer.parseInt(Arrays.asList(originalString)));
}
}
return targetList;
}
```
When lengthOfRow and lengthOfColumn all equal to -1 this method will fully convert 2D String to 2D Integer ArrayList. No problem with String because the String array to be proceed is partially filled by integer. I met this problem is because my original methods are all written in basic types and string. On the mid way I found I cannot handle several problem with string array. By this reason I have to write several method to convert string to ArrayList. | 2014/12/18 | [
"https://Stackoverflow.com/questions/27539419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4372809/"
]
| <https://medium.com/@tomiwatech_45998/installing-couchdb-on-ubuntu-17-10-18148e2eb846>
Hi there,
this helped me resolve the issue and solved the problem. My ubuntu version is 16.04 and i downloaded couchdb-1.7.0 version. | You can start couchdb using below command
sudo couchdb stop
sudo couchdb start |
27,539,419 | I was trying to convert my 2D String into 2D Integer ArrayList, but I don't know how to. I have read some reference but didn't find anything related.
Here is my method:
```
public static ArrayList<int[]> convert2DStringTo2DIntArrayList(String[][] originalString, int lengthOfRow, int lengthOfColumn) {
ArrayList<int[]> targetList = new ArrayList<int[]>();
if (lengthOfRow == -1) {
lengthOfRow = originalString.length - 1;
}
if (lengthOfColumn == -1) {
lengthOfColumn = originalString[0].length - 1;
}
for (int i = 0; i <= lengthOfRow - 1; i++) {
for (int j = 0; j <= lengthOfColumn - 1; j++) {
//targetList.addAll(Integer.parseInt(Arrays.asList(originalString)));
}
}
return targetList;
}
```
When lengthOfRow and lengthOfColumn all equal to -1 this method will fully convert 2D String to 2D Integer ArrayList. No problem with String because the String array to be proceed is partially filled by integer. I met this problem is because my original methods are all written in basic types and string. On the mid way I found I cannot handle several problem with string array. By this reason I have to write several method to convert string to ArrayList. | 2014/12/18 | [
"https://Stackoverflow.com/questions/27539419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4372809/"
]
| I would like to make a note here for how I fixed this problem in my environment. In my case, the `/opt/couchdb/data` folder was a symlink to `/var/lib/couchdb`. No matter what I tried I would get a permission denied error at startup, even though all the files seemed to be owned by user `couchdb`.
I eventually figured out that the "execute" permission was not set on `/var/lib`. Without this permission the symlink would not work. If you run into this problem, start by setting `chmod -R a+x /var` as I did, to prevent this from happening. | Although on CentOS, the "problem" is avoided using `service couchdb [start|status|stop|restart]`. |
27,539,419 | I was trying to convert my 2D String into 2D Integer ArrayList, but I don't know how to. I have read some reference but didn't find anything related.
Here is my method:
```
public static ArrayList<int[]> convert2DStringTo2DIntArrayList(String[][] originalString, int lengthOfRow, int lengthOfColumn) {
ArrayList<int[]> targetList = new ArrayList<int[]>();
if (lengthOfRow == -1) {
lengthOfRow = originalString.length - 1;
}
if (lengthOfColumn == -1) {
lengthOfColumn = originalString[0].length - 1;
}
for (int i = 0; i <= lengthOfRow - 1; i++) {
for (int j = 0; j <= lengthOfColumn - 1; j++) {
//targetList.addAll(Integer.parseInt(Arrays.asList(originalString)));
}
}
return targetList;
}
```
When lengthOfRow and lengthOfColumn all equal to -1 this method will fully convert 2D String to 2D Integer ArrayList. No problem with String because the String array to be proceed is partially filled by integer. I met this problem is because my original methods are all written in basic types and string. On the mid way I found I cannot handle several problem with string array. By this reason I have to write several method to convert string to ArrayList. | 2014/12/18 | [
"https://Stackoverflow.com/questions/27539419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4372809/"
]
| I would like to make a note here for how I fixed this problem in my environment. In my case, the `/opt/couchdb/data` folder was a symlink to `/var/lib/couchdb`. No matter what I tried I would get a permission denied error at startup, even though all the files seemed to be owned by user `couchdb`.
I eventually figured out that the "execute" permission was not set on `/var/lib`. Without this permission the symlink would not work. If you run into this problem, start by setting `chmod -R a+x /var` as I did, to prevent this from happening. | <https://medium.com/@tomiwatech_45998/installing-couchdb-on-ubuntu-17-10-18148e2eb846>
Hi there,
this helped me resolve the issue and solved the problem. My ubuntu version is 16.04 and i downloaded couchdb-1.7.0 version. |
182,341 | In Package `KnotTheory`, there's a function called `PD[]` that takes a tabulated knot and returns its PD codes, for example:
`PD[Knot[4, Alternating, 1]]` returns `PD[X[4, 2, 5, 1], X[6, 3, 7, 4], X[8, 6, 1, 5], X[2, 7, 3, 8]]`.
My question: what is the data type of this output above and what could be its design purpose? | 2018/09/22 | [
"https://mathematica.stackexchange.com/questions/182341",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/60308/"
]
| One could agree on a following convention for describing the same knot by agreeing on what is represented in each dimension:
```
{{4, 2, 5, 1}, {6, 3, 7, 4}, {8, 6, 1, 5}, {2, 7, 3, 8}}
```
The first dimension is a list of crossings and the second dimension is a list of edges. The same [expression](https://reference.wolfram.com/language/tutorial/EverythingIsAnExpression.html) in a [`FullForm`](https://reference.wolfram.com/language/ref/FullForm.html) would be
```
List[List[4, 2, 5, 1], List[6, 3, 7, 4], List[8, 6, 1, 5], List[2, 7, 3, 8]]
```
You can make your symbolic expressions much more self-explaining, semantic and flexible by using a different [*head*](https://mathematica.stackexchange.com/questions/95513/what-is-the-definition-of-head-in-mathematica) instead of `List`:
```
PD[X[4, 2, 5, 1], X[6, 3, 7, 4], X[8, 6, 1, 5], X[2, 7, 3, 8]]
```
`PD` and `X` look like "functions" which do not do anything, but they are useful symbolic wrappers. For example, in some application you could have complex nested structures, you can easily check if the head of a function argument is correct and so on. | *Mathematica* is an expression rewriting language. "Functions" are implemented with rewriting rules. In this case, `PD` appears to be associated with a rule that rewrites `PD[Knot[...]` as `PD[X[...],...` but no rule to rewrite it further. This design pattern allows an expression to rewrite itself into a standard form. You might want to think of the `PD` in the input expression as a function (because there's a rule to rewrite it), while the `PD` in the output is more like a data type (because there's no rule to rewrite it). |
64,335 | How do I sync Calendar-Evolution between laptop (Ubuntu 10-10) and desktop (Ubuntu 11-04)? Information for new Ubuntu One users provided a warning and FAQ link, but the link is broken. | 2011/10/05 | [
"https://askubuntu.com/questions/64335",
"https://askubuntu.com",
"https://askubuntu.com/users/26219/"
]
| Yes, synchronizing calendar with Ubuntu One doesn't work. But you can use SyncEvolution to do that. There is also a GUI called Genesis to simplify. If you want an online solution, then you can also get an account at Funambol.com, or similar.
You could sync Evolutions data directory on Ubuntu One, but I wouldn't recommend it as it can have negative side effects. | Read Step-by-step methods here:
[Synchronize-evolution-data-among-computers-over-lan](https://help.ubuntu.com/community/SyncEvolution/synchronize-evolution-data-among-computers-over-lan)
**Source:** <https://help.ubuntu.com/community/SyncEvolution/> |
56,327,738 | I want to take message value, which is under message array and parameter name equal to documentId.(which is bold in bellow code)
bellow code which i have tried but not working as described above.
`dynamic obj = JsonConvert.DeserializeObject(JsonDATA);
var recid = obj.messages.message;`
**JSON Data**
```
{
"message": "Success",
"messages": [
{
"parameter": "documentId",
"message": "8111ffb4-dddc-4d94-b050-bf8fa050181f"
},
{
"parameter": "refNo",
"message": "INNT19/75254854"
}
]
}
```
Please Help me to take the particular value only in C#. | 2019/05/27 | [
"https://Stackoverflow.com/questions/56327738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9131197/"
]
| You need to get the message at the correct index in the messages-array:
```
dynamic obj = JsonConvert.DeserializeObject(JsonDATA);
var recid = obj.messages[0].message;
``` | As `messages` is an array in your JSON, If you need to read any property of perticular element of an array then you need to use **index**. Something like
```
var recid = obj.messages[0].message;
``` |
93,603 | We are looking for a song (artist and title).
[](https://i.stack.imgur.com/H98kr.png)
---
Other (independently solvable) puzzles of this type: [1](https://puzzling.stackexchange.com/questions/93441/fun-with-flags-part-1-something-different), [3](https://puzzling.stackexchange.com/questions/93817/fun-with-flags-part-3-what-used-to-be), [4](https://puzzling.stackexchange.com/questions/94515/fun-with-flags-part-4-a-pile-of-coasters), [5](https://puzzling.stackexchange.com/questions/94711/fun-with-flags-part-5-with-a-smile), [6](https://puzzling.stackexchange.com/questions/96773/fun-with-flags-part-6-left-right-left), [7](https://puzzling.stackexchange.com/questions/97350/fun-with-flags-part-7-attention-please), [8](https://puzzling.stackexchange.com/questions/97682/fun-with-flags-part-8-its-your-roll), [9](https://puzzling.stackexchange.com/questions/98072/fun-with-flags-part-9-a-different-design), [10](https://puzzling.stackexchange.com/questions/98671/fun-with-flags-part-10-dont-lose-count). | 2020/02/11 | [
"https://puzzling.stackexchange.com/questions/93603",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/60396/"
]
| The song you are looking for is:
>
> **[AFRICA](https://en.wikipedia.org/wiki/Africa_(Toto_song))**, by the band **TOTO**
>
>
>
How? Well, first note that @legodude5000 (go upvote their answer!) has done a lot of the heavy lifting here and managed in the majority of cases to:
>
> Identify which two countries' flags have been merged to form each of the combination flags in the puzzle. There are just a few corrections to be made (red text in the following image):
>
>
>
> [](https://i.stack.imgur.com/36uGw.png)
>
>
>
Now, note that these are all:
>
> Countries on the African mainland
>
>
>
And if you:
>
> Draw lines on a map of Africa connecting each flag-merged pair of countries, you get the following image:
>
>
>
> [](https://i.stack.imgur.com/oBwTT.png)
>
> *Map courtesy of Google Maps*
>
>
>
Hence we have:
>
> The name of the band **TOTO** spelled out using pairs of flags from countries in **AFRICA**, which just so happens to be the title of one of their biggest hits!
>
>
> | Partial answer because I'm not certain where to go from here, possibly because I've made some sort of error.
I noticed that
>
> Each flag appears to be a combination of two flags from different African countries.
>
>
>
A graphic showing this:
>
> [](https://i.stack.imgur.com/IQvmk.png)
>
>
>
And some observations:
>
> - Each country is used twice, except for South Sudan and Gabon, which are each used once on only the seventh flag.
> - Not every combination is set in stone; for example the ninth flag could also be Central African Republic + Namibia to fit the color scheme but not the pattern, or + South Sudan (though now Kenya would only be used once)
> - Some possible trains of thought were that the "chain of countries" between flags might be useful, in which case I have:
> - `Egypt, Libya, Chad, Sudan`- `Mauritania, Liberia`- `Central African Republic, Democratic Republic of Congo, Kenya`- `Zambia, Botswana, Namibia, Angola`- `South Sudan, Gabon [no wrap around]`- Right now, the tags don't help with whether I should rely on word patterns between country names, geographic knowledge of where the countries are or what their capitals are, historical knowledge of similarities between these countries, etc. I'll leave it to someone with more knowledge and time than I to work from here unless I have an epiphany of some kind.
>
>
>
>
Later edit:
>
> I think the ninth combination might actually be The Ghana, not Kenya, but the colors are still slightly off
> [](https://i.stack.imgur.com/WHHvU.png)
>
>
> |
58,351,458 | I have the following data frame with column 'Name' having a pattern '///' in its values
```
data = [['a1','yahoo', 'apple'], ['a2','gma///il', 'mango'], ['a3','amazon', 'papaya'],
['a4','bi///ng', 'guava']]
df = pd.DataFrame(data, columns = ['ID', 'Name', 'Info'])
```
I need to extract the entire row from this data frame if the column 'Name' has Value having a pattern '///' in it. I have tried the following code but getting a empty dataframe.
```
new_df = df.loc[df['Name'] == '///']
```
My expected output should give me a data frame like this:
```
data_new = [['a2','gma///il', 'mango'],['a4','bi///ng', 'guava']]
new_df = pd.DataFrame(data, columns = ['ID', 'Name', 'Info'])
print(new_df)
``` | 2019/10/12 | [
"https://Stackoverflow.com/questions/58351458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8791858/"
]
| Use `Series.str.contains`:
```
import pandas as pd
data = [['a1','yahoo', 'apple'], ['a2','gma///il', 'mango'],
['a3','amazon', 'papaya'],['a4','bi///ng', 'guava']]
df = pd.DataFrame(data, columns = ['ID', 'Name', 'Info'])
print (df[df["Name"].str.contains("///")])
#
ID Name Info
1 a2 gma///il mango
3 a4 bi///ng guava
``` | If you want to filter on perticular one column then use this solution
```py
import numpy as np
immport pandas as pd
data = [['a1','yahoo', 'apple'], ['a2','gma///il', 'mango'], ['a3','amazon', 'papaya'],
['a4','bi///ng', 'guava']]
df = pd.DataFrame(data, columns = ['ID', 'Name', 'Info'])
mask = np.column_stack([df['Name'].str.contains(r"\///", na=False)])
df.loc[mask.any(axis=1)]
```
Output:
```
ID Name Info
1 a2 gma///il mango
3 a4 bi///ng guava
```
If you need filtering on all columns for some pattern then see the below solution
```py
import numpy as np
mask = np.column_stack([df[col].str.contains(r"\///", na=False) for col in df])
df.loc[mask.any(axis=1)]
```
Output:
```
ID Name Info
1 a2 gma///il mango
3 a4 bi///ng guava
``` |
58,351,458 | I have the following data frame with column 'Name' having a pattern '///' in its values
```
data = [['a1','yahoo', 'apple'], ['a2','gma///il', 'mango'], ['a3','amazon', 'papaya'],
['a4','bi///ng', 'guava']]
df = pd.DataFrame(data, columns = ['ID', 'Name', 'Info'])
```
I need to extract the entire row from this data frame if the column 'Name' has Value having a pattern '///' in it. I have tried the following code but getting a empty dataframe.
```
new_df = df.loc[df['Name'] == '///']
```
My expected output should give me a data frame like this:
```
data_new = [['a2','gma///il', 'mango'],['a4','bi///ng', 'guava']]
new_df = pd.DataFrame(data, columns = ['ID', 'Name', 'Info'])
print(new_df)
``` | 2019/10/12 | [
"https://Stackoverflow.com/questions/58351458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8791858/"
]
| Use `Series.str.contains`:
```
import pandas as pd
data = [['a1','yahoo', 'apple'], ['a2','gma///il', 'mango'],
['a3','amazon', 'papaya'],['a4','bi///ng', 'guava']]
df = pd.DataFrame(data, columns = ['ID', 'Name', 'Info'])
print (df[df["Name"].str.contains("///")])
#
ID Name Info
1 a2 gma///il mango
3 a4 bi///ng guava
``` | `DataFrame` has string function `contains()` for this
```
new_df = df[ df['Name'].str.contains('///') ]
``` |
28,581,544 | I am trying to find the difference of expenses of previous and current month in sql.
I have a table like this
```
Date Amount Category
2/18/2015 100 Salary
2/12/2015 150 Rent
2/21/2015 200 Allowances
1/4/2015 200 Salary
1/17/2015 50 Rent
1/20/2015 100 Allowances
```
Now I want a result like this
```
Category CurrentMonthAmount PreviousMonthAmount Difference
Salary 100 200 100
Rent 150 50 100
Allowances 200 100 100
``` | 2015/02/18 | [
"https://Stackoverflow.com/questions/28581544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3655932/"
]
| You can use something like below on the Calender Click Method:
```
DateTime date = Convert.ToDateTime(calendar.SelectedDate.ToString());
```
Here calendar is the ID of your calendar control!
Hope this helps. | Because it'is a web application i could just use JQuery UI
<http://jqueryui.com/datepicker/#inline>
```
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Display inline</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
<form runat="server" id="form1">
Date: <div id="datepicker"></div>
</form>
</body>
</html>
```
Here is a full API description <http://api.jqueryui.com/datepicker/>
May be this can help you as an alternative to do this also !\
There is also an Ajax library for .NET. you can try also: <http://www.codeproject.com/Tips/407460/How-to-use-ASP-NET-AJAX-Calender-Extender> |
12,592,994 | I have a page that is listing links to other websites. Each link is followed by a brief description of the site being linked to. I want the link text to be slightly larger than the description so I added a CSS class definition a.link, in which I define font-size as 16px. The complete list is inside a standard `<p>` tag and I have `<hr>` tags in between each list item. The problem is that only the first link in the list gets the new font-size. Each link after the first loses all styles defined not only in the link class definition, but in the `<p>` tag as well. If I remove the `<hr>` tags, every item in the list is correctly styled. If I wrap each link in the list inside a `<p>` tag, they also are styled correctly, but I'd rather not clutter up the list with extra tags if possible
Here is my stylesheet code:
```
#pane {
float: right;
width: 800px;
}
#pane p {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane p a.link { font-size: 16px; }
```
Here is a sample of the HTML generated:
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
```
Has anyone else encountered this behavior and found a way to fix it with adding `<p>` tags everywhere? | 2012/09/26 | [
"https://Stackoverflow.com/questions/12592994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1698803/"
]
| Good answer on the `<p>, <hr>`
You'd be better off not using the `<p>`.
Style the `a.link` into `display:block` which will display the a tag just like the enclosing `<p>` tag.
Also auto-close your `<hr/>`
Then correct your css selector: `#pane > a.link` if you need to actually be that selective. Probably better to just style `a.link` by itself, so that you can overwrite it with another selector later if required and not have issues with [specificity](http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/). | I think that you have problem with your HR tag,
in XHTML you have to close your tag.
So your HR should look like `<hr/>`
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr/>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr/>
</p>
</div>
```
Than it should work, no reason not to. |
12,592,994 | I have a page that is listing links to other websites. Each link is followed by a brief description of the site being linked to. I want the link text to be slightly larger than the description so I added a CSS class definition a.link, in which I define font-size as 16px. The complete list is inside a standard `<p>` tag and I have `<hr>` tags in between each list item. The problem is that only the first link in the list gets the new font-size. Each link after the first loses all styles defined not only in the link class definition, but in the `<p>` tag as well. If I remove the `<hr>` tags, every item in the list is correctly styled. If I wrap each link in the list inside a `<p>` tag, they also are styled correctly, but I'd rather not clutter up the list with extra tags if possible
Here is my stylesheet code:
```
#pane {
float: right;
width: 800px;
}
#pane p {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane p a.link { font-size: 16px; }
```
Here is a sample of the HTML generated:
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
```
Has anyone else encountered this behavior and found a way to fix it with adding `<p>` tags everywhere? | 2012/09/26 | [
"https://Stackoverflow.com/questions/12592994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1698803/"
]
| You can't put an `<hr>` inside of a `<p>` tag. If you try to, the browser automatically corrects it by closing the `<p>` tag for you. The second link is no longer within a `<p>` element and so your CSS rules no longer apply.
This is what the browser fixes your code to and why your CSS classes are no longer applied.
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
</p><hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<p></p>
</div>
``` | I think that you have problem with your HR tag,
in XHTML you have to close your tag.
So your HR should look like `<hr/>`
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr/>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr/>
</p>
</div>
```
Than it should work, no reason not to. |
12,592,994 | I have a page that is listing links to other websites. Each link is followed by a brief description of the site being linked to. I want the link text to be slightly larger than the description so I added a CSS class definition a.link, in which I define font-size as 16px. The complete list is inside a standard `<p>` tag and I have `<hr>` tags in between each list item. The problem is that only the first link in the list gets the new font-size. Each link after the first loses all styles defined not only in the link class definition, but in the `<p>` tag as well. If I remove the `<hr>` tags, every item in the list is correctly styled. If I wrap each link in the list inside a `<p>` tag, they also are styled correctly, but I'd rather not clutter up the list with extra tags if possible
Here is my stylesheet code:
```
#pane {
float: right;
width: 800px;
}
#pane p {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane p a.link { font-size: 16px; }
```
Here is a sample of the HTML generated:
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
```
Has anyone else encountered this behavior and found a way to fix it with adding `<p>` tags everywhere? | 2012/09/26 | [
"https://Stackoverflow.com/questions/12592994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1698803/"
]
| hr can't in p tag. you can change p tag to div
```
<!doctype html>
<html>
<head>
<style>
#pane {
float: right;
width: 800px;
}
#pane div {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane div a.large { font-size: 26px; }
</style>
</head>
<body>
<div id="pane">
<div>
<a href="http://www.google.com" class="large">Google</a> - For finding stuff
<hr/>
<a href="http://www.newegg.com" class="large">Newegg</a> - For buying stuff
<hr/>
</div>
</div>
</body>
</html>
``` | I think that you have problem with your HR tag,
in XHTML you have to close your tag.
So your HR should look like `<hr/>`
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr/>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr/>
</p>
</div>
```
Than it should work, no reason not to. |
12,592,994 | I have a page that is listing links to other websites. Each link is followed by a brief description of the site being linked to. I want the link text to be slightly larger than the description so I added a CSS class definition a.link, in which I define font-size as 16px. The complete list is inside a standard `<p>` tag and I have `<hr>` tags in between each list item. The problem is that only the first link in the list gets the new font-size. Each link after the first loses all styles defined not only in the link class definition, but in the `<p>` tag as well. If I remove the `<hr>` tags, every item in the list is correctly styled. If I wrap each link in the list inside a `<p>` tag, they also are styled correctly, but I'd rather not clutter up the list with extra tags if possible
Here is my stylesheet code:
```
#pane {
float: right;
width: 800px;
}
#pane p {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane p a.link { font-size: 16px; }
```
Here is a sample of the HTML generated:
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
```
Has anyone else encountered this behavior and found a way to fix it with adding `<p>` tags everywhere? | 2012/09/26 | [
"https://Stackoverflow.com/questions/12592994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1698803/"
]
| You can't put an `<hr>` inside of a `<p>` tag. If you try to, the browser automatically corrects it by closing the `<p>` tag for you. The second link is no longer within a `<p>` element and so your CSS rules no longer apply.
This is what the browser fixes your code to and why your CSS classes are no longer applied.
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
</p><hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<p></p>
</div>
``` | A collection of links is probably more suited to an unordered list (`UL`) perhaps inside a `NAV`.
Your issue is caused because `HR` inside of `P` doesn't [validate](http://validator.w3.org/) (and for a good reason). To confirm, I used this sample:
```
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
</body>
</html>
```
>
> A p element’s end tag may be omitted if the p element is immediately
> followed by an ...HR...
>
>
>
Source: <http://www.w3.org/TR/html-markup/p.html#p>
As @Bill pointed out, this leads to the parser closing the `P` when you don't expect it.
An `HR` [reprsents a thematic break](http://www.w3.org/TR/html-markup/hr.html#hr), which is semantically invalid inside of a paragraph. Logically (at least in English) a paragraph is supposed to [contain a collection of related thoughts on a single theme](http://en.wikipedia.org/wiki/Paragraph), so this makes sense. |
12,592,994 | I have a page that is listing links to other websites. Each link is followed by a brief description of the site being linked to. I want the link text to be slightly larger than the description so I added a CSS class definition a.link, in which I define font-size as 16px. The complete list is inside a standard `<p>` tag and I have `<hr>` tags in between each list item. The problem is that only the first link in the list gets the new font-size. Each link after the first loses all styles defined not only in the link class definition, but in the `<p>` tag as well. If I remove the `<hr>` tags, every item in the list is correctly styled. If I wrap each link in the list inside a `<p>` tag, they also are styled correctly, but I'd rather not clutter up the list with extra tags if possible
Here is my stylesheet code:
```
#pane {
float: right;
width: 800px;
}
#pane p {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane p a.link { font-size: 16px; }
```
Here is a sample of the HTML generated:
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
```
Has anyone else encountered this behavior and found a way to fix it with adding `<p>` tags everywhere? | 2012/09/26 | [
"https://Stackoverflow.com/questions/12592994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1698803/"
]
| Is it necessary to wrap it as a paragraph? If not then you can lose that tag and then it works without that clutter. <http://jsfiddle.net/bqhC9/>
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
</p>
<hr>
<p>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
</p>
<hr>
</div>
``` | hr can't in p tag. you can change p tag to div
```
<!doctype html>
<html>
<head>
<style>
#pane {
float: right;
width: 800px;
}
#pane div {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane div a.large { font-size: 26px; }
</style>
</head>
<body>
<div id="pane">
<div>
<a href="http://www.google.com" class="large">Google</a> - For finding stuff
<hr/>
<a href="http://www.newegg.com" class="large">Newegg</a> - For buying stuff
<hr/>
</div>
</div>
</body>
</html>
``` |
12,592,994 | I have a page that is listing links to other websites. Each link is followed by a brief description of the site being linked to. I want the link text to be slightly larger than the description so I added a CSS class definition a.link, in which I define font-size as 16px. The complete list is inside a standard `<p>` tag and I have `<hr>` tags in between each list item. The problem is that only the first link in the list gets the new font-size. Each link after the first loses all styles defined not only in the link class definition, but in the `<p>` tag as well. If I remove the `<hr>` tags, every item in the list is correctly styled. If I wrap each link in the list inside a `<p>` tag, they also are styled correctly, but I'd rather not clutter up the list with extra tags if possible
Here is my stylesheet code:
```
#pane {
float: right;
width: 800px;
}
#pane p {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane p a.link { font-size: 16px; }
```
Here is a sample of the HTML generated:
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
```
Has anyone else encountered this behavior and found a way to fix it with adding `<p>` tags everywhere? | 2012/09/26 | [
"https://Stackoverflow.com/questions/12592994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1698803/"
]
| Is it necessary to wrap it as a paragraph? If not then you can lose that tag and then it works without that clutter. <http://jsfiddle.net/bqhC9/>
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
</p>
<hr>
<p>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
</p>
<hr>
</div>
``` | I think that you have problem with your HR tag,
in XHTML you have to close your tag.
So your HR should look like `<hr/>`
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr/>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr/>
</p>
</div>
```
Than it should work, no reason not to. |
12,592,994 | I have a page that is listing links to other websites. Each link is followed by a brief description of the site being linked to. I want the link text to be slightly larger than the description so I added a CSS class definition a.link, in which I define font-size as 16px. The complete list is inside a standard `<p>` tag and I have `<hr>` tags in between each list item. The problem is that only the first link in the list gets the new font-size. Each link after the first loses all styles defined not only in the link class definition, but in the `<p>` tag as well. If I remove the `<hr>` tags, every item in the list is correctly styled. If I wrap each link in the list inside a `<p>` tag, they also are styled correctly, but I'd rather not clutter up the list with extra tags if possible
Here is my stylesheet code:
```
#pane {
float: right;
width: 800px;
}
#pane p {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane p a.link { font-size: 16px; }
```
Here is a sample of the HTML generated:
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
```
Has anyone else encountered this behavior and found a way to fix it with adding `<p>` tags everywhere? | 2012/09/26 | [
"https://Stackoverflow.com/questions/12592994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1698803/"
]
| A collection of links is probably more suited to an unordered list (`UL`) perhaps inside a `NAV`.
Your issue is caused because `HR` inside of `P` doesn't [validate](http://validator.w3.org/) (and for a good reason). To confirm, I used this sample:
```
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
</body>
</html>
```
>
> A p element’s end tag may be omitted if the p element is immediately
> followed by an ...HR...
>
>
>
Source: <http://www.w3.org/TR/html-markup/p.html#p>
As @Bill pointed out, this leads to the parser closing the `P` when you don't expect it.
An `HR` [reprsents a thematic break](http://www.w3.org/TR/html-markup/hr.html#hr), which is semantically invalid inside of a paragraph. Logically (at least in English) a paragraph is supposed to [contain a collection of related thoughts on a single theme](http://en.wikipedia.org/wiki/Paragraph), so this makes sense. | I think that you have problem with your HR tag,
in XHTML you have to close your tag.
So your HR should look like `<hr/>`
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr/>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr/>
</p>
</div>
```
Than it should work, no reason not to. |
12,592,994 | I have a page that is listing links to other websites. Each link is followed by a brief description of the site being linked to. I want the link text to be slightly larger than the description so I added a CSS class definition a.link, in which I define font-size as 16px. The complete list is inside a standard `<p>` tag and I have `<hr>` tags in between each list item. The problem is that only the first link in the list gets the new font-size. Each link after the first loses all styles defined not only in the link class definition, but in the `<p>` tag as well. If I remove the `<hr>` tags, every item in the list is correctly styled. If I wrap each link in the list inside a `<p>` tag, they also are styled correctly, but I'd rather not clutter up the list with extra tags if possible
Here is my stylesheet code:
```
#pane {
float: right;
width: 800px;
}
#pane p {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane p a.link { font-size: 16px; }
```
Here is a sample of the HTML generated:
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
```
Has anyone else encountered this behavior and found a way to fix it with adding `<p>` tags everywhere? | 2012/09/26 | [
"https://Stackoverflow.com/questions/12592994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1698803/"
]
| You can't put an `<hr>` inside of a `<p>` tag. If you try to, the browser automatically corrects it by closing the `<p>` tag for you. The second link is no longer within a `<p>` element and so your CSS rules no longer apply.
This is what the browser fixes your code to and why your CSS classes are no longer applied.
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
</p><hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<p></p>
</div>
``` | hr can't in p tag. you can change p tag to div
```
<!doctype html>
<html>
<head>
<style>
#pane {
float: right;
width: 800px;
}
#pane div {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane div a.large { font-size: 26px; }
</style>
</head>
<body>
<div id="pane">
<div>
<a href="http://www.google.com" class="large">Google</a> - For finding stuff
<hr/>
<a href="http://www.newegg.com" class="large">Newegg</a> - For buying stuff
<hr/>
</div>
</div>
</body>
</html>
``` |
12,592,994 | I have a page that is listing links to other websites. Each link is followed by a brief description of the site being linked to. I want the link text to be slightly larger than the description so I added a CSS class definition a.link, in which I define font-size as 16px. The complete list is inside a standard `<p>` tag and I have `<hr>` tags in between each list item. The problem is that only the first link in the list gets the new font-size. Each link after the first loses all styles defined not only in the link class definition, but in the `<p>` tag as well. If I remove the `<hr>` tags, every item in the list is correctly styled. If I wrap each link in the list inside a `<p>` tag, they also are styled correctly, but I'd rather not clutter up the list with extra tags if possible
Here is my stylesheet code:
```
#pane {
float: right;
width: 800px;
}
#pane p {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane p a.link { font-size: 16px; }
```
Here is a sample of the HTML generated:
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
```
Has anyone else encountered this behavior and found a way to fix it with adding `<p>` tags everywhere? | 2012/09/26 | [
"https://Stackoverflow.com/questions/12592994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1698803/"
]
| You can't put an `<hr>` inside of a `<p>` tag. If you try to, the browser automatically corrects it by closing the `<p>` tag for you. The second link is no longer within a `<p>` element and so your CSS rules no longer apply.
This is what the browser fixes your code to and why your CSS classes are no longer applied.
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
</p><hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<p></p>
</div>
``` | Good answer on the `<p>, <hr>`
You'd be better off not using the `<p>`.
Style the `a.link` into `display:block` which will display the a tag just like the enclosing `<p>` tag.
Also auto-close your `<hr/>`
Then correct your css selector: `#pane > a.link` if you need to actually be that selective. Probably better to just style `a.link` by itself, so that you can overwrite it with another selector later if required and not have issues with [specificity](http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/). |
12,592,994 | I have a page that is listing links to other websites. Each link is followed by a brief description of the site being linked to. I want the link text to be slightly larger than the description so I added a CSS class definition a.link, in which I define font-size as 16px. The complete list is inside a standard `<p>` tag and I have `<hr>` tags in between each list item. The problem is that only the first link in the list gets the new font-size. Each link after the first loses all styles defined not only in the link class definition, but in the `<p>` tag as well. If I remove the `<hr>` tags, every item in the list is correctly styled. If I wrap each link in the list inside a `<p>` tag, they also are styled correctly, but I'd rather not clutter up the list with extra tags if possible
Here is my stylesheet code:
```
#pane {
float: right;
width: 800px;
}
#pane p {
margin-left: 15px;
font-family: verdana;
font-size: 12px;
}
#pane p a.link { font-size: 16px; }
```
Here is a sample of the HTML generated:
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
```
Has anyone else encountered this behavior and found a way to fix it with adding `<p>` tags everywhere? | 2012/09/26 | [
"https://Stackoverflow.com/questions/12592994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1698803/"
]
| Is it necessary to wrap it as a paragraph? If not then you can lose that tag and then it works without that clutter. <http://jsfiddle.net/bqhC9/>
```
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
</p>
<hr>
<p>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
</p>
<hr>
</div>
``` | A collection of links is probably more suited to an unordered list (`UL`) perhaps inside a `NAV`.
Your issue is caused because `HR` inside of `P` doesn't [validate](http://validator.w3.org/) (and for a good reason). To confirm, I used this sample:
```
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="pane">
<p>
<a href="http://www.google.com" class="link">Google</a> - For finding stuff
<hr>
<a href="http://www.newegg.com" class="link">Newegg</a> - For buying stuff
<hr>
</p>
</div>
</body>
</html>
```
>
> A p element’s end tag may be omitted if the p element is immediately
> followed by an ...HR...
>
>
>
Source: <http://www.w3.org/TR/html-markup/p.html#p>
As @Bill pointed out, this leads to the parser closing the `P` when you don't expect it.
An `HR` [reprsents a thematic break](http://www.w3.org/TR/html-markup/hr.html#hr), which is semantically invalid inside of a paragraph. Logically (at least in English) a paragraph is supposed to [contain a collection of related thoughts on a single theme](http://en.wikipedia.org/wiki/Paragraph), so this makes sense. |
69,593,730 | Using Admin-sdk, Is there a way to delete a particular provider from a user record in firebase?
For eg:
Assume a given user has the following providers linked to his account
1. password
2. google.com
3. facebook.com
Say, I would like to revoke the user's ability to login via facebook to his account. Can this be done using admin sdk.
I could only find an api to unlink a provider (which is client side api. This will require the firebase-issued-idToken of the user). | 2021/10/16 | [
"https://Stackoverflow.com/questions/69593730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6179988/"
]
| You need to declare the variable first, and then assign it values on separate lines.
```
pragma solidity ^0.8;
contract MyContract {
mapping(address => bool) public myMap;
constructor() {
myMap[address(0x123)] = true;
myMap[address(0x456)] = false;
myMap[address(0x789)] = true;
}
}
``` | Unfortunately, you can't. See the Solidity documentation for details on the reasons why. Your only option is to iterate through the keys.
If you don't know your set of keys ahead of time, you'll have to keep the keys in a separate array inside your contract. |
30,109,014 | I am trying to extract the length of an integer column but I get this error as below. Can someone share their thoughts on this? Thanks.
**`Error: Argument type mismatch in function LENGTH: first argument is type int64`** | 2015/05/07 | [
"https://Stackoverflow.com/questions/30109014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1049893/"
]
| I might be wrong, but these two must be your major problems:
1. `signaling_server.send(...` I am not seeing any target here, so guessing that the server just broadcasts this message to everyone. When you are sending an sdp to already established peer connection, you are bound to get the error which you are getting now. My suggesting would be to add a target id in the message, either the server can forward it to that particular peer or, server can just broadcast, but `event_handler` of the peer can check if the target id of message is same as it's own id, if not, just ignore the message.
2. `onicecandidate` event, you are broadcasting the ICE candidates to all remote peers, again this is meant for single peer, another issue might be, `addIceCandidate` on PeerConnection before setting it's local and remote description would throw error, you need to some sort of mechanism to handle this( add ICE candidates only after setting the connections descriptions).
finally a suggestion. I am guessing `peer_connection` is an Array, if you change it Object, you can remove the redundancy of `locate_peer_connection`,
you can do something like.
```
if(peer_connection[signal.id]){
//do something...
}else{
peer_connection[signal.id] = new PeerConnection(...
}
``` | i had the same problem when i was implementing one-to-many rtc broadcast, and what mido22 said is right. you might be sending/resetting existing established peer object with other incoming client. you have to create new RTCPeerConenction object for every new incoming client. the general work flow would be as follow.
```
peerconnection=[];//empty array
```
then you initialize your media devices with getUserMedia
and store media stream into global variable so that it can be added when creating offer.
once this is done you inform your singalling server with unique id
your signalling server may then broadcast this to all clients except from which it is received. each client will then check if that unique id does exist in there peerconnection array and like mido22 said you can do this as
```
if(peerconnection[signal.id])
{
//do something with existing peerconnections
}
else
{
peerconnection[signal.id]=new RTCPeerConnection({"stun_server_address"});
//register peerconnection[signal.id].onicecandidate callback
//register peerconnection[signal.id].onaddstream callback
//createoffer
//if local stream is ready then
peerconnection[signal.id].addStream(localStream);
//and rest of the stuff go as it is like in one-to-one call..
//setLocalDescriptor setRemoteDescriptor
}
``` |
48,129,014 | I'm trying to write my own boolean "abstract" with some additional functions.
```
@forward
abstract MyBool(Bool) {
public inline function new(b:Bool) {
this = b;
}
@:from
public static inline function fromBool(b:Bool):MyBool {
return new MyBool(b);
}
@:to
public inline function toBool():Bool {
return this;
}
// some additional functions
}
```
In principal this works fine:
```
var t:T = true;
if(t) {
trace("1");
}
t.someStrangeMethod();
```
However @:forward does not forward basic boolean-operators like "!":
```
var f:T = false;
if(!f) { // fails here, because "!" is not defined as an operator for MyBool ...
trace("2");
}
```
The error message is "MyBool should be Bool", which I find quite strange because MyBool is an abstract of a Bool with @:forward annotation *and* there is a @:to-method.
Of course there are some easy workarounds. One could either use:
```
if(!f.toBool()) {
trace("2");
}
```
and/or add a function annotated with @:op(!A) to the abstract:
```
@:op(!A)
public inline function notOp():Bool {
return !this;
}
```
However I do not like both methods:
* I dislike adding @:op(...) to MyBool, because creating a method for each possible operator would require much code (Maybe not with a boolean, but e.g. with an Int, Float, ...).
* I dislike using !var.toBool(). If someone has already written quite some code (s)he does not want to go through all of it, when (s)he simply wants to change Bool to a MyBool ... I mean of course (s)he could also cast Bool to MyBool whenever adding new code, but that can be horrible too.
So I was wondering if anyone has a better idea? Is there maybe another "@:forward"-like compiling metadata, I do not know about yet? | 2018/01/06 | [
"https://Stackoverflow.com/questions/48129014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3009636/"
]
| There's an open feature request regarding this:
[Can @:forward also forward underlying operator overloads? (#5035)](https://github.com/HaxeFoundation/haxe/issues/5035)
One way to make your code example work is to allow implicit conversions with `to Bool`. I'm not entirely sure why the equivalent `@:to` function doesn't work here, as the Haxe Manual states that ["Class field casts have the same semantics"](https://haxe.org/manual/types-abstract-implicit-casts.html).
```
abstract MyBool(Bool) to Bool {
```
Apart from that, I think the only options is to declare an `@:op` function for each operator you want to support. If declared without a body, the underlying type's operator will be forwarded:
```
@:op(!A) function notOp():MyBool;
``` | If your main goal is to just add methods to the `Bool` type, then perhaps avoid the problem altogether by instead creating a class that adds methods to Bool via static extension (documented in the Haxe manual). This method would eliminate the need for operator forwarding. |
717,939 | I recently restarted after an update on 15.10, and now the keyboard on my laptop (Lenovo Thinkpad Yoga) doesn't work. I can't even ctrl-alt-[N] to get to a virtual terminal, nor does a USB keyboard work. The keyboard *does* work in BIOS setup and GRUB mode, but that's it. Also, the touchscreen stopped working at the same time. I had also changed a line in a xorg.conf.d file, affecting the synaptics driver prior to this, but I can't work out why this would kill the keyboard and touchscreen. | 2016/01/07 | [
"https://askubuntu.com/questions/717939",
"https://askubuntu.com",
"https://askubuntu.com/users/4749/"
]
| NetworkManager includes an `nmcli` program, which has a `monitor` command. Here is what its output looks like for me when I disconnect then connect to a Wi-Fi access point:
```
$ nmcli monitor
There's no primary connection
wlp4s0: unavailable
Networkmanager is now in the 'disconnected' state
wlp4s0: disconnected
wlp4s0: using connection 'CyberShadowPC'
wlp4s0: connecting (prepare)
Networkmanager is now in the 'connecting' state
wlp4s0: connecting (configuring)
wlp4s0: connecting (need authentication)
wlp4s0: connecting (prepare)
wlp4s0: connecting (configuring)
wlp4s0: connecting (getting IP configuration)
wlp4s0: connecting (checking IP connectivity)
wlp4s0: connecting (starting secondary connections)
wlp4s0: connected
Networkmanager is now in the 'connected' state
'CyberShadowPC' is now the primary connection
```
It looks like it should be easy to parse its output and run appropriate actions as necessary. Here's a bash script which runs a command when a NetworkManager connection becomes the active primary one:
```
#!/bin/bash
set -euo pipefail
connection_name=CyberShadowPC
command=(notify-send "Connected to $connection_name!")
LC_ALL=C nmcli monitor | \
while read -r line
do
if [[ "$line" == "'$connection_name' is now the primary connection" ]]
then
"${command[@]}"
fi
done
``` | While it's certainly possible to use `dbus` , personally I'd go with simple bash while loop + awk
```
while [ "$(iwconfig 2> /dev/null | awk '/Access Point/ && /XX:YY:ZZ:11:22:33/ {print "true" }')" != "true" ]; do : ; sleep 0.25 ;done ; echo DONE
```
What is happening there ? While loop keeps running, testing output of `iwconfig` filtered out with `awk`. So far as the `awk` doesn't find the mac address of the access that you want to connect to, loop continues running. As soon as `awk` sees that you've associated with that particular AP , the test condition `[ "String1" != "String2" ]` becomes false, loop breaks , and goes on to the `echo DONE` command. Of course , `echo DONE` is what can be replaced with the program that you want to run.
This command can be ran manually or placed into a script, and the script added to the Startup Application list.
Simple, straightforward, and does the job. Like I said in the beginning, it is possible to use dbus , but is not as simple. |
717,939 | I recently restarted after an update on 15.10, and now the keyboard on my laptop (Lenovo Thinkpad Yoga) doesn't work. I can't even ctrl-alt-[N] to get to a virtual terminal, nor does a USB keyboard work. The keyboard *does* work in BIOS setup and GRUB mode, but that's it. Also, the touchscreen stopped working at the same time. I had also changed a line in a xorg.conf.d file, affecting the synaptics driver prior to this, but I can't work out why this would kill the keyboard and touchscreen. | 2016/01/07 | [
"https://askubuntu.com/questions/717939",
"https://askubuntu.com",
"https://askubuntu.com/users/4749/"
]
| Run
>
> dbus-monitor --system "type='signal',interface='org.freedesktop.NetworkManager'"
>
>
>
Then change your wifi connection. You will get the signal that property changed. It returns a "PrimaryConnection" that is activated.
You can then query the activated connection and see if it matches the connection you are interested in.
For example:
>
> qdbus --system --literal org.freedesktop.NetworkManager
> /org/freedesktop/NetworkManager/ActiveConnection/Whatever
> org.freedesktop.DBus.Properties.GetAll
> org.freedesktop.NetworkManager.Connection.Active
>
>
> qdbus --system --literal org.freedesktop.NetworkManager
> /org/freedesktop/NetworkManager/AccessPoint/Whatever org.freedesktop.DBus.Properties.Get
> org.freedesktop.NetworkManager.AccessPoint.Ssid
>
>
>
(probably just simpler to run iwgetid -r after you detect the property change) | While it's certainly possible to use `dbus` , personally I'd go with simple bash while loop + awk
```
while [ "$(iwconfig 2> /dev/null | awk '/Access Point/ && /XX:YY:ZZ:11:22:33/ {print "true" }')" != "true" ]; do : ; sleep 0.25 ;done ; echo DONE
```
What is happening there ? While loop keeps running, testing output of `iwconfig` filtered out with `awk`. So far as the `awk` doesn't find the mac address of the access that you want to connect to, loop continues running. As soon as `awk` sees that you've associated with that particular AP , the test condition `[ "String1" != "String2" ]` becomes false, loop breaks , and goes on to the `echo DONE` command. Of course , `echo DONE` is what can be replaced with the program that you want to run.
This command can be ran manually or placed into a script, and the script added to the Startup Application list.
Simple, straightforward, and does the job. Like I said in the beginning, it is possible to use dbus , but is not as simple. |
58,539,906 | I have widget with following info:
```
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="328dp"
android:minHeight="56dp"
android:updatePeriodMillis="1000000"
android:initialLayout="@layout/home_widget"
android:previewImage="@drawable/widget_preview"
android:resizeMode="horizontal"
android:widgetCategory="home_screen">
</appwidget-provider>
```
The layout (not necessary to put it here) looks good on my device, but I found out that the widget is not applicable for smaller screen. Can somebody help me solve this issue? Instead of not displaying this widget on smaller devices, I would like to alter the layout (maybe create another xml layout for it). I tried putting `minWidth` to dimens, but as I have all the widget elements positioned and sized precisely, this approach would cut the widget. Thanks for any help. | 2019/10/24 | [
"https://Stackoverflow.com/questions/58539906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1619036/"
]
| becuase of we use diffrent screen size and diffrent density of the screen to solve this dont use dp or sp rather than use sdp or ssp which is provide in this library
<https://github.com/intuit/sdp>
And this make your space preamter screen responsive | If you want widget width match as parent then you can use the `android:layout_width="match_parent"`
`match_parent` defines the width/height as match of parent, there is not any need to define the static dimen. It is adjust the width according to parent's width.
I hope its work for you. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.