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
|
---|---|---|---|---|---|
3,318,270 |
I am new to java. I think this is the simplest problem but even i dont know how to solve this problem. I have one text file. In that file i have some words like below :
**good
bad
efficiency**
I want to add list of words into another by using java program. My output want to be like this
**good bad
good efficiency
bad efficiency**
How to get this using java program. I tried search for some ideas. But i wont get any idea. Please suggest me any ideas. Thanks in advance.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3318270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341868/"
] |
LINQ itself doesn't contain anything for this - I'd would use a normal `foreach` loop:
```
foreach (var value in objects.Select(x => x.someProperty)
.Where(y => y != null))
{
SomeFunction(value);
}
```
Or if you want a query expression version:
```
var query = from obj in objects
let value = obj.SomeProperty
where value != null
select value;
foreach (var value in query)
{
SomeFunction(value);
}
```
(I prefer the first version, personally.)
Note that I've performed the selection before the filtering to avoid calling the property twice unnecessarily. It's not for performance reasons so much as I didn't like the redundancy :)
While you *can* use `ToList()` and call `ForEach()` on that, I prefer to use a straight `foreach` loop, as per [Eric's explanation](http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx). Basically `SomeFunction` must incur a side-effect to be useful, and LINQ is designed with side-effect-free functions in mind.
|
```
objects.where(i => i.someProperty != null)
.ToList()
.ForEach(i=> SomeFunction(i.someProperty))
```
|
3,318,270 |
I am new to java. I think this is the simplest problem but even i dont know how to solve this problem. I have one text file. In that file i have some words like below :
**good
bad
efficiency**
I want to add list of words into another by using java program. My output want to be like this
**good bad
good efficiency
bad efficiency**
How to get this using java program. I tried search for some ideas. But i wont get any idea. Please suggest me any ideas. Thanks in advance.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3318270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341868/"
] |
LINQ itself doesn't contain anything for this - I'd would use a normal `foreach` loop:
```
foreach (var value in objects.Select(x => x.someProperty)
.Where(y => y != null))
{
SomeFunction(value);
}
```
Or if you want a query expression version:
```
var query = from obj in objects
let value = obj.SomeProperty
where value != null
select value;
foreach (var value in query)
{
SomeFunction(value);
}
```
(I prefer the first version, personally.)
Note that I've performed the selection before the filtering to avoid calling the property twice unnecessarily. It's not for performance reasons so much as I didn't like the redundancy :)
While you *can* use `ToList()` and call `ForEach()` on that, I prefer to use a straight `foreach` loop, as per [Eric's explanation](http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx). Basically `SomeFunction` must incur a side-effect to be useful, and LINQ is designed with side-effect-free functions in mind.
|
You can move the if statement into a Where clause of Linq:
```
IEnumerable<MyClass> objects = ...
foreach(MyClass obj in objects.Where(obj => obj.someProperty != null)
{
SomeFunction(obj.someProperty);
}
```
Going further, you can use List's `ForEach` method:
```
IEnumerable<MyClass> objects = ...
objects.Where(obj => obj.someProperty != null).ToList()
.ForEach(obj => SomeFunction(obj.someProperty));
```
That's making the code slightly harder to read, though. Usually I stick with the typical `foreach` statement versus List's `ForEach`, but it's entirely up to you.
|
3,318,270 |
I am new to java. I think this is the simplest problem but even i dont know how to solve this problem. I have one text file. In that file i have some words like below :
**good
bad
efficiency**
I want to add list of words into another by using java program. My output want to be like this
**good bad
good efficiency
bad efficiency**
How to get this using java program. I tried search for some ideas. But i wont get any idea. Please suggest me any ideas. Thanks in advance.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3318270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341868/"
] |
LINQ itself doesn't contain anything for this - I'd would use a normal `foreach` loop:
```
foreach (var value in objects.Select(x => x.someProperty)
.Where(y => y != null))
{
SomeFunction(value);
}
```
Or if you want a query expression version:
```
var query = from obj in objects
let value = obj.SomeProperty
where value != null
select value;
foreach (var value in query)
{
SomeFunction(value);
}
```
(I prefer the first version, personally.)
Note that I've performed the selection before the filtering to avoid calling the property twice unnecessarily. It's not for performance reasons so much as I didn't like the redundancy :)
While you *can* use `ToList()` and call `ForEach()` on that, I prefer to use a straight `foreach` loop, as per [Eric's explanation](http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx). Basically `SomeFunction` must incur a side-effect to be useful, and LINQ is designed with side-effect-free functions in mind.
|
Although it can be done with Linq, sometimes its not always necessary. Sometimes you lose readability of your code. For your particular example, I'd leave it alone.
|
3,318,270 |
I am new to java. I think this is the simplest problem but even i dont know how to solve this problem. I have one text file. In that file i have some words like below :
**good
bad
efficiency**
I want to add list of words into another by using java program. My output want to be like this
**good bad
good efficiency
bad efficiency**
How to get this using java program. I tried search for some ideas. But i wont get any idea. Please suggest me any ideas. Thanks in advance.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3318270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341868/"
] |
LINQ itself doesn't contain anything for this - I'd would use a normal `foreach` loop:
```
foreach (var value in objects.Select(x => x.someProperty)
.Where(y => y != null))
{
SomeFunction(value);
}
```
Or if you want a query expression version:
```
var query = from obj in objects
let value = obj.SomeProperty
where value != null
select value;
foreach (var value in query)
{
SomeFunction(value);
}
```
(I prefer the first version, personally.)
Note that I've performed the selection before the filtering to avoid calling the property twice unnecessarily. It's not for performance reasons so much as I didn't like the redundancy :)
While you *can* use `ToList()` and call `ForEach()` on that, I prefer to use a straight `foreach` loop, as per [Eric's explanation](http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx). Basically `SomeFunction` must incur a side-effect to be useful, and LINQ is designed with side-effect-free functions in mind.
|
LINQ is used to create a result, so if you use it to call `SomeFunction` for each found item, you would be using a side effect of the code to do the main work. Things like that makes the code harder to maintain.
You can use it to filter out the non-null values, though:
```
foreach(MyClass obj in objects.Where(o => o.someProperty != null)) {
SomeFunction(obj.someProperty);
}
```
|
3,318,270 |
I am new to java. I think this is the simplest problem but even i dont know how to solve this problem. I have one text file. In that file i have some words like below :
**good
bad
efficiency**
I want to add list of words into another by using java program. My output want to be like this
**good bad
good efficiency
bad efficiency**
How to get this using java program. I tried search for some ideas. But i wont get any idea. Please suggest me any ideas. Thanks in advance.
|
2010/07/23
|
[
"https://Stackoverflow.com/questions/3318270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/341868/"
] |
LINQ itself doesn't contain anything for this - I'd would use a normal `foreach` loop:
```
foreach (var value in objects.Select(x => x.someProperty)
.Where(y => y != null))
{
SomeFunction(value);
}
```
Or if you want a query expression version:
```
var query = from obj in objects
let value = obj.SomeProperty
where value != null
select value;
foreach (var value in query)
{
SomeFunction(value);
}
```
(I prefer the first version, personally.)
Note that I've performed the selection before the filtering to avoid calling the property twice unnecessarily. It's not for performance reasons so much as I didn't like the redundancy :)
While you *can* use `ToList()` and call `ForEach()` on that, I prefer to use a straight `foreach` loop, as per [Eric's explanation](http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx). Basically `SomeFunction` must incur a side-effect to be useful, and LINQ is designed with side-effect-free functions in mind.
|
One option is to use the pattern outlined in the book [Linq In Action](http://linqinaction.net/) which uses an extension method to add a ForEach operator to IEnumerable<>
From the book:
```
public static void ForEach<T> (this IEnumerable<T> source, Action<T> func)
{
foreach (var item in source)
func(item)
}
```
Then you can use that like this:
```
(from foo in fooList
where foo.Name.Contains("bar")
select foo)
.ForEach(foo => Console.WriteLine(foo.Name));
```
|
3,897,587 |
I'm working on a pretty simple iPhone app at the moment. I have a UIWebView with a UIToolBar at the bottom of it with a button on it. I've built it all through code, although I did create an empty NIB as I am hoping to get Facebook Connect working with it eventually and have had problems when I don't set it up with this empty NIB in the past...
I've added another button that just kind of sits in the middle of the page (for testing purposes while I build) that calls a UIActionSheet. When you select a button on the UIActionSheet, I have the UIImagePickerController popping up on top of everything, in order to select an image from my Camera Roll.
The problem is that when my UIImagePickerController has closed (either by selecting an image or by pressing the cancel button), all of the content on my page has been pushed down by 20 pixels...
While it is true that I could just shift the frames of all of my elements up by 20 pixels, that feels "hacky", and while I love to hack, I'd rather figure out why this is going on.
Has anyone ever encountered this? How did you fix it?
Thank you,
--d
|
2010/10/09
|
[
"https://Stackoverflow.com/questions/3897587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383125/"
] |
`--lim` means "take one from the value of `lim` and use the result".
The alternative `lim--` would be "use the value of `lim` and then take one away".
So if `lim` starts at 1000 the first time the loop executes it will have the value `999` before it is checked to see if it's greater than 0. If it were `lim--` then the value that would be checked would be `1000`, but it would still have the value of 999 at the end of the iteration through the loop. This is important at the start and end of the loop.
The MSDN as a page on this [Prefix Increment and Decrement Operators](http://msdn.microsoft.com/en-us/library/6syyw3ba%28v=VS.100%29.aspx)
>
> When the operator appears before its operand, the operand is incremented or decremented and its new value is the result of the expression.
>
>
>
|
`--lim` or `lim--` is a short hand of `lim = lim - 1`, So maybe author want to use this syntax to better clarify!
|
3,897,587 |
I'm working on a pretty simple iPhone app at the moment. I have a UIWebView with a UIToolBar at the bottom of it with a button on it. I've built it all through code, although I did create an empty NIB as I am hoping to get Facebook Connect working with it eventually and have had problems when I don't set it up with this empty NIB in the past...
I've added another button that just kind of sits in the middle of the page (for testing purposes while I build) that calls a UIActionSheet. When you select a button on the UIActionSheet, I have the UIImagePickerController popping up on top of everything, in order to select an image from my Camera Roll.
The problem is that when my UIImagePickerController has closed (either by selecting an image or by pressing the cancel button), all of the content on my page has been pushed down by 20 pixels...
While it is true that I could just shift the frames of all of my elements up by 20 pixels, that feels "hacky", and while I love to hack, I'd rather figure out why this is going on.
Has anyone ever encountered this? How did you fix it?
Thank you,
--d
|
2010/10/09
|
[
"https://Stackoverflow.com/questions/3897587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383125/"
] |
`--lim` means "take one from the value of `lim` and use the result".
The alternative `lim--` would be "use the value of `lim` and then take one away".
So if `lim` starts at 1000 the first time the loop executes it will have the value `999` before it is checked to see if it's greater than 0. If it were `lim--` then the value that would be checked would be `1000`, but it would still have the value of 999 at the end of the iteration through the loop. This is important at the start and end of the loop.
The MSDN as a page on this [Prefix Increment and Decrement Operators](http://msdn.microsoft.com/en-us/library/6syyw3ba%28v=VS.100%29.aspx)
>
> When the operator appears before its operand, the operand is incremented or decremented and its new value is the result of the expression.
>
>
>
|
Excluding David's example (where the initial test of 'c' causes the loop body to never be executed, and thus lim is not decremented), and the possibility that lim is initially less than or equal to 1 (in which case the getchar() would not be executed), the code is equivalent to the following:
```
c=getchar();
while (lim > 1 && c != EOF && c != '\n')
{
lim = lim - 1;
/* Original body of loop */
c=getchar();
}
```
Both exceptions are rather unlikely and probably inconsequential, so you could use the above code if it's easier to understand.
|
3,897,587 |
I'm working on a pretty simple iPhone app at the moment. I have a UIWebView with a UIToolBar at the bottom of it with a button on it. I've built it all through code, although I did create an empty NIB as I am hoping to get Facebook Connect working with it eventually and have had problems when I don't set it up with this empty NIB in the past...
I've added another button that just kind of sits in the middle of the page (for testing purposes while I build) that calls a UIActionSheet. When you select a button on the UIActionSheet, I have the UIImagePickerController popping up on top of everything, in order to select an image from my Camera Roll.
The problem is that when my UIImagePickerController has closed (either by selecting an image or by pressing the cancel button), all of the content on my page has been pushed down by 20 pixels...
While it is true that I could just shift the frames of all of my elements up by 20 pixels, that feels "hacky", and while I love to hack, I'd rather figure out why this is going on.
Has anyone ever encountered this? How did you fix it?
Thank you,
--d
|
2010/10/09
|
[
"https://Stackoverflow.com/questions/3897587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383125/"
] |
Are you sure?
```
#include <stdio.h>
int main()
{
int lim = 10;
while (--lim > 0 && printf("%d\n",lim));
}
```
ouput:
```
9
8
7
6
5
4
3
2
1
```
|
`--lim` or `lim--` is a short hand of `lim = lim - 1`, So maybe author want to use this syntax to better clarify!
|
3,897,587 |
I'm working on a pretty simple iPhone app at the moment. I have a UIWebView with a UIToolBar at the bottom of it with a button on it. I've built it all through code, although I did create an empty NIB as I am hoping to get Facebook Connect working with it eventually and have had problems when I don't set it up with this empty NIB in the past...
I've added another button that just kind of sits in the middle of the page (for testing purposes while I build) that calls a UIActionSheet. When you select a button on the UIActionSheet, I have the UIImagePickerController popping up on top of everything, in order to select an image from my Camera Roll.
The problem is that when my UIImagePickerController has closed (either by selecting an image or by pressing the cancel button), all of the content on my page has been pushed down by 20 pixels...
While it is true that I could just shift the frames of all of my elements up by 20 pixels, that feels "hacky", and while I love to hack, I'd rather figure out why this is going on.
Has anyone ever encountered this? How did you fix it?
Thank you,
--d
|
2010/10/09
|
[
"https://Stackoverflow.com/questions/3897587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383125/"
] |
Try to compile and run this code. It should be somewhat enlightening.
```
#include <stdio.h>
int main()
{
int lim = 10;
while (--lim > 0 && 1 > 32)
printf("I should never get here\n");
printf("%d\n",lim); // lim is now 9
}
```
Oh look, `lim` is now `9` even though I never actually entered the loop because 1 isn't greater than 32.
|
`--lim` or `lim--` is a short hand of `lim = lim - 1`, So maybe author want to use this syntax to better clarify!
|
3,897,587 |
I'm working on a pretty simple iPhone app at the moment. I have a UIWebView with a UIToolBar at the bottom of it with a button on it. I've built it all through code, although I did create an empty NIB as I am hoping to get Facebook Connect working with it eventually and have had problems when I don't set it up with this empty NIB in the past...
I've added another button that just kind of sits in the middle of the page (for testing purposes while I build) that calls a UIActionSheet. When you select a button on the UIActionSheet, I have the UIImagePickerController popping up on top of everything, in order to select an image from my Camera Roll.
The problem is that when my UIImagePickerController has closed (either by selecting an image or by pressing the cancel button), all of the content on my page has been pushed down by 20 pixels...
While it is true that I could just shift the frames of all of my elements up by 20 pixels, that feels "hacky", and while I love to hack, I'd rather figure out why this is going on.
Has anyone ever encountered this? How did you fix it?
Thank you,
--d
|
2010/10/09
|
[
"https://Stackoverflow.com/questions/3897587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383125/"
] |
`--lim` means "take one from the value of `lim` and use the result".
The alternative `lim--` would be "use the value of `lim` and then take one away".
So if `lim` starts at 1000 the first time the loop executes it will have the value `999` before it is checked to see if it's greater than 0. If it were `lim--` then the value that would be checked would be `1000`, but it would still have the value of 999 at the end of the iteration through the loop. This is important at the start and end of the loop.
The MSDN as a page on this [Prefix Increment and Decrement Operators](http://msdn.microsoft.com/en-us/library/6syyw3ba%28v=VS.100%29.aspx)
>
> When the operator appears before its operand, the operand is incremented or decremented and its new value is the result of the expression.
>
>
>
|
Are you sure?
```
#include <stdio.h>
int main()
{
int lim = 10;
while (--lim > 0 && printf("%d\n",lim));
}
```
ouput:
```
9
8
7
6
5
4
3
2
1
```
|
3,897,587 |
I'm working on a pretty simple iPhone app at the moment. I have a UIWebView with a UIToolBar at the bottom of it with a button on it. I've built it all through code, although I did create an empty NIB as I am hoping to get Facebook Connect working with it eventually and have had problems when I don't set it up with this empty NIB in the past...
I've added another button that just kind of sits in the middle of the page (for testing purposes while I build) that calls a UIActionSheet. When you select a button on the UIActionSheet, I have the UIImagePickerController popping up on top of everything, in order to select an image from my Camera Roll.
The problem is that when my UIImagePickerController has closed (either by selecting an image or by pressing the cancel button), all of the content on my page has been pushed down by 20 pixels...
While it is true that I could just shift the frames of all of my elements up by 20 pixels, that feels "hacky", and while I love to hack, I'd rather figure out why this is going on.
Has anyone ever encountered this? How did you fix it?
Thank you,
--d
|
2010/10/09
|
[
"https://Stackoverflow.com/questions/3897587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383125/"
] |
Lim **is** decreasing, you probably made a mistake elsewhere. However, `--lim` is not quite equal to `lim = lim - 1`.
There are two operators to perform increment/decrement of a variable: pre-increment(or decrement), and post-increment(or decrement).
`++x` (pre-inc) and `x++` (post-inc) both modify the value of x by +1. So what's the difference?
When you use `x++` in an expression, the expression will consider x to have it's current value and **after** evaluating everything accordingly, increment that value by one. So...
```
int x = 5;
printf("%d", x++);
```
... will print out 5. HOWEVER, after the printf() line, the value of x will be 6.
Pre-increment works the other way round: the value of x it's first incremented, and then considered to evaluate the expression surrounding it. So...
```
int x = 5;
printf("%d", ++x);
```
... will print out 6 and, of course, the value of x will be 6 after that.
Of course, the same applies to the decrement operators.
Now, the assignment operation (`x = x + 1`) evaluates to the value assigned, after the assignment happened, so its behavior is actually similar to `++x`, not `x++`.
|
`--lim` or `lim--` is a short hand of `lim = lim - 1`, So maybe author want to use this syntax to better clarify!
|
3,897,587 |
I'm working on a pretty simple iPhone app at the moment. I have a UIWebView with a UIToolBar at the bottom of it with a button on it. I've built it all through code, although I did create an empty NIB as I am hoping to get Facebook Connect working with it eventually and have had problems when I don't set it up with this empty NIB in the past...
I've added another button that just kind of sits in the middle of the page (for testing purposes while I build) that calls a UIActionSheet. When you select a button on the UIActionSheet, I have the UIImagePickerController popping up on top of everything, in order to select an image from my Camera Roll.
The problem is that when my UIImagePickerController has closed (either by selecting an image or by pressing the cancel button), all of the content on my page has been pushed down by 20 pixels...
While it is true that I could just shift the frames of all of my elements up by 20 pixels, that feels "hacky", and while I love to hack, I'd rather figure out why this is going on.
Has anyone ever encountered this? How did you fix it?
Thank you,
--d
|
2010/10/09
|
[
"https://Stackoverflow.com/questions/3897587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383125/"
] |
Lim **is** decreasing, you probably made a mistake elsewhere. However, `--lim` is not quite equal to `lim = lim - 1`.
There are two operators to perform increment/decrement of a variable: pre-increment(or decrement), and post-increment(or decrement).
`++x` (pre-inc) and `x++` (post-inc) both modify the value of x by +1. So what's the difference?
When you use `x++` in an expression, the expression will consider x to have it's current value and **after** evaluating everything accordingly, increment that value by one. So...
```
int x = 5;
printf("%d", x++);
```
... will print out 5. HOWEVER, after the printf() line, the value of x will be 6.
Pre-increment works the other way round: the value of x it's first incremented, and then considered to evaluate the expression surrounding it. So...
```
int x = 5;
printf("%d", ++x);
```
... will print out 6 and, of course, the value of x will be 6 after that.
Of course, the same applies to the decrement operators.
Now, the assignment operation (`x = x + 1`) evaluates to the value assigned, after the assignment happened, so its behavior is actually similar to `++x`, not `x++`.
|
Excluding David's example (where the initial test of 'c' causes the loop body to never be executed, and thus lim is not decremented), and the possibility that lim is initially less than or equal to 1 (in which case the getchar() would not be executed), the code is equivalent to the following:
```
c=getchar();
while (lim > 1 && c != EOF && c != '\n')
{
lim = lim - 1;
/* Original body of loop */
c=getchar();
}
```
Both exceptions are rather unlikely and probably inconsequential, so you could use the above code if it's easier to understand.
|
3,897,587 |
I'm working on a pretty simple iPhone app at the moment. I have a UIWebView with a UIToolBar at the bottom of it with a button on it. I've built it all through code, although I did create an empty NIB as I am hoping to get Facebook Connect working with it eventually and have had problems when I don't set it up with this empty NIB in the past...
I've added another button that just kind of sits in the middle of the page (for testing purposes while I build) that calls a UIActionSheet. When you select a button on the UIActionSheet, I have the UIImagePickerController popping up on top of everything, in order to select an image from my Camera Roll.
The problem is that when my UIImagePickerController has closed (either by selecting an image or by pressing the cancel button), all of the content on my page has been pushed down by 20 pixels...
While it is true that I could just shift the frames of all of my elements up by 20 pixels, that feels "hacky", and while I love to hack, I'd rather figure out why this is going on.
Has anyone ever encountered this? How did you fix it?
Thank you,
--d
|
2010/10/09
|
[
"https://Stackoverflow.com/questions/3897587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383125/"
] |
`--lim` means "take one from the value of `lim` and use the result".
The alternative `lim--` would be "use the value of `lim` and then take one away".
So if `lim` starts at 1000 the first time the loop executes it will have the value `999` before it is checked to see if it's greater than 0. If it were `lim--` then the value that would be checked would be `1000`, but it would still have the value of 999 at the end of the iteration through the loop. This is important at the start and end of the loop.
The MSDN as a page on this [Prefix Increment and Decrement Operators](http://msdn.microsoft.com/en-us/library/6syyw3ba%28v=VS.100%29.aspx)
>
> When the operator appears before its operand, the operand is incremented or decremented and its new value is the result of the expression.
>
>
>
|
Lim **is** decreasing, you probably made a mistake elsewhere. However, `--lim` is not quite equal to `lim = lim - 1`.
There are two operators to perform increment/decrement of a variable: pre-increment(or decrement), and post-increment(or decrement).
`++x` (pre-inc) and `x++` (post-inc) both modify the value of x by +1. So what's the difference?
When you use `x++` in an expression, the expression will consider x to have it's current value and **after** evaluating everything accordingly, increment that value by one. So...
```
int x = 5;
printf("%d", x++);
```
... will print out 5. HOWEVER, after the printf() line, the value of x will be 6.
Pre-increment works the other way round: the value of x it's first incremented, and then considered to evaluate the expression surrounding it. So...
```
int x = 5;
printf("%d", ++x);
```
... will print out 6 and, of course, the value of x will be 6 after that.
Of course, the same applies to the decrement operators.
Now, the assignment operation (`x = x + 1`) evaluates to the value assigned, after the assignment happened, so its behavior is actually similar to `++x`, not `x++`.
|
3,897,587 |
I'm working on a pretty simple iPhone app at the moment. I have a UIWebView with a UIToolBar at the bottom of it with a button on it. I've built it all through code, although I did create an empty NIB as I am hoping to get Facebook Connect working with it eventually and have had problems when I don't set it up with this empty NIB in the past...
I've added another button that just kind of sits in the middle of the page (for testing purposes while I build) that calls a UIActionSheet. When you select a button on the UIActionSheet, I have the UIImagePickerController popping up on top of everything, in order to select an image from my Camera Roll.
The problem is that when my UIImagePickerController has closed (either by selecting an image or by pressing the cancel button), all of the content on my page has been pushed down by 20 pixels...
While it is true that I could just shift the frames of all of my elements up by 20 pixels, that feels "hacky", and while I love to hack, I'd rather figure out why this is going on.
Has anyone ever encountered this? How did you fix it?
Thank you,
--d
|
2010/10/09
|
[
"https://Stackoverflow.com/questions/3897587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383125/"
] |
`--lim` means "take one from the value of `lim` and use the result".
The alternative `lim--` would be "use the value of `lim` and then take one away".
So if `lim` starts at 1000 the first time the loop executes it will have the value `999` before it is checked to see if it's greater than 0. If it were `lim--` then the value that would be checked would be `1000`, but it would still have the value of 999 at the end of the iteration through the loop. This is important at the start and end of the loop.
The MSDN as a page on this [Prefix Increment and Decrement Operators](http://msdn.microsoft.com/en-us/library/6syyw3ba%28v=VS.100%29.aspx)
>
> When the operator appears before its operand, the operand is incremented or decremented and its new value is the result of the expression.
>
>
>
|
Try to compile and run this code. It should be somewhat enlightening.
```
#include <stdio.h>
int main()
{
int lim = 10;
while (--lim > 0 && 1 > 32)
printf("I should never get here\n");
printf("%d\n",lim); // lim is now 9
}
```
Oh look, `lim` is now `9` even though I never actually entered the loop because 1 isn't greater than 32.
|
3,897,587 |
I'm working on a pretty simple iPhone app at the moment. I have a UIWebView with a UIToolBar at the bottom of it with a button on it. I've built it all through code, although I did create an empty NIB as I am hoping to get Facebook Connect working with it eventually and have had problems when I don't set it up with this empty NIB in the past...
I've added another button that just kind of sits in the middle of the page (for testing purposes while I build) that calls a UIActionSheet. When you select a button on the UIActionSheet, I have the UIImagePickerController popping up on top of everything, in order to select an image from my Camera Roll.
The problem is that when my UIImagePickerController has closed (either by selecting an image or by pressing the cancel button), all of the content on my page has been pushed down by 20 pixels...
While it is true that I could just shift the frames of all of my elements up by 20 pixels, that feels "hacky", and while I love to hack, I'd rather figure out why this is going on.
Has anyone ever encountered this? How did you fix it?
Thank you,
--d
|
2010/10/09
|
[
"https://Stackoverflow.com/questions/3897587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383125/"
] |
Try to compile and run this code. It should be somewhat enlightening.
```
#include <stdio.h>
int main()
{
int lim = 10;
while (--lim > 0 && 1 > 32)
printf("I should never get here\n");
printf("%d\n",lim); // lim is now 9
}
```
Oh look, `lim` is now `9` even though I never actually entered the loop because 1 isn't greater than 32.
|
Excluding David's example (where the initial test of 'c' causes the loop body to never be executed, and thus lim is not decremented), and the possibility that lim is initially less than or equal to 1 (in which case the getchar() would not be executed), the code is equivalent to the following:
```
c=getchar();
while (lim > 1 && c != EOF && c != '\n')
{
lim = lim - 1;
/* Original body of loop */
c=getchar();
}
```
Both exceptions are rather unlikely and probably inconsequential, so you could use the above code if it's easier to understand.
|
36,591,811 |
Hello i am working on this fix for 2-3 hours.. it was working at first, i moved some of my code to another file and required that file to make it cleaner then boom doesnt work anymore.
```
require('./mongooschema.js');
console.log(Mesaj);
/// SECOND FILE mongooschema.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://"""""""/"""""""');
var Schema = mongoose.Schema;
var mesajSchema = new Schema({
mesaj: 'String',
size: 'string'
});
var Mesaj = mongoose.model('Mesaj', mesajSchema);
module.exports = Mesaj;
```
|
2016/04/13
|
[
"https://Stackoverflow.com/questions/36591811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4627680/"
] |
>
> Is CTI still valid as approach?
>
>
>
I think that if the number of the categories are in the order of tenth, and not of hundredth, then yes.
>
> How could I assign the correct attributes set to a product?
>
>
>
You could add to each category row the table name of corresponding table of attributes, and for each attribute table, the id of the row will be the id of the corresponding product (so that you can define it as a foreign key for the products table).
|
In almost all situations it is "wrong" to have 55 tables with identical schema. Making it 1 table is better. But then it gets you into the nightmare called "Entity-Attribute-Value".
Pick a few "attributes" that you usually need to search on. Put the rest into a JSON string in a single column. [More details](http://mysql.rjweb.org/doc.php/eav)
Your schema is not quite EAV. It is an interesting variant; what does it stand for? I don't think I have seen this as an alternative to EAV. I don't yet have an opinion on whether this replaces the set of problems that EAV has with a different set of problems. Or maybe it is better.
What client language will you be using? You will need to turn `category.name` into `attr_laptop` in order to `SELECT ... from attr_laptop ...` This implies dynamically creating the queries. (This is quite easy in most client languages. It is also possible, though a little clumsy, in Stored Routines.)
|
50,145,882 |
I'm trying to write a program that calculates the union and intersection of two sets of numbers. The sets can be represented using arrays
So my code is working perfectly for the intersection, but for the union, it does something really weird.
The code should do this:
```
Enter number of elements in set A: 5
Enter set A: 0 4 2 1 6
Enter number of elements in set B: 3
Enter set B: 1 9 3
Union: 0 1 2 3 4 6 9
Intersection: 1
```
My errors for the union are that they are not arranged in order and also it shouldn't print the repeated numbers and it does.
I like don't know what's wrong or how to fix it. Its definitely something wrong with the logic of the union function but idk
```
#include <stdio.h>
#include <stdlib.h>
void print_array(int[], int);
void compute_union(int[], int[], int, int[]);
void compute_intersection(int, int[], int[], int[]);
int size1, size2;
int union_size=0;
int main()
{
printf("Enter the size of your first array: ");
scanf("%d", &size1);
printf("Enter the size of your second array: ");
scanf("%d", &size2);
printf("Enter the values of your array: ");
int i,j;
int arr1[size1];
int arr2[size2];
int set_union[size1+size2];
int set_intersection[(size1+size2)/2];
for(i=0; i<size1; i++)
{
scanf("%d", &arr1[i]);
}
for(j=0; j<size2; j++)
{
scanf("%d", &arr2[j]);
}
//print_array(arr1,size1);
compute_union(arr1, arr2, size1+size2, set_union);
//print_array(set_union, size1+size2);
compute_intersection((size1+size2)/2, arr1, arr2, set_intersection);
//print_array(set_intersection, (size1+size2)/2);
return 0;
}
void print_array(int array[], int size)
{
int x;
for(x=0; x<size; x++)
{
printf("%d ", array[x]);
}
printf("\n");
}
void compute_union(int s1[], int s2[], int max_size, int set_union[]){
int i=0;
int j=0;
while(i<size1 && j<size2)
{
if(s1[i]<s2[j])
{
set_union[i+j]=s1[i];
i++;
}
else if (s1[i]>s2[j])
{
set_union[i+j]=s2[j];
j++;
}
else
{
set_union[i+j]=s1[i];
i++;
j++;
}
}
//add remainder of nonempty array
while(i<size1)
{
set_union[i+j]=s1[i];
i++;
}
while(j<size2)
{
set_union[i+j]=s2[j];
j++;
}
print_array(set_union, size1+size2);
}
void compute_intersection(int max_size, int set1[], int set2[], int
set_intersection[])
{
int i, j, n=0;
for(i=0; i<size1; i++)
{
for(j=0; j<size2; j++)
{
if(set1[i]==set2[j])
{
set_intersection[k]=set1[i];
n++;
break;
}
}
}
print_array(set_intersection, n);
}
```
|
2018/05/03
|
[
"https://Stackoverflow.com/questions/50145882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9476436/"
] |
You never sort your arrays, but it looks like the `compute_union()` routine is assuming sorted arrays.
|
You are not looking if an element is already stored in the union set array or not.
If you don't want to sort the arrays first, you could use a function like
```
int srch(int *a, int size, int x)
{
for(int i=0; i<size; ++i)
{
if(a[i]==x)
{
return 1;
}
}
return 0;
}
```
to perform linear search. `srch()` will return `1` for successful search and `0` otherwise.
Modify the `compute_union()` function to
```
int compute_union(int s1[], int s2[], int max_size, int set_union[]){
int i=0;
int cursize=0;
for(i=0; i<size1; ++i)
{
if(srch(set_union, cursize, s1[i])==0)
{
set_union[cursize++] = s1[i];
}
}
for(i=0; i<size2; ++i)
{
if(srch(set_union, cursize, s2[i])==0)
{
set_union[cursize++] = s2[i];
}
}
return cursize;
}
```
and `compute_intersection()` to
```
int compute_intersection(int max_size, int set1[], int set2[], int set_intersection[])
{
int i, j, cursize=0;
for(i=0; i<size1; i++)
{
for(j=0; j<size2; j++)
{
if(set1[i]==set2[j])
{
set_intersection[cursize++]=set1[i];
break;
}
}
}
return cursize;
}
```
These 2 functions will return the size of the union and intersection sets respectively.
Let the size be stored in variables `usize` and `nsize`.
```
usize = compute_union(arr1, arr2, size1+size2, set_union);
print_array(set_union, usize);
nsize = compute_intersection((size1+size2)/2, arr1, arr2, set_intersection);
print_array(set_intersection, nsize);
```
For the inputs in the question, output will be
```
Union: 0 4 2 1 6 9 3
Intersection: 1
```
Better way would be to sort the elements of the input arrays and then examining them though.
|
50,145,882 |
I'm trying to write a program that calculates the union and intersection of two sets of numbers. The sets can be represented using arrays
So my code is working perfectly for the intersection, but for the union, it does something really weird.
The code should do this:
```
Enter number of elements in set A: 5
Enter set A: 0 4 2 1 6
Enter number of elements in set B: 3
Enter set B: 1 9 3
Union: 0 1 2 3 4 6 9
Intersection: 1
```
My errors for the union are that they are not arranged in order and also it shouldn't print the repeated numbers and it does.
I like don't know what's wrong or how to fix it. Its definitely something wrong with the logic of the union function but idk
```
#include <stdio.h>
#include <stdlib.h>
void print_array(int[], int);
void compute_union(int[], int[], int, int[]);
void compute_intersection(int, int[], int[], int[]);
int size1, size2;
int union_size=0;
int main()
{
printf("Enter the size of your first array: ");
scanf("%d", &size1);
printf("Enter the size of your second array: ");
scanf("%d", &size2);
printf("Enter the values of your array: ");
int i,j;
int arr1[size1];
int arr2[size2];
int set_union[size1+size2];
int set_intersection[(size1+size2)/2];
for(i=0; i<size1; i++)
{
scanf("%d", &arr1[i]);
}
for(j=0; j<size2; j++)
{
scanf("%d", &arr2[j]);
}
//print_array(arr1,size1);
compute_union(arr1, arr2, size1+size2, set_union);
//print_array(set_union, size1+size2);
compute_intersection((size1+size2)/2, arr1, arr2, set_intersection);
//print_array(set_intersection, (size1+size2)/2);
return 0;
}
void print_array(int array[], int size)
{
int x;
for(x=0; x<size; x++)
{
printf("%d ", array[x]);
}
printf("\n");
}
void compute_union(int s1[], int s2[], int max_size, int set_union[]){
int i=0;
int j=0;
while(i<size1 && j<size2)
{
if(s1[i]<s2[j])
{
set_union[i+j]=s1[i];
i++;
}
else if (s1[i]>s2[j])
{
set_union[i+j]=s2[j];
j++;
}
else
{
set_union[i+j]=s1[i];
i++;
j++;
}
}
//add remainder of nonempty array
while(i<size1)
{
set_union[i+j]=s1[i];
i++;
}
while(j<size2)
{
set_union[i+j]=s2[j];
j++;
}
print_array(set_union, size1+size2);
}
void compute_intersection(int max_size, int set1[], int set2[], int
set_intersection[])
{
int i, j, n=0;
for(i=0; i<size1; i++)
{
for(j=0; j<size2; j++)
{
if(set1[i]==set2[j])
{
set_intersection[k]=set1[i];
n++;
break;
}
}
}
print_array(set_intersection, n);
}
```
|
2018/05/03
|
[
"https://Stackoverflow.com/questions/50145882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9476436/"
] |
>
> My errors for the union are that they are not arranged in order and also it shouldnt print the repeated numbers and it does.
>
>
>
Sets typically are not ordered data structures, unless you specifically need an ordered set. But the second requirement about non repeated numbers is valid for a set; a set should not contain duplicates. One approach here would be to simply iterate the `set_union` array and check if a value exists before adding it. Only new values would be added, something like this:
```
int compute_union(int s1[], int s2[], int max_size, int set_union[]) {
int num_elements = 0;
for (int i=0; i < size1; ++i) {
int present = 0;
for (int n=0; n < num_elements; ++n) {
if (set_union[n] == s1[i]) {
present = 1;
break;
}
}
if (present == 0) {
set_union[num_elements] = s1[i];
++num_elements;
}
}
for (int i=0; i < size2; ++i) {
int present = 0;
for (int n=0; n < num_elements; ++n) {
if (set_union[n] == s2[i]) {
present = 1;
break;
}
}
if (present == 0) {
set_union[num_elements] = s2[i];
++num_elements;
}
}
// return the size of the actual set
return num_elements;
}
```
This isn't a very efficient way of implementing a set. One typical way a set is implemented is using a hash map. In this case, we can lookup to see if a value is contained within the set in constant time. The above approach means we have to potentially scan the entire array "set" to check for a value.
|
You are not looking if an element is already stored in the union set array or not.
If you don't want to sort the arrays first, you could use a function like
```
int srch(int *a, int size, int x)
{
for(int i=0; i<size; ++i)
{
if(a[i]==x)
{
return 1;
}
}
return 0;
}
```
to perform linear search. `srch()` will return `1` for successful search and `0` otherwise.
Modify the `compute_union()` function to
```
int compute_union(int s1[], int s2[], int max_size, int set_union[]){
int i=0;
int cursize=0;
for(i=0; i<size1; ++i)
{
if(srch(set_union, cursize, s1[i])==0)
{
set_union[cursize++] = s1[i];
}
}
for(i=0; i<size2; ++i)
{
if(srch(set_union, cursize, s2[i])==0)
{
set_union[cursize++] = s2[i];
}
}
return cursize;
}
```
and `compute_intersection()` to
```
int compute_intersection(int max_size, int set1[], int set2[], int set_intersection[])
{
int i, j, cursize=0;
for(i=0; i<size1; i++)
{
for(j=0; j<size2; j++)
{
if(set1[i]==set2[j])
{
set_intersection[cursize++]=set1[i];
break;
}
}
}
return cursize;
}
```
These 2 functions will return the size of the union and intersection sets respectively.
Let the size be stored in variables `usize` and `nsize`.
```
usize = compute_union(arr1, arr2, size1+size2, set_union);
print_array(set_union, usize);
nsize = compute_intersection((size1+size2)/2, arr1, arr2, set_intersection);
print_array(set_intersection, nsize);
```
For the inputs in the question, output will be
```
Union: 0 4 2 1 6 9 3
Intersection: 1
```
Better way would be to sort the elements of the input arrays and then examining them though.
|
27,672,337 |
I'm getting this error when submitting the form:
>
> org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account
>
>
>
Here are my entities:
**Account:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Account {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String login;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
@ManyToOne
@JoinColumn(name = "team_id")
private Team team;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private List<Team> ownedTeams;
...
```
**Team:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Team {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false)
private Account owner;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "team")
private List<Account> members;
...
```
Here's a part of the Controller:
```
@ModelAttribute("team")
public Team createTeamObject() {
return new Team();
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.GET)
public String getCreateTeam(@ModelAttribute("team") Team team, Principal principal) {
logger.info("Welcome to the create team page!");
Account owner = accountService.findOneByLogin(principal.getName());
team.setOwner(owner);
team.setMembers(new AutoPopulatingList<Account>(Account.class));
return "teams";
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.POST)
public String postCreateTeam(@ModelAttribute("team") Team team) {
logger.info("Team created!");
teamService.save(team);
return "redirect:/teams.html";
}
```
And the form:
```
<form:form commandName="team" id="teamForm">
<div class="form-group">
<label>Name</label>
<form:input path="name" cssClass="form-control" />
</div>
<div class="form-group" id="row-template">
<label>Members</label>
<form:select path="members[0].id" cssClass="form-control" data-live-search="true" >
<form:options items="${accounts}" itemValue="id" />
</form:select>
...
</div>
<form:hidden path="owner.id" />
</form:form>
```
What am I doing wrong?
|
2014/12/27
|
[
"https://Stackoverflow.com/questions/27672337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287404/"
] |
Since your id is auto generated value, don't send it from client side. I had a same issue. Make sure that you does't provide a value for auto generated attribute.
|
Be aware of Lombok .toBuilder() method - it is creating a new instance of the object, which can be pretty misleading, when you are trying to update the part of a child object.
Example:
```
public class User {
@OneToOne(...)
Field x;
}
```
```
@Builder(toBuilder = true)
public class Field {
String a;
String b;
}
```
```
@Transactional
public class UserService {
public updateUserField(User user) {
...
user.setX(user.getX().toBuilder().a("New value").build());
}
}
```
This will throw the PersistentObjectException without explicitly calling the userRepo.save method.
You need to do:
```
var x = user.getX();
x.setA("New Value");
```
|
27,672,337 |
I'm getting this error when submitting the form:
>
> org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account
>
>
>
Here are my entities:
**Account:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Account {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String login;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
@ManyToOne
@JoinColumn(name = "team_id")
private Team team;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private List<Team> ownedTeams;
...
```
**Team:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Team {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false)
private Account owner;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "team")
private List<Account> members;
...
```
Here's a part of the Controller:
```
@ModelAttribute("team")
public Team createTeamObject() {
return new Team();
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.GET)
public String getCreateTeam(@ModelAttribute("team") Team team, Principal principal) {
logger.info("Welcome to the create team page!");
Account owner = accountService.findOneByLogin(principal.getName());
team.setOwner(owner);
team.setMembers(new AutoPopulatingList<Account>(Account.class));
return "teams";
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.POST)
public String postCreateTeam(@ModelAttribute("team") Team team) {
logger.info("Team created!");
teamService.save(team);
return "redirect:/teams.html";
}
```
And the form:
```
<form:form commandName="team" id="teamForm">
<div class="form-group">
<label>Name</label>
<form:input path="name" cssClass="form-control" />
</div>
<div class="form-group" id="row-template">
<label>Members</label>
<form:select path="members[0].id" cssClass="form-control" data-live-search="true" >
<form:options items="${accounts}" itemValue="id" />
</form:select>
...
</div>
<form:hidden path="owner.id" />
</form:form>
```
What am I doing wrong?
|
2014/12/27
|
[
"https://Stackoverflow.com/questions/27672337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287404/"
] |
The error occurs because the **id** is set. Hibernate distinguishes between transient and detached objects and persist works only with transient objects.
```
isteamService.save(team);
```
in this operation can not be loaded id because is @GeneratedValue
|
Please, change `@OneToMany(cascade = CascadeType.ALL,..)` to `@OneToMany(cascade = CascadeType.REMOVE,...)` or another except `CascadeType.PERSIST` and the problem has been solved
|
27,672,337 |
I'm getting this error when submitting the form:
>
> org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account
>
>
>
Here are my entities:
**Account:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Account {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String login;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
@ManyToOne
@JoinColumn(name = "team_id")
private Team team;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private List<Team> ownedTeams;
...
```
**Team:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Team {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false)
private Account owner;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "team")
private List<Account> members;
...
```
Here's a part of the Controller:
```
@ModelAttribute("team")
public Team createTeamObject() {
return new Team();
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.GET)
public String getCreateTeam(@ModelAttribute("team") Team team, Principal principal) {
logger.info("Welcome to the create team page!");
Account owner = accountService.findOneByLogin(principal.getName());
team.setOwner(owner);
team.setMembers(new AutoPopulatingList<Account>(Account.class));
return "teams";
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.POST)
public String postCreateTeam(@ModelAttribute("team") Team team) {
logger.info("Team created!");
teamService.save(team);
return "redirect:/teams.html";
}
```
And the form:
```
<form:form commandName="team" id="teamForm">
<div class="form-group">
<label>Name</label>
<form:input path="name" cssClass="form-control" />
</div>
<div class="form-group" id="row-template">
<label>Members</label>
<form:select path="members[0].id" cssClass="form-control" data-live-search="true" >
<form:options items="${accounts}" itemValue="id" />
</form:select>
...
</div>
<form:hidden path="owner.id" />
</form:form>
```
What am I doing wrong?
|
2014/12/27
|
[
"https://Stackoverflow.com/questions/27672337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287404/"
] |
The error occurs because the **id** is set. Hibernate distinguishes between transient and detached objects and persist works only with transient objects.
```
isteamService.save(team);
```
in this operation can not be loaded id because is @GeneratedValue
|
Since your id is auto generated value, don't send it from client side. I had a same issue. Make sure that you does't provide a value for auto generated attribute.
|
27,672,337 |
I'm getting this error when submitting the form:
>
> org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account
>
>
>
Here are my entities:
**Account:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Account {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String login;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
@ManyToOne
@JoinColumn(name = "team_id")
private Team team;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private List<Team> ownedTeams;
...
```
**Team:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Team {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false)
private Account owner;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "team")
private List<Account> members;
...
```
Here's a part of the Controller:
```
@ModelAttribute("team")
public Team createTeamObject() {
return new Team();
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.GET)
public String getCreateTeam(@ModelAttribute("team") Team team, Principal principal) {
logger.info("Welcome to the create team page!");
Account owner = accountService.findOneByLogin(principal.getName());
team.setOwner(owner);
team.setMembers(new AutoPopulatingList<Account>(Account.class));
return "teams";
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.POST)
public String postCreateTeam(@ModelAttribute("team") Team team) {
logger.info("Team created!");
teamService.save(team);
return "redirect:/teams.html";
}
```
And the form:
```
<form:form commandName="team" id="teamForm">
<div class="form-group">
<label>Name</label>
<form:input path="name" cssClass="form-control" />
</div>
<div class="form-group" id="row-template">
<label>Members</label>
<form:select path="members[0].id" cssClass="form-control" data-live-search="true" >
<form:options items="${accounts}" itemValue="id" />
</form:select>
...
</div>
<form:hidden path="owner.id" />
</form:form>
```
What am I doing wrong?
|
2014/12/27
|
[
"https://Stackoverflow.com/questions/27672337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287404/"
] |
```
teamService.save(team);
```
Save method accepts only transient objects. What is the transient object you can find [here](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/objectstate.html)
`Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).`
You are getting the Team object and you are trying to persist it to the DB but that object has Account object in it and that Account object is detached (means that instance of that object has saved into the DB but that object is not in the session). Hibernate is trying to save it because of you have specified:
```
@OneToMany(cascade = CascadeType.ALL, ....
```
So, there are few ways how you can fix it:
1) do not use CascadeType.ALL configuration. Account object can be used for number of Teams (at least domain structure allows it) and update operation might update Account for ALL Teams -- it means that this operation should not be initiated with Team update.
I would remove cascade parameter from there (default value is no cascade operations), of if you really need use MERGE/DELETE configuration. But if you really need to persist it then see option #2
2) use 'saveOrUpdate()' method instead of 'save()'. 'saveOrUpdate()' method accepts transient and detached objects.
But the problem with this approach is in design: do you really need to insert/update account when you are saving Team object? I would split it in two operations and prevent updating Account from the Team.
Hope this helps.
|
Please, change `@OneToMany(cascade = CascadeType.ALL,..)` to `@OneToMany(cascade = CascadeType.REMOVE,...)` or another except `CascadeType.PERSIST` and the problem has been solved
|
27,672,337 |
I'm getting this error when submitting the form:
>
> org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account
>
>
>
Here are my entities:
**Account:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Account {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String login;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
@ManyToOne
@JoinColumn(name = "team_id")
private Team team;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private List<Team> ownedTeams;
...
```
**Team:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Team {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false)
private Account owner;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "team")
private List<Account> members;
...
```
Here's a part of the Controller:
```
@ModelAttribute("team")
public Team createTeamObject() {
return new Team();
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.GET)
public String getCreateTeam(@ModelAttribute("team") Team team, Principal principal) {
logger.info("Welcome to the create team page!");
Account owner = accountService.findOneByLogin(principal.getName());
team.setOwner(owner);
team.setMembers(new AutoPopulatingList<Account>(Account.class));
return "teams";
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.POST)
public String postCreateTeam(@ModelAttribute("team") Team team) {
logger.info("Team created!");
teamService.save(team);
return "redirect:/teams.html";
}
```
And the form:
```
<form:form commandName="team" id="teamForm">
<div class="form-group">
<label>Name</label>
<form:input path="name" cssClass="form-control" />
</div>
<div class="form-group" id="row-template">
<label>Members</label>
<form:select path="members[0].id" cssClass="form-control" data-live-search="true" >
<form:options items="${accounts}" itemValue="id" />
</form:select>
...
</div>
<form:hidden path="owner.id" />
</form:form>
```
What am I doing wrong?
|
2014/12/27
|
[
"https://Stackoverflow.com/questions/27672337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287404/"
] |
```
teamService.save(team);
```
Save method accepts only transient objects. What is the transient object you can find [here](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/objectstate.html)
`Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).`
You are getting the Team object and you are trying to persist it to the DB but that object has Account object in it and that Account object is detached (means that instance of that object has saved into the DB but that object is not in the session). Hibernate is trying to save it because of you have specified:
```
@OneToMany(cascade = CascadeType.ALL, ....
```
So, there are few ways how you can fix it:
1) do not use CascadeType.ALL configuration. Account object can be used for number of Teams (at least domain structure allows it) and update operation might update Account for ALL Teams -- it means that this operation should not be initiated with Team update.
I would remove cascade parameter from there (default value is no cascade operations), of if you really need use MERGE/DELETE configuration. But if you really need to persist it then see option #2
2) use 'saveOrUpdate()' method instead of 'save()'. 'saveOrUpdate()' method accepts transient and detached objects.
But the problem with this approach is in design: do you really need to insert/update account when you are saving Team object? I would split it in two operations and prevent updating Account from the Team.
Hope this helps.
|
The error occurs because the **id** is set. Hibernate distinguishes between transient and detached objects and persist works only with transient objects.
```
isteamService.save(team);
```
in this operation can not be loaded id because is @GeneratedValue
|
27,672,337 |
I'm getting this error when submitting the form:
>
> org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account
>
>
>
Here are my entities:
**Account:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Account {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String login;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
@ManyToOne
@JoinColumn(name = "team_id")
private Team team;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private List<Team> ownedTeams;
...
```
**Team:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Team {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false)
private Account owner;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "team")
private List<Account> members;
...
```
Here's a part of the Controller:
```
@ModelAttribute("team")
public Team createTeamObject() {
return new Team();
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.GET)
public String getCreateTeam(@ModelAttribute("team") Team team, Principal principal) {
logger.info("Welcome to the create team page!");
Account owner = accountService.findOneByLogin(principal.getName());
team.setOwner(owner);
team.setMembers(new AutoPopulatingList<Account>(Account.class));
return "teams";
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.POST)
public String postCreateTeam(@ModelAttribute("team") Team team) {
logger.info("Team created!");
teamService.save(team);
return "redirect:/teams.html";
}
```
And the form:
```
<form:form commandName="team" id="teamForm">
<div class="form-group">
<label>Name</label>
<form:input path="name" cssClass="form-control" />
</div>
<div class="form-group" id="row-template">
<label>Members</label>
<form:select path="members[0].id" cssClass="form-control" data-live-search="true" >
<form:options items="${accounts}" itemValue="id" />
</form:select>
...
</div>
<form:hidden path="owner.id" />
</form:form>
```
What am I doing wrong?
|
2014/12/27
|
[
"https://Stackoverflow.com/questions/27672337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287404/"
] |
Please, change `@OneToMany(cascade = CascadeType.ALL,..)` to `@OneToMany(cascade = CascadeType.REMOVE,...)` or another except `CascadeType.PERSIST` and the problem has been solved
|
This error happened for me when I tried to save a child entity and then pass the newly saved entity as parameter to a new parent object.
For instance:
`ChildA a = childAService.save(childAObject);`
`Parent parent = new Parent()`;
`parent.setChildA(a) // <=== Culprit`
`parentService.save(parent);`
Instead, do:
`ChildA a = new ChildA();`
`parent.setChildA(a)`
`parentService.save(parent)`
Hibernate handles the persisting of `a` for you, you don't have to do it yourself.
|
27,672,337 |
I'm getting this error when submitting the form:
>
> org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account
>
>
>
Here are my entities:
**Account:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Account {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String login;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
@ManyToOne
@JoinColumn(name = "team_id")
private Team team;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private List<Team> ownedTeams;
...
```
**Team:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Team {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false)
private Account owner;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "team")
private List<Account> members;
...
```
Here's a part of the Controller:
```
@ModelAttribute("team")
public Team createTeamObject() {
return new Team();
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.GET)
public String getCreateTeam(@ModelAttribute("team") Team team, Principal principal) {
logger.info("Welcome to the create team page!");
Account owner = accountService.findOneByLogin(principal.getName());
team.setOwner(owner);
team.setMembers(new AutoPopulatingList<Account>(Account.class));
return "teams";
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.POST)
public String postCreateTeam(@ModelAttribute("team") Team team) {
logger.info("Team created!");
teamService.save(team);
return "redirect:/teams.html";
}
```
And the form:
```
<form:form commandName="team" id="teamForm">
<div class="form-group">
<label>Name</label>
<form:input path="name" cssClass="form-control" />
</div>
<div class="form-group" id="row-template">
<label>Members</label>
<form:select path="members[0].id" cssClass="form-control" data-live-search="true" >
<form:options items="${accounts}" itemValue="id" />
</form:select>
...
</div>
<form:hidden path="owner.id" />
</form:form>
```
What am I doing wrong?
|
2014/12/27
|
[
"https://Stackoverflow.com/questions/27672337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287404/"
] |
```
teamService.save(team);
```
Save method accepts only transient objects. What is the transient object you can find [here](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/objectstate.html)
`Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).`
You are getting the Team object and you are trying to persist it to the DB but that object has Account object in it and that Account object is detached (means that instance of that object has saved into the DB but that object is not in the session). Hibernate is trying to save it because of you have specified:
```
@OneToMany(cascade = CascadeType.ALL, ....
```
So, there are few ways how you can fix it:
1) do not use CascadeType.ALL configuration. Account object can be used for number of Teams (at least domain structure allows it) and update operation might update Account for ALL Teams -- it means that this operation should not be initiated with Team update.
I would remove cascade parameter from there (default value is no cascade operations), of if you really need use MERGE/DELETE configuration. But if you really need to persist it then see option #2
2) use 'saveOrUpdate()' method instead of 'save()'. 'saveOrUpdate()' method accepts transient and detached objects.
But the problem with this approach is in design: do you really need to insert/update account when you are saving Team object? I would split it in two operations and prevent updating Account from the Team.
Hope this helps.
|
Since your id is auto generated value, don't send it from client side. I had a same issue. Make sure that you does't provide a value for auto generated attribute.
|
27,672,337 |
I'm getting this error when submitting the form:
>
> org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account
>
>
>
Here are my entities:
**Account:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Account {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String login;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
@ManyToOne
@JoinColumn(name = "team_id")
private Team team;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private List<Team> ownedTeams;
...
```
**Team:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Team {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false)
private Account owner;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "team")
private List<Account> members;
...
```
Here's a part of the Controller:
```
@ModelAttribute("team")
public Team createTeamObject() {
return new Team();
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.GET)
public String getCreateTeam(@ModelAttribute("team") Team team, Principal principal) {
logger.info("Welcome to the create team page!");
Account owner = accountService.findOneByLogin(principal.getName());
team.setOwner(owner);
team.setMembers(new AutoPopulatingList<Account>(Account.class));
return "teams";
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.POST)
public String postCreateTeam(@ModelAttribute("team") Team team) {
logger.info("Team created!");
teamService.save(team);
return "redirect:/teams.html";
}
```
And the form:
```
<form:form commandName="team" id="teamForm">
<div class="form-group">
<label>Name</label>
<form:input path="name" cssClass="form-control" />
</div>
<div class="form-group" id="row-template">
<label>Members</label>
<form:select path="members[0].id" cssClass="form-control" data-live-search="true" >
<form:options items="${accounts}" itemValue="id" />
</form:select>
...
</div>
<form:hidden path="owner.id" />
</form:form>
```
What am I doing wrong?
|
2014/12/27
|
[
"https://Stackoverflow.com/questions/27672337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287404/"
] |
```
teamService.save(team);
```
Save method accepts only transient objects. What is the transient object you can find [here](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/objectstate.html)
`Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).`
You are getting the Team object and you are trying to persist it to the DB but that object has Account object in it and that Account object is detached (means that instance of that object has saved into the DB but that object is not in the session). Hibernate is trying to save it because of you have specified:
```
@OneToMany(cascade = CascadeType.ALL, ....
```
So, there are few ways how you can fix it:
1) do not use CascadeType.ALL configuration. Account object can be used for number of Teams (at least domain structure allows it) and update operation might update Account for ALL Teams -- it means that this operation should not be initiated with Team update.
I would remove cascade parameter from there (default value is no cascade operations), of if you really need use MERGE/DELETE configuration. But if you really need to persist it then see option #2
2) use 'saveOrUpdate()' method instead of 'save()'. 'saveOrUpdate()' method accepts transient and detached objects.
But the problem with this approach is in design: do you really need to insert/update account when you are saving Team object? I would split it in two operations and prevent updating Account from the Team.
Hope this helps.
|
This error happened for me when I tried to save a child entity and then pass the newly saved entity as parameter to a new parent object.
For instance:
`ChildA a = childAService.save(childAObject);`
`Parent parent = new Parent()`;
`parent.setChildA(a) // <=== Culprit`
`parentService.save(parent);`
Instead, do:
`ChildA a = new ChildA();`
`parent.setChildA(a)`
`parentService.save(parent)`
Hibernate handles the persisting of `a` for you, you don't have to do it yourself.
|
27,672,337 |
I'm getting this error when submitting the form:
>
> org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account
>
>
>
Here are my entities:
**Account:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Account {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String login;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
@ManyToOne
@JoinColumn(name = "team_id")
private Team team;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private List<Team> ownedTeams;
...
```
**Team:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Team {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false)
private Account owner;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "team")
private List<Account> members;
...
```
Here's a part of the Controller:
```
@ModelAttribute("team")
public Team createTeamObject() {
return new Team();
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.GET)
public String getCreateTeam(@ModelAttribute("team") Team team, Principal principal) {
logger.info("Welcome to the create team page!");
Account owner = accountService.findOneByLogin(principal.getName());
team.setOwner(owner);
team.setMembers(new AutoPopulatingList<Account>(Account.class));
return "teams";
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.POST)
public String postCreateTeam(@ModelAttribute("team") Team team) {
logger.info("Team created!");
teamService.save(team);
return "redirect:/teams.html";
}
```
And the form:
```
<form:form commandName="team" id="teamForm">
<div class="form-group">
<label>Name</label>
<form:input path="name" cssClass="form-control" />
</div>
<div class="form-group" id="row-template">
<label>Members</label>
<form:select path="members[0].id" cssClass="form-control" data-live-search="true" >
<form:options items="${accounts}" itemValue="id" />
</form:select>
...
</div>
<form:hidden path="owner.id" />
</form:form>
```
What am I doing wrong?
|
2014/12/27
|
[
"https://Stackoverflow.com/questions/27672337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287404/"
] |
Please, change `@OneToMany(cascade = CascadeType.ALL,..)` to `@OneToMany(cascade = CascadeType.REMOVE,...)` or another except `CascadeType.PERSIST` and the problem has been solved
|
Since your id is auto generated value, don't send it from client side. I had a same issue. Make sure that you does't provide a value for auto generated attribute.
|
27,672,337 |
I'm getting this error when submitting the form:
>
> org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account; nested exception is javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.project.pmet.model.Account
>
>
>
Here are my entities:
**Account:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Account {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String login;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
@ManyToOne
@JoinColumn(name = "team_id")
private Team team;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private List<Team> ownedTeams;
...
```
**Team:**
```
@Entity
@DynamicInsert
@DynamicUpdate
public class Team {
@Id
@GeneratedValue
private Integer id;
@Column(nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false)
private Account owner;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "team")
private List<Account> members;
...
```
Here's a part of the Controller:
```
@ModelAttribute("team")
public Team createTeamObject() {
return new Team();
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.GET)
public String getCreateTeam(@ModelAttribute("team") Team team, Principal principal) {
logger.info("Welcome to the create team page!");
Account owner = accountService.findOneByLogin(principal.getName());
team.setOwner(owner);
team.setMembers(new AutoPopulatingList<Account>(Account.class));
return "teams";
}
@RequestMapping(value = "/teams/create-team", method = RequestMethod.POST)
public String postCreateTeam(@ModelAttribute("team") Team team) {
logger.info("Team created!");
teamService.save(team);
return "redirect:/teams.html";
}
```
And the form:
```
<form:form commandName="team" id="teamForm">
<div class="form-group">
<label>Name</label>
<form:input path="name" cssClass="form-control" />
</div>
<div class="form-group" id="row-template">
<label>Members</label>
<form:select path="members[0].id" cssClass="form-control" data-live-search="true" >
<form:options items="${accounts}" itemValue="id" />
</form:select>
...
</div>
<form:hidden path="owner.id" />
</form:form>
```
What am I doing wrong?
|
2014/12/27
|
[
"https://Stackoverflow.com/questions/27672337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287404/"
] |
The error occurs because the **id** is set. Hibernate distinguishes between transient and detached objects and persist works only with transient objects.
```
isteamService.save(team);
```
in this operation can not be loaded id because is @GeneratedValue
|
This error happened for me when I tried to save a child entity and then pass the newly saved entity as parameter to a new parent object.
For instance:
`ChildA a = childAService.save(childAObject);`
`Parent parent = new Parent()`;
`parent.setChildA(a) // <=== Culprit`
`parentService.save(parent);`
Instead, do:
`ChildA a = new ChildA();`
`parent.setChildA(a)`
`parentService.save(parent)`
Hibernate handles the persisting of `a` for you, you don't have to do it yourself.
|
52,350,011 |
Basically my title is the question:
Example:
```
>>> l=[1,2,3]
>>> *l
SyntaxError: can't use starred expression here
>>> print(*l)
1 2 3
>>>
```
Why is that???
|
2018/09/16
|
[
"https://Stackoverflow.com/questions/52350011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8708364/"
] |
because it's equivalent to positional arugments corspondent to the list, so when your not calling it somewhere that can take all the arguments, it makes no sense, since there are nowhere to put the arguments
f.x.
```
print(*[1,2,3])
# is the same as
print(1,2,3)
```
and
```
*[1,2,3]
#is the same as - and do not think of it as a tuple
1,2,3 # here how ever that makes it a tuple since tuples not defined by the parenthasies, but the point is the same
```
there is however a slight exception to this which is in tuple, list, set and dictionaries as of python 3.5 but that is an exception, and can also be used to assign left over values, how ever python can see your doing non of these.
**EDIT**
I undeleted my answer since i realised only the last part was wrong.
|
I think this is actually a question about understanding `*l` or generally `*ListLikeObject`.
The critical point is `*ListLikeObject` is not a valid expression individually. It doesn't mean "Oh please unpack the list".
An example can be `2 *[1, 2, 3]`(As we all know, it will output `[1, 2, 3, 1, 2, 3]`). If an individual `*[1, 2, 3]` is valid, what should it output? Should it raise a runtime exception as the evaluated expression is `2 1 2 3` and it is invalid(Somehow like divided by 0)?
So basically, `*[1, 2, 3]` is just a syntax sugar that helps you to pass arguments. You don't need to manually unpack the list but the interpreter will do it for you. But **essentially** it is still passing *three* arguments instead of one tuple of something else.
|
41,858 |
Below is from a truffle test cases in javascript, where I was trying to add the gas cost to an account balance to confirm the sum of transaction, where the sum should be equal to the previous balance.
But I couldn't get it to work!
The rcpt.cumulativeGasUsed, web3.eth.gasPrice, getBalance(accounts[1]) are all correct, but the arithmetic is not, some fromWei, toWei kung-fu needed?
What am I doing wrong here?
```
return instance.bailOut({ from: accounts[1] }).then(function (resp) {
var rcpt = web3.eth.getTransactionReceipt(resp.tx);
console.log("Sum: " + ((rcpt.cumulativeGasUsed * web3.eth.gasPrice) + web3.eth.getBalance(accounts[1]).toString(10)));
```
});
After a lot of experiments, it looks like the below method works fine, but couldn't explain the logic of transaction cost! Any idea is most welcome.
Anyways unit test is passing now!!!
```
return contractInstance.withdraw({ value: web3.toWei(1, "ether"), gas: 1000000 }).then(function () {
var contractAddressBalance = web3.fromWei(web3.eth.getBalance(contractAddress).toString(10));
console.log("contractAddress balance after withdraw: " + contractAddressBalance);
return contractInstance.bailOut({ from: accounts[1] }).then(function (resp) {
var rcpt = web3.eth.getTransactionReceipt(resp.tx);
console.log("cumulativeGasUsed: " + rcpt.cumulativeGasUsed);
console.log("gasPrice: " + web3.eth.gasPrice);
var transactionCost = (rcpt.cumulativeGasUsed / 10000000); // How come this works???
console.log("transactionCost: " + transactionCost);
console.log("Account[1] balance after withdraw: " + web3.eth.getBalance(accounts[1]));
contractWalletAfter = web3.fromWei(web3.eth.getBalance(accounts[1]).add(web3.fromWei(rcpt.cumulativeGasUsed)));
assert.equal(((contractWalletAfter.minus(contractWalletBefore)).add(transactionCost)).valueOf(), 6, "6 wasn't in the contract wallet");
});
});
```
|
2018/03/06
|
[
"https://ethereum.stackexchange.com/questions/41858",
"https://ethereum.stackexchange.com",
"https://ethereum.stackexchange.com/users/31355/"
] |
Note: This answer is only valid for Truffle v4.
---
I've tried this test with the MetaCoin example from truffle (ie run `truffle unbox metacoin` in an empty directory)
```
var MetaCoin = artifacts.require("./MetaCoin.sol");
contract('MetaCoin', function(accounts) {
it("Test gas", async () => {
const meta = await MetaCoin.deployed();
// Initial balance of the second account
const initial = await web3.eth.getBalance(accounts[1]);
console.log(`Initial: ${initial.toString()}`);
// Obtain gas used from the receipt
const receipt = await meta.sendCoin(accounts[2], 1, { from: accounts[1] });
const gasUsed = receipt.receipt.gasUsed;
console.log(`GasUsed: ${receipt.receipt.gasUsed}`);
// Obtain gasPrice from the transaction
const tx = await web3.eth.getTransaction(receipt.tx);
const gasPrice = tx.gasPrice;
console.log(`GasPrice: ${tx.gasPrice}`);
// Final balance
const final = await web3.eth.getBalance(accounts[1]);
console.log(`Final: ${final.toString()}`);
assert.equal(final.add(gasPrice.mul(gasUsed)).toString(), initial.toString(), "Must be equal");
});
});
```
The correspoding output is:
```
Contract: MetaCoin
Initial: 99971803600000000000
GasUsed: 23497
GasPrice: 100000000000
Final: 99969453900000000000
✓ Test gas (199ms)
1 passing (217ms)
```
One difference is that I'm reading the gasPrice from the transaction (`getTransaction(hash).gasPrice`) instead of the network `eth.gasPrice()`.
|
The following code is the same code as [Ismael](https://ethereum.stackexchange.com/users/2124/ismael)'s code, with the changes to work with Truffle v5, as `getBalance`'s return type, beside `gasUsed` and `gasPrice` values are not BN by default:
```
var MetaCoin = artifacts.require("./MetaCoin.sol");
const { toBN } = web3.utils;
contract('MetaCoin', function(accounts) {
it("Test gas", async () => {
const meta = await MetaCoin.deployed();
// Initial balance of the second account
const initial = toBN(await web3.eth.getBalance(accounts[1]));
console.log(`Initial: ${initial.toString()}`);
// Obtain gas used from the receipt
const receipt = await meta.sendCoin(accounts[2], 1, { from: accounts[1] });
const gasUsed = toBN(receipt.receipt.gasUsed);
console.log(`GasUsed: ${receipt.receipt.gasUsed}`);
// Obtain gasPrice from the transaction
const tx = await web3.eth.getTransaction(receipt.tx);
const gasPrice = toBN(tx.gasPrice);
console.log(`GasPrice: ${tx.gasPrice}`);
// Final balance
const final = toBN(await web3.eth.getBalance(accounts[1]));
console.log(`Final: ${final.toString()}`);
assert.equal(final.add(gasPrice.mul(gasUsed)).toString(), initial.toString(), "Must be equal");
});
});
```
|
53,841,696 |
I have data in a table(list) as shown below,
```
id no1 no2
1000 0 511
1000 820 0
```
I need data like shown below,
```
id no1 no2
1000 820 511
```
Can anyone solve this. Thanks in advance.
|
2018/12/18
|
[
"https://Stackoverflow.com/questions/53841696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8029341/"
] |
simple group by with summation will work for you
```
SELECT
ID,
SUM(NO1) NO1,
SUM(NO2) NO2
FROM Table1
Group by ID
```
|
You can use sum or max:
```
select id,max(no1),max(no2) from tab_name group by id;
```
or
```
select id,sum(no1),sum(no2) from tab_name group by id;
```
|
3,835,043 |
I have a C server (a data feed handler) that has the potential to send millions of tiny messages per second across a few thousand long-lived Erlang processes. In a single day, some of these processes will receive a few *thousand* messages, while others will receive tens of *millions*. My interests are threefold:
1. to minimize latency — shortening the length of time from when the C server sends a message to when the Erlang process receives it. A lot of work can be done on things that happen *before* the message is sent or *after* the message is received, but this question is about the link between C and Erlang.
2. to maximize throughput — the faster the better; if the C server can send out 10% more messages per second across all of the Erlang processes, that's a big win.
3. to maximize predictability — if latency or throughput can suddenly degrade by several orders of magnitude due to something like network congestion, that's a big fail.
How can I send messages from a C program to an Erlang process in a high-performance way? What tricks can I do to minimize latency, maximize throughput, or make the communication between Erland and C more predictable? There are many aspects to this. We can choose the protocol for communication between an Erlang program and other programs. We can use Distributed Erlang with a "C Node" for communication between Erlang and C. We can use ports or linked-in drivers.
|
2010/09/30
|
[
"https://Stackoverflow.com/questions/3835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203104/"
] |
Try the following DiffRange function.
```
public static DateTime DayStart(DateTime date)
{
return date.Date.AddHours(7);
}
public static DateTime DayEnd(DateTime date)
{
return date.Date.AddHours(19);
}
public static TimeSpan DiffSingleDay(DateTime start, DateTime end)
{
if ( start.Date != end.Date ) {
throw new ArgumentException();
}
if (start.DayOfWeek == DayOfWeek.Saturday || start.DayOfWeek == DayOfWeek.Sunday )
{
return TimeSpan.Zero;
}
start = start >= DayStart(start) ? start : DayStart(start);
end = end <= DayEnd(end) ? end : DayEnd(end);
return end - start;
}
public static TimeSpan DiffRange(DateTime start, DateTime end)
{
if (start.Date == end.Date)
{
return DiffSingleDay(start, end);
}
var firstDay = DiffSingleDay(start, DayEnd(start));
var lastDay = DiffSingleDay(DayStart(end), end);
var middle = TimeSpan.Zero;
var current = start.AddDays(1);
while (current.Date != end.Date)
{
middle = middle + DiffSingleDay(current.Date, DayEnd(current.Date));
current = current.AddDays(1);
}
return firstDay + lastDay + middle;
}
```
|
My implementation :) The idea is to quickly compute the total weeks, and walk the remaining week day by day...
```
public TimeSpan Compute(DateTime start, DateTime end)
{
// constant start / end times per day
TimeSpan sevenAM = TimeSpan.FromHours(7);
TimeSpan sevenPM = TimeSpan.FromHours(19);
if( start >= end )
{
throw new Exception("invalid date range");
}
// total # of weeks
int completeWeeks = ((int)(end - start).TotalDays) / 7;
// starting total
TimeSpan total = TimeSpan.FromHours(completeWeeks * 12 * 5);
// adjust the start date to be exactly "completeWeeks" past its original start
start = start.AddDays(completeWeeks * 7);
// walk days from the adjusted start to end (at most 7), accumulating time as we can...
for(
// start at midnight
DateTime dt = start.Date;
// continue while there is time left
dt < end;
// increment 1 day at a time
dt = dt.AddDays(1)
)
{
// ignore weekend
if( (dt.DayOfWeek == DayOfWeek.Saturday) ||
(dt.DayOfWeek == DayOfWeek.Sunday) )
{
continue;
}
// get the start/end time for each day...
// typically 7am / 7pm unless we are at the start / end date
TimeSpan dtStartTime = ((dt == start.Date) && (start.TimeOfDay > sevenAM)) ?
start.TimeOfDay : sevenAM;
TimeSpan dtEndTime = ((dt == end.Date) && (end.TimeOfDay < sevenPM)) ?
end.TimeOfDay : sevenPM;
if( dtStartTime < dtEndTime )
{
total = total.Add(dtEndTime - dtStartTime);
}
}
return total;
}
```
|
3,835,043 |
I have a C server (a data feed handler) that has the potential to send millions of tiny messages per second across a few thousand long-lived Erlang processes. In a single day, some of these processes will receive a few *thousand* messages, while others will receive tens of *millions*. My interests are threefold:
1. to minimize latency — shortening the length of time from when the C server sends a message to when the Erlang process receives it. A lot of work can be done on things that happen *before* the message is sent or *after* the message is received, but this question is about the link between C and Erlang.
2. to maximize throughput — the faster the better; if the C server can send out 10% more messages per second across all of the Erlang processes, that's a big win.
3. to maximize predictability — if latency or throughput can suddenly degrade by several orders of magnitude due to something like network congestion, that's a big fail.
How can I send messages from a C program to an Erlang process in a high-performance way? What tricks can I do to minimize latency, maximize throughput, or make the communication between Erland and C more predictable? There are many aspects to this. We can choose the protocol for communication between an Erlang program and other programs. We can use Distributed Erlang with a "C Node" for communication between Erlang and C. We can use ports or linked-in drivers.
|
2010/09/30
|
[
"https://Stackoverflow.com/questions/3835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203104/"
] |
You can, of course, use LINQ:
```
DateTime a = new DateTime(2010, 10, 30, 21, 58, 29);
DateTime b = a + new TimeSpan(12, 5, 54, 24, 623);
var minutes = from day in a.DaysInRangeUntil(b)
where !day.IsWeekendDay()
let start = Max(day.AddHours( 7), a)
let end = Min(day.AddHours(19), b)
select (end - start).TotalMinutes;
var result = minutes.Sum();
// result == 6292.89
```
(Note: You probably need to check for a lot of corner cases which I completely ignored.)
Helper methods:
```
static IEnumerable<DateTime> DaysInRangeUntil(this DateTime start, DateTime end)
{
return Enumerable.Range(0, 1 + (int)(end.Date - start.Date).TotalDays)
.Select(dt => start.Date.AddDays(dt));
}
static bool IsWeekendDay(this DateTime dt)
{
return dt.DayOfWeek == DayOfWeek.Saturday
|| dt.DayOfWeek == DayOfWeek.Sunday;
}
static DateTime Max(DateTime a, DateTime b)
{
return new DateTime(Math.Max(a.Ticks, b.Ticks));
}
static DateTime Min(DateTime a, DateTime b)
{
return new DateTime(Math.Min(a.Ticks, b.Ticks));
}
```
|
Use TimeSpan.TotalMinutes, subtract non-business days, subtract superfluous hours.
|
3,835,043 |
I have a C server (a data feed handler) that has the potential to send millions of tiny messages per second across a few thousand long-lived Erlang processes. In a single day, some of these processes will receive a few *thousand* messages, while others will receive tens of *millions*. My interests are threefold:
1. to minimize latency — shortening the length of time from when the C server sends a message to when the Erlang process receives it. A lot of work can be done on things that happen *before* the message is sent or *after* the message is received, but this question is about the link between C and Erlang.
2. to maximize throughput — the faster the better; if the C server can send out 10% more messages per second across all of the Erlang processes, that's a big win.
3. to maximize predictability — if latency or throughput can suddenly degrade by several orders of magnitude due to something like network congestion, that's a big fail.
How can I send messages from a C program to an Erlang process in a high-performance way? What tricks can I do to minimize latency, maximize throughput, or make the communication between Erland and C more predictable? There are many aspects to this. We can choose the protocol for communication between an Erlang program and other programs. We can use Distributed Erlang with a "C Node" for communication between Erlang and C. We can use ports or linked-in drivers.
|
2010/09/30
|
[
"https://Stackoverflow.com/questions/3835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203104/"
] |
Take your start time, get the amount of minutes to the end of that day (Ie the 7pm).
Then from the 7am the next day, count the amount of days to the final day (excluding any time into the end day).
Calculate how many (If any) weekends have passed. (For every weekends reduce the count of days by 2).
Do some simple math from there to get the total minutes for the count of days.
Add the extra time on the final day and the start days extra time.
|
It was a pretty hard question. For a basic, in a straightforward approach, I have written the below code:
```
DateTime start = new DateTime(2010, 01, 01, 21, 00, 00);
DateTime end = new DateTime(2010, 10, 01, 14, 00, 00);
// Shift start date's hour to 7 and same for end date
// These will be added after doing calculation:
double startAdjustmentMinutes = (start - start.Date.AddHours(7)).TotalMinutes;
double endAdjustmentMinutes = (end - end.Date.AddHours(7)).TotalMinutes;
// We can do some basic
// mathematical calculation to find weekdays count:
// divide by 7 multiply by 5 gives complete weeks weekdays
// and adding remainder gives the all weekdays:
int weekdaysCount = (((int)((end.Date - start.Date).Days / 7) * 5)
+ ((end.Date - start.Date).Days % 7));
// so we can multiply it by minutes between 7am to 7 pm
int minutes = weekdaysCount * (12 * 60);
// after adding adjustment we have the result:
int result = minutes + startAdjustmentMinutes + endAdjustmentMinutes;
```
I know this not seem programmatically beautiful but I don't know if it is good to iterate through days and hours between start and end.
|
3,835,043 |
I have a C server (a data feed handler) that has the potential to send millions of tiny messages per second across a few thousand long-lived Erlang processes. In a single day, some of these processes will receive a few *thousand* messages, while others will receive tens of *millions*. My interests are threefold:
1. to minimize latency — shortening the length of time from when the C server sends a message to when the Erlang process receives it. A lot of work can be done on things that happen *before* the message is sent or *after* the message is received, but this question is about the link between C and Erlang.
2. to maximize throughput — the faster the better; if the C server can send out 10% more messages per second across all of the Erlang processes, that's a big win.
3. to maximize predictability — if latency or throughput can suddenly degrade by several orders of magnitude due to something like network congestion, that's a big fail.
How can I send messages from a C program to an Erlang process in a high-performance way? What tricks can I do to minimize latency, maximize throughput, or make the communication between Erland and C more predictable? There are many aspects to this. We can choose the protocol for communication between an Erlang program and other programs. We can use Distributed Erlang with a "C Node" for communication between Erlang and C. We can use ports or linked-in drivers.
|
2010/09/30
|
[
"https://Stackoverflow.com/questions/3835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203104/"
] |
Take your start time, get the amount of minutes to the end of that day (Ie the 7pm).
Then from the 7am the next day, count the amount of days to the final day (excluding any time into the end day).
Calculate how many (If any) weekends have passed. (For every weekends reduce the count of days by 2).
Do some simple math from there to get the total minutes for the count of days.
Add the extra time on the final day and the start days extra time.
|
My implementation :) The idea is to quickly compute the total weeks, and walk the remaining week day by day...
```
public TimeSpan Compute(DateTime start, DateTime end)
{
// constant start / end times per day
TimeSpan sevenAM = TimeSpan.FromHours(7);
TimeSpan sevenPM = TimeSpan.FromHours(19);
if( start >= end )
{
throw new Exception("invalid date range");
}
// total # of weeks
int completeWeeks = ((int)(end - start).TotalDays) / 7;
// starting total
TimeSpan total = TimeSpan.FromHours(completeWeeks * 12 * 5);
// adjust the start date to be exactly "completeWeeks" past its original start
start = start.AddDays(completeWeeks * 7);
// walk days from the adjusted start to end (at most 7), accumulating time as we can...
for(
// start at midnight
DateTime dt = start.Date;
// continue while there is time left
dt < end;
// increment 1 day at a time
dt = dt.AddDays(1)
)
{
// ignore weekend
if( (dt.DayOfWeek == DayOfWeek.Saturday) ||
(dt.DayOfWeek == DayOfWeek.Sunday) )
{
continue;
}
// get the start/end time for each day...
// typically 7am / 7pm unless we are at the start / end date
TimeSpan dtStartTime = ((dt == start.Date) && (start.TimeOfDay > sevenAM)) ?
start.TimeOfDay : sevenAM;
TimeSpan dtEndTime = ((dt == end.Date) && (end.TimeOfDay < sevenPM)) ?
end.TimeOfDay : sevenPM;
if( dtStartTime < dtEndTime )
{
total = total.Add(dtEndTime - dtStartTime);
}
}
return total;
}
```
|
3,835,043 |
I have a C server (a data feed handler) that has the potential to send millions of tiny messages per second across a few thousand long-lived Erlang processes. In a single day, some of these processes will receive a few *thousand* messages, while others will receive tens of *millions*. My interests are threefold:
1. to minimize latency — shortening the length of time from when the C server sends a message to when the Erlang process receives it. A lot of work can be done on things that happen *before* the message is sent or *after* the message is received, but this question is about the link between C and Erlang.
2. to maximize throughput — the faster the better; if the C server can send out 10% more messages per second across all of the Erlang processes, that's a big win.
3. to maximize predictability — if latency or throughput can suddenly degrade by several orders of magnitude due to something like network congestion, that's a big fail.
How can I send messages from a C program to an Erlang process in a high-performance way? What tricks can I do to minimize latency, maximize throughput, or make the communication between Erland and C more predictable? There are many aspects to this. We can choose the protocol for communication between an Erlang program and other programs. We can use Distributed Erlang with a "C Node" for communication between Erlang and C. We can use ports or linked-in drivers.
|
2010/09/30
|
[
"https://Stackoverflow.com/questions/3835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203104/"
] |
Take your start time, get the amount of minutes to the end of that day (Ie the 7pm).
Then from the 7am the next day, count the amount of days to the final day (excluding any time into the end day).
Calculate how many (If any) weekends have passed. (For every weekends reduce the count of days by 2).
Do some simple math from there to get the total minutes for the count of days.
Add the extra time on the final day and the start days extra time.
|
I'm sure there's something I missed.
```
TimeSpan CalcBusinessTime(DateTime a, DateTime b)
{
if (a > b)
{
DateTime tmp = a;
a = b;
b = tmp;
}
if (a.TimeOfDay < new TimeSpan(7, 0, 0))
a = new DateTime(a.Year, a.Month, a.Day, 7, 0, 0);
if (b.TimeOfDay > new TimeSpan(19, 0, 0))
b = new DateTime(b.Year, b.Month, b.Day, 19, 0, 0);
TimeSpan sum = new TimeSpan();
TimeSpan fullDay = new TimeSpan(12, 0, 0);
while (a < b)
{
if (a.DayOfWeek != DayOfWeek.Saturday && a.DayOfWeek != DayOfWeek.Sunday)
{
sum += (b - a < fullDay) ? b - a : fullDay;
}
a = a.AddDays(1);
}
return sum;
}
```
|
3,835,043 |
I have a C server (a data feed handler) that has the potential to send millions of tiny messages per second across a few thousand long-lived Erlang processes. In a single day, some of these processes will receive a few *thousand* messages, while others will receive tens of *millions*. My interests are threefold:
1. to minimize latency — shortening the length of time from when the C server sends a message to when the Erlang process receives it. A lot of work can be done on things that happen *before* the message is sent or *after* the message is received, but this question is about the link between C and Erlang.
2. to maximize throughput — the faster the better; if the C server can send out 10% more messages per second across all of the Erlang processes, that's a big win.
3. to maximize predictability — if latency or throughput can suddenly degrade by several orders of magnitude due to something like network congestion, that's a big fail.
How can I send messages from a C program to an Erlang process in a high-performance way? What tricks can I do to minimize latency, maximize throughput, or make the communication between Erland and C more predictable? There are many aspects to this. We can choose the protocol for communication between an Erlang program and other programs. We can use Distributed Erlang with a "C Node" for communication between Erlang and C. We can use ports or linked-in drivers.
|
2010/09/30
|
[
"https://Stackoverflow.com/questions/3835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203104/"
] |
Try the following DiffRange function.
```
public static DateTime DayStart(DateTime date)
{
return date.Date.AddHours(7);
}
public static DateTime DayEnd(DateTime date)
{
return date.Date.AddHours(19);
}
public static TimeSpan DiffSingleDay(DateTime start, DateTime end)
{
if ( start.Date != end.Date ) {
throw new ArgumentException();
}
if (start.DayOfWeek == DayOfWeek.Saturday || start.DayOfWeek == DayOfWeek.Sunday )
{
return TimeSpan.Zero;
}
start = start >= DayStart(start) ? start : DayStart(start);
end = end <= DayEnd(end) ? end : DayEnd(end);
return end - start;
}
public static TimeSpan DiffRange(DateTime start, DateTime end)
{
if (start.Date == end.Date)
{
return DiffSingleDay(start, end);
}
var firstDay = DiffSingleDay(start, DayEnd(start));
var lastDay = DiffSingleDay(DayStart(end), end);
var middle = TimeSpan.Zero;
var current = start.AddDays(1);
while (current.Date != end.Date)
{
middle = middle + DiffSingleDay(current.Date, DayEnd(current.Date));
current = current.AddDays(1);
}
return firstDay + lastDay + middle;
}
```
|
Use TimeSpan.TotalMinutes, subtract non-business days, subtract superfluous hours.
|
3,835,043 |
I have a C server (a data feed handler) that has the potential to send millions of tiny messages per second across a few thousand long-lived Erlang processes. In a single day, some of these processes will receive a few *thousand* messages, while others will receive tens of *millions*. My interests are threefold:
1. to minimize latency — shortening the length of time from when the C server sends a message to when the Erlang process receives it. A lot of work can be done on things that happen *before* the message is sent or *after* the message is received, but this question is about the link between C and Erlang.
2. to maximize throughput — the faster the better; if the C server can send out 10% more messages per second across all of the Erlang processes, that's a big win.
3. to maximize predictability — if latency or throughput can suddenly degrade by several orders of magnitude due to something like network congestion, that's a big fail.
How can I send messages from a C program to an Erlang process in a high-performance way? What tricks can I do to minimize latency, maximize throughput, or make the communication between Erland and C more predictable? There are many aspects to this. We can choose the protocol for communication between an Erlang program and other programs. We can use Distributed Erlang with a "C Node" for communication between Erlang and C. We can use ports or linked-in drivers.
|
2010/09/30
|
[
"https://Stackoverflow.com/questions/3835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203104/"
] |
You can, of course, use LINQ:
```
DateTime a = new DateTime(2010, 10, 30, 21, 58, 29);
DateTime b = a + new TimeSpan(12, 5, 54, 24, 623);
var minutes = from day in a.DaysInRangeUntil(b)
where !day.IsWeekendDay()
let start = Max(day.AddHours( 7), a)
let end = Min(day.AddHours(19), b)
select (end - start).TotalMinutes;
var result = minutes.Sum();
// result == 6292.89
```
(Note: You probably need to check for a lot of corner cases which I completely ignored.)
Helper methods:
```
static IEnumerable<DateTime> DaysInRangeUntil(this DateTime start, DateTime end)
{
return Enumerable.Range(0, 1 + (int)(end.Date - start.Date).TotalDays)
.Select(dt => start.Date.AddDays(dt));
}
static bool IsWeekendDay(this DateTime dt)
{
return dt.DayOfWeek == DayOfWeek.Saturday
|| dt.DayOfWeek == DayOfWeek.Sunday;
}
static DateTime Max(DateTime a, DateTime b)
{
return new DateTime(Math.Max(a.Ticks, b.Ticks));
}
static DateTime Min(DateTime a, DateTime b)
{
return new DateTime(Math.Min(a.Ticks, b.Ticks));
}
```
|
My implementation :) The idea is to quickly compute the total weeks, and walk the remaining week day by day...
```
public TimeSpan Compute(DateTime start, DateTime end)
{
// constant start / end times per day
TimeSpan sevenAM = TimeSpan.FromHours(7);
TimeSpan sevenPM = TimeSpan.FromHours(19);
if( start >= end )
{
throw new Exception("invalid date range");
}
// total # of weeks
int completeWeeks = ((int)(end - start).TotalDays) / 7;
// starting total
TimeSpan total = TimeSpan.FromHours(completeWeeks * 12 * 5);
// adjust the start date to be exactly "completeWeeks" past its original start
start = start.AddDays(completeWeeks * 7);
// walk days from the adjusted start to end (at most 7), accumulating time as we can...
for(
// start at midnight
DateTime dt = start.Date;
// continue while there is time left
dt < end;
// increment 1 day at a time
dt = dt.AddDays(1)
)
{
// ignore weekend
if( (dt.DayOfWeek == DayOfWeek.Saturday) ||
(dt.DayOfWeek == DayOfWeek.Sunday) )
{
continue;
}
// get the start/end time for each day...
// typically 7am / 7pm unless we are at the start / end date
TimeSpan dtStartTime = ((dt == start.Date) && (start.TimeOfDay > sevenAM)) ?
start.TimeOfDay : sevenAM;
TimeSpan dtEndTime = ((dt == end.Date) && (end.TimeOfDay < sevenPM)) ?
end.TimeOfDay : sevenPM;
if( dtStartTime < dtEndTime )
{
total = total.Add(dtEndTime - dtStartTime);
}
}
return total;
}
```
|
3,835,043 |
I have a C server (a data feed handler) that has the potential to send millions of tiny messages per second across a few thousand long-lived Erlang processes. In a single day, some of these processes will receive a few *thousand* messages, while others will receive tens of *millions*. My interests are threefold:
1. to minimize latency — shortening the length of time from when the C server sends a message to when the Erlang process receives it. A lot of work can be done on things that happen *before* the message is sent or *after* the message is received, but this question is about the link between C and Erlang.
2. to maximize throughput — the faster the better; if the C server can send out 10% more messages per second across all of the Erlang processes, that's a big win.
3. to maximize predictability — if latency or throughput can suddenly degrade by several orders of magnitude due to something like network congestion, that's a big fail.
How can I send messages from a C program to an Erlang process in a high-performance way? What tricks can I do to minimize latency, maximize throughput, or make the communication between Erland and C more predictable? There are many aspects to this. We can choose the protocol for communication between an Erlang program and other programs. We can use Distributed Erlang with a "C Node" for communication between Erlang and C. We can use ports or linked-in drivers.
|
2010/09/30
|
[
"https://Stackoverflow.com/questions/3835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203104/"
] |
Take your start time, get the amount of minutes to the end of that day (Ie the 7pm).
Then from the 7am the next day, count the amount of days to the final day (excluding any time into the end day).
Calculate how many (If any) weekends have passed. (For every weekends reduce the count of days by 2).
Do some simple math from there to get the total minutes for the count of days.
Add the extra time on the final day and the start days extra time.
|
Try the following DiffRange function.
```
public static DateTime DayStart(DateTime date)
{
return date.Date.AddHours(7);
}
public static DateTime DayEnd(DateTime date)
{
return date.Date.AddHours(19);
}
public static TimeSpan DiffSingleDay(DateTime start, DateTime end)
{
if ( start.Date != end.Date ) {
throw new ArgumentException();
}
if (start.DayOfWeek == DayOfWeek.Saturday || start.DayOfWeek == DayOfWeek.Sunday )
{
return TimeSpan.Zero;
}
start = start >= DayStart(start) ? start : DayStart(start);
end = end <= DayEnd(end) ? end : DayEnd(end);
return end - start;
}
public static TimeSpan DiffRange(DateTime start, DateTime end)
{
if (start.Date == end.Date)
{
return DiffSingleDay(start, end);
}
var firstDay = DiffSingleDay(start, DayEnd(start));
var lastDay = DiffSingleDay(DayStart(end), end);
var middle = TimeSpan.Zero;
var current = start.AddDays(1);
while (current.Date != end.Date)
{
middle = middle + DiffSingleDay(current.Date, DayEnd(current.Date));
current = current.AddDays(1);
}
return firstDay + lastDay + middle;
}
```
|
3,835,043 |
I have a C server (a data feed handler) that has the potential to send millions of tiny messages per second across a few thousand long-lived Erlang processes. In a single day, some of these processes will receive a few *thousand* messages, while others will receive tens of *millions*. My interests are threefold:
1. to minimize latency — shortening the length of time from when the C server sends a message to when the Erlang process receives it. A lot of work can be done on things that happen *before* the message is sent or *after* the message is received, but this question is about the link between C and Erlang.
2. to maximize throughput — the faster the better; if the C server can send out 10% more messages per second across all of the Erlang processes, that's a big win.
3. to maximize predictability — if latency or throughput can suddenly degrade by several orders of magnitude due to something like network congestion, that's a big fail.
How can I send messages from a C program to an Erlang process in a high-performance way? What tricks can I do to minimize latency, maximize throughput, or make the communication between Erland and C more predictable? There are many aspects to this. We can choose the protocol for communication between an Erlang program and other programs. We can use Distributed Erlang with a "C Node" for communication between Erlang and C. We can use ports or linked-in drivers.
|
2010/09/30
|
[
"https://Stackoverflow.com/questions/3835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203104/"
] |
You can, of course, use LINQ:
```
DateTime a = new DateTime(2010, 10, 30, 21, 58, 29);
DateTime b = a + new TimeSpan(12, 5, 54, 24, 623);
var minutes = from day in a.DaysInRangeUntil(b)
where !day.IsWeekendDay()
let start = Max(day.AddHours( 7), a)
let end = Min(day.AddHours(19), b)
select (end - start).TotalMinutes;
var result = minutes.Sum();
// result == 6292.89
```
(Note: You probably need to check for a lot of corner cases which I completely ignored.)
Helper methods:
```
static IEnumerable<DateTime> DaysInRangeUntil(this DateTime start, DateTime end)
{
return Enumerable.Range(0, 1 + (int)(end.Date - start.Date).TotalDays)
.Select(dt => start.Date.AddDays(dt));
}
static bool IsWeekendDay(this DateTime dt)
{
return dt.DayOfWeek == DayOfWeek.Saturday
|| dt.DayOfWeek == DayOfWeek.Sunday;
}
static DateTime Max(DateTime a, DateTime b)
{
return new DateTime(Math.Max(a.Ticks, b.Ticks));
}
static DateTime Min(DateTime a, DateTime b)
{
return new DateTime(Math.Min(a.Ticks, b.Ticks));
}
```
|
Try the following DiffRange function.
```
public static DateTime DayStart(DateTime date)
{
return date.Date.AddHours(7);
}
public static DateTime DayEnd(DateTime date)
{
return date.Date.AddHours(19);
}
public static TimeSpan DiffSingleDay(DateTime start, DateTime end)
{
if ( start.Date != end.Date ) {
throw new ArgumentException();
}
if (start.DayOfWeek == DayOfWeek.Saturday || start.DayOfWeek == DayOfWeek.Sunday )
{
return TimeSpan.Zero;
}
start = start >= DayStart(start) ? start : DayStart(start);
end = end <= DayEnd(end) ? end : DayEnd(end);
return end - start;
}
public static TimeSpan DiffRange(DateTime start, DateTime end)
{
if (start.Date == end.Date)
{
return DiffSingleDay(start, end);
}
var firstDay = DiffSingleDay(start, DayEnd(start));
var lastDay = DiffSingleDay(DayStart(end), end);
var middle = TimeSpan.Zero;
var current = start.AddDays(1);
while (current.Date != end.Date)
{
middle = middle + DiffSingleDay(current.Date, DayEnd(current.Date));
current = current.AddDays(1);
}
return firstDay + lastDay + middle;
}
```
|
3,835,043 |
I have a C server (a data feed handler) that has the potential to send millions of tiny messages per second across a few thousand long-lived Erlang processes. In a single day, some of these processes will receive a few *thousand* messages, while others will receive tens of *millions*. My interests are threefold:
1. to minimize latency — shortening the length of time from when the C server sends a message to when the Erlang process receives it. A lot of work can be done on things that happen *before* the message is sent or *after* the message is received, but this question is about the link between C and Erlang.
2. to maximize throughput — the faster the better; if the C server can send out 10% more messages per second across all of the Erlang processes, that's a big win.
3. to maximize predictability — if latency or throughput can suddenly degrade by several orders of magnitude due to something like network congestion, that's a big fail.
How can I send messages from a C program to an Erlang process in a high-performance way? What tricks can I do to minimize latency, maximize throughput, or make the communication between Erland and C more predictable? There are many aspects to this. We can choose the protocol for communication between an Erlang program and other programs. We can use Distributed Erlang with a "C Node" for communication between Erlang and C. We can use ports or linked-in drivers.
|
2010/09/30
|
[
"https://Stackoverflow.com/questions/3835043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203104/"
] |
You can, of course, use LINQ:
```
DateTime a = new DateTime(2010, 10, 30, 21, 58, 29);
DateTime b = a + new TimeSpan(12, 5, 54, 24, 623);
var minutes = from day in a.DaysInRangeUntil(b)
where !day.IsWeekendDay()
let start = Max(day.AddHours( 7), a)
let end = Min(day.AddHours(19), b)
select (end - start).TotalMinutes;
var result = minutes.Sum();
// result == 6292.89
```
(Note: You probably need to check for a lot of corner cases which I completely ignored.)
Helper methods:
```
static IEnumerable<DateTime> DaysInRangeUntil(this DateTime start, DateTime end)
{
return Enumerable.Range(0, 1 + (int)(end.Date - start.Date).TotalDays)
.Select(dt => start.Date.AddDays(dt));
}
static bool IsWeekendDay(this DateTime dt)
{
return dt.DayOfWeek == DayOfWeek.Saturday
|| dt.DayOfWeek == DayOfWeek.Sunday;
}
static DateTime Max(DateTime a, DateTime b)
{
return new DateTime(Math.Max(a.Ticks, b.Ticks));
}
static DateTime Min(DateTime a, DateTime b)
{
return new DateTime(Math.Min(a.Ticks, b.Ticks));
}
```
|
I won't write any code, but having a DateTime you can tell the Day of the week, thus you know how many weekends are in your range, so you can tell how many minutes are in a weekend.
So it wouldn't be so hard... of course there must be an optimal one line solution... but i think you can get around with this one.
I forgot to mention that you also know the minutes btween 7:00 pm and 7:00 am so all you have to do is substract the right amount of minutes to the time difference you get.
|
23,215,697 |
I have a custom Wordpress table with the following contents:
```
account_info
id | account_id | wp_title | wp_url
1 | 12345 | website | website.com
```
What is the best (or fastest) way to get the results?
**Option 1:**
```
global $wpdb;
$sql = "SELECT id, wp_title. wp_name FROM account_info";
$results = $wpdb->get_results($sql);
if(!empty($results)) {
foreach($results as $r) {
$id = $r->id;
$wp_title = $r->wp_title;
$wp_name = $r->wp_name;
}
}
```
**Option 2:**
```
$id = $wpdb->get_var("SELECT id FROM account_info");
$wp_title = $wpdb->get_var("SELECT wp_title FROM account_info");
$wp_name = $wpdb->get_var("SELECT wp_name FROM account_info");
```
|
2014/04/22
|
[
"https://Stackoverflow.com/questions/23215697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/985664/"
] |
When you are talking about "best" and "fastest" - these aren't the only things you need to take into consideration. *Readibility* is also key for future developers looking at your code.
Option one clearly shows that, if the result set isn't empty, you loop around them and set some variables. Option two is *framework specific*, and this isn't always the best approach.
So *before* micro-optimising, make sure *readability* is at it's utmost - never sacrifice one for the other.
Speed-wise, just make sure you're indexing your database properly. You're using the fastest loops available to PHP. Also, option two is making multiple database queries. Always try and combine multiple queries into one - you don't need to make a load of extra calls to the db that you don't actually need.
You want to avoid using the `global` keyword. It's bad practice and makes your code untestable. Get access to the `$wpdb` variable another way, either by passing it into a function or including a file elsewhere. See [why global variables are bad](https://stackoverflow.com/questions/8715897/why-is-it-considered-bad-practice-to-use-global-reference-inside-functions) and search a little on google.
|
This would depend on your objective, query language and the metta data design around indexing etc.
In you example above collecting your results as an object above and iterating through would be the best option, if more than one option is available.
If only ever expecting a singular result to be safe ad LIMIT 1 in your query and access your object properties accordingly
|
23,215,697 |
I have a custom Wordpress table with the following contents:
```
account_info
id | account_id | wp_title | wp_url
1 | 12345 | website | website.com
```
What is the best (or fastest) way to get the results?
**Option 1:**
```
global $wpdb;
$sql = "SELECT id, wp_title. wp_name FROM account_info";
$results = $wpdb->get_results($sql);
if(!empty($results)) {
foreach($results as $r) {
$id = $r->id;
$wp_title = $r->wp_title;
$wp_name = $r->wp_name;
}
}
```
**Option 2:**
```
$id = $wpdb->get_var("SELECT id FROM account_info");
$wp_title = $wpdb->get_var("SELECT wp_title FROM account_info");
$wp_name = $wpdb->get_var("SELECT wp_name FROM account_info");
```
|
2014/04/22
|
[
"https://Stackoverflow.com/questions/23215697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/985664/"
] |
When you are talking about "best" and "fastest" - these aren't the only things you need to take into consideration. *Readibility* is also key for future developers looking at your code.
Option one clearly shows that, if the result set isn't empty, you loop around them and set some variables. Option two is *framework specific*, and this isn't always the best approach.
So *before* micro-optimising, make sure *readability* is at it's utmost - never sacrifice one for the other.
Speed-wise, just make sure you're indexing your database properly. You're using the fastest loops available to PHP. Also, option two is making multiple database queries. Always try and combine multiple queries into one - you don't need to make a load of extra calls to the db that you don't actually need.
You want to avoid using the `global` keyword. It's bad practice and makes your code untestable. Get access to the `$wpdb` variable another way, either by passing it into a function or including a file elsewhere. See [why global variables are bad](https://stackoverflow.com/questions/8715897/why-is-it-considered-bad-practice-to-use-global-reference-inside-functions) and search a little on google.
|
IMHO, I recommend the option 1, but even better I recommend using prepared statements, suggested by many authors. It avoids abuse of the protocol and mimimize data transfers.
```
$stmt = $dbh->prepare("SELECT id, wp_title. wp_name FROM account_info");
if ($stmt->execute(array())) {
while ($row = $stmt->fetch()) {
$id = $row['id'];
$wp_title = $row['wp_title'];
$wp_name = $row['wp_name'];
}
}
```
|
59,192,023 |
I have some blog with some posts. Every page has a block "Read now" which contains post titles with count of readers at that moment (guests and auth users).The question is how to get these counters.
I am usinng laravel Echo with beyondcode/laravel-websockets.
Tryed to using presence channel, but it requires authorization.
|
2019/12/05
|
[
"https://Stackoverflow.com/questions/59192023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4489464/"
] |
You can try this method [by SaeedPrez](https://laracasts.com/discuss/channels/laravel/find-out-all-logged-in-users?page=0#reply=318054).
Alternatively, you could try going through Laravels `Request` like this:
```
Request::session()->all()
```
Try dumping and dying (`dd()` function) and see how you could parse the given response. As an idea maybe use a CRON and save the variables in cache.
|
I think you can try init Echo.listen() on public channel once user hit the post page. From that, you can build logic to see how many people are in that post.id page by temporarily store the count data somewhere in Redis or just in database the belong to that specific post. And remove the count when user leave the page by calling the Echo.leave().
There's no true solution yet since presence channel require authenticated user.
|
26,239,083 |
I'm using `InnoDb` schema on `mysql 5.5`.
`mysql 5.5` guide states:
>
> InnoDB uses the in-memory auto-increment counter as long as the server
> runs. When the server is stopped and restarted, InnoDB reinitializes
> the counter for each table for the first INSERT to the table, as
> described earlier.
>
>
>
This is a big problem for me. I'm using `envers` to keep entities audits. I get as many errors as many "last rows" I delete.
Suppose I'm starting insert data into an empty table. Suppose to insert 10 rows. Then suppose to delete the last 8. In my table I will have as result 2 entities, with id 1 and 2 respectively. In the audit table I will have all 10 entities, with id from 1 to 10: entities with id from 3 to 10 will have 2 action: create action and delete action.
auto-increment counter is now setted to 11 in main table. Restarting mysql service auto-increment counter goes to 3. So if I insert a new entity, it will be saved with id 3. But in audit table there is already an entity with id = 3. That entity is already marked as created and deleted. It result in an assertion failure during update /delete action because envers cannot handle this inconsistent state.
```
ERROR org.hibernate.AssertionFailure - HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): java.lang.RuntimeException: Cannot update previous revision for entity Customer_H and id **.
```
Is there a way to change this behaviour and keep auto-increment values while restarting server?
As I remember also in mysqldump generated file there is no infos about autoincrement counter. So also restoring a dump could be a problem!
|
2014/10/07
|
[
"https://Stackoverflow.com/questions/26239083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1157935/"
] |
you'll need to create a service that returns your user information
```
angular.module('app').factory('Authentication', function ($resource) {
var resource = $resource('/user', {}, {
query: {
method: 'GET',
cache: true
}
});
return resource.get().$promise;
});
```
\* note that you'll need to create and endpoint that will send you the user data as json using web api
once you got it done you'll be able to use it in any controller (let's assume you have a homecontroller, it could be a headercontroller or any other)
```
angular.module('app').controller('HomeController', ['$scope', 'Authentication', function ($scope, Authentication) {
$scope.authentication = Authentication;
}]);
```
then use it in your view like:
```
<span >Logged In As: {{authentication.user.username}} </span>
```
**EDIT:**
your api controller as you suggested could be like
```
public HttpResponseMessage Get()
{
var userId = getCurrentUserId(); //something like that
using (var context = new ApplicationDbContext())
{
ApplicationUser user = new ApplicationUser();
user = context.ApplicationUsers.SingleOrDefault(x=>x.id==userId);
return user;
}
}
```
try to read <http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization>
for routing try to read this article (I guess you are using web api 2)
<http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2>
|
If you want to cheat a little, you can do this in `<head>` in your \_Layout:
```
<script type="text/javascript">
(function(myApp) {
myApp.username = "@User.Identity.GetUserName()";
//optional
myApp.otherStuff = "@moreMvcStuff";
})(window.myApp = window.myApp || {});
</script>
```
Then start your angular app like this:
```
(function (myApp) {
"use strict";
//var app = set up your angular app
app.run(["$rootScope",
function ($rootScope) {
$rootScope.appSettings = {
username: myApp.username
};
}
]);
})(window.myApp = window.myApp || {});
```
What you are doing is creating a single value on the window called myApp (or name it whatever you like) and passing it into your IIFE. This gives you access to it inside your angular script, bot only in that on block. So if you want it to stick around, you need to put it in a service or your rootScope.
In the app.run block, you can stick it in your rootScope or wherever you want it.
Now in your views you can display it with `{{appSettings.username}}`.
I call this "cheating" because it's specifically for MVC or webforms and it's not the "angular way". If you ever migrated to a fully agnostic html/js client (no asp.net mvc) and web APIs, you'd need to do what is in the currently-accepted answer.
|
5,095,471 |
I have a small PHP mysql query looking at a table in my database. It's pulling all rows and then echoing out the record.
Problem is I have a few empty rows in the table so what I get is a weird looking record.
This is what I got:
```
<?php
$con = mysql_connect("localhost","username","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("username", $con);
$result = mysql_query("SELECT * FROM wallnames2011 WHERE firstname IS NOT NULL");
while($row = mysql_fetch_array($result)){
echo $row['firstname'] . " - " . $row['city'] . ", " .$row['state'] . " | ";
}
?>
```
I want to keep the empty rows out.
|
2011/02/23
|
[
"https://Stackoverflow.com/questions/5095471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237153/"
] |
You can put an `if(!empty($row['firstname']))` before you echo the row.
|
To print out only `rowname` and result from rows where result `IS NOT NULL`, try this:
```
if ($result = $mysqli->query($query)) {
/* fetch associative array */
$i=1;
while($a = $result->fetch_assoc()) {
$i++;
foreach ($a as $key => $value) {
if($value != NULL) {
echo $key." = ".$value."<br/>";
}
}
echo "-- <br />";
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
```
|
5,095,471 |
I have a small PHP mysql query looking at a table in my database. It's pulling all rows and then echoing out the record.
Problem is I have a few empty rows in the table so what I get is a weird looking record.
This is what I got:
```
<?php
$con = mysql_connect("localhost","username","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("username", $con);
$result = mysql_query("SELECT * FROM wallnames2011 WHERE firstname IS NOT NULL");
while($row = mysql_fetch_array($result)){
echo $row['firstname'] . " - " . $row['city'] . ", " .$row['state'] . " | ";
}
?>
```
I want to keep the empty rows out.
|
2011/02/23
|
[
"https://Stackoverflow.com/questions/5095471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237153/"
] |
Try SELECT column\_name
FROM table\_name
WHERE TRIM(column\_name) IS NOT NULL
|
You can put an `if(!empty($row['firstname']))` before you echo the row.
|
5,095,471 |
I have a small PHP mysql query looking at a table in my database. It's pulling all rows and then echoing out the record.
Problem is I have a few empty rows in the table so what I get is a weird looking record.
This is what I got:
```
<?php
$con = mysql_connect("localhost","username","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("username", $con);
$result = mysql_query("SELECT * FROM wallnames2011 WHERE firstname IS NOT NULL");
while($row = mysql_fetch_array($result)){
echo $row['firstname'] . " - " . $row['city'] . ", " .$row['state'] . " | ";
}
?>
```
I want to keep the empty rows out.
|
2011/02/23
|
[
"https://Stackoverflow.com/questions/5095471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237153/"
] |
why u not put
>
> Try SELECT column\_name FROM table\_name WHERE column\_name!=''
>
>
>
|
To print out only `rowname` and result from rows where result `IS NOT NULL`, try this:
```
if ($result = $mysqli->query($query)) {
/* fetch associative array */
$i=1;
while($a = $result->fetch_assoc()) {
$i++;
foreach ($a as $key => $value) {
if($value != NULL) {
echo $key." = ".$value."<br/>";
}
}
echo "-- <br />";
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
```
|
5,095,471 |
I have a small PHP mysql query looking at a table in my database. It's pulling all rows and then echoing out the record.
Problem is I have a few empty rows in the table so what I get is a weird looking record.
This is what I got:
```
<?php
$con = mysql_connect("localhost","username","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("username", $con);
$result = mysql_query("SELECT * FROM wallnames2011 WHERE firstname IS NOT NULL");
while($row = mysql_fetch_array($result)){
echo $row['firstname'] . " - " . $row['city'] . ", " .$row['state'] . " | ";
}
?>
```
I want to keep the empty rows out.
|
2011/02/23
|
[
"https://Stackoverflow.com/questions/5095471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237153/"
] |
You can put an `if(!empty($row['firstname']))` before you echo the row.
|
I think in the "where" clause mention all field names like `first_name IS NOT NULL AND last_name IS NOT NULL`.
|
5,095,471 |
I have a small PHP mysql query looking at a table in my database. It's pulling all rows and then echoing out the record.
Problem is I have a few empty rows in the table so what I get is a weird looking record.
This is what I got:
```
<?php
$con = mysql_connect("localhost","username","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("username", $con);
$result = mysql_query("SELECT * FROM wallnames2011 WHERE firstname IS NOT NULL");
while($row = mysql_fetch_array($result)){
echo $row['firstname'] . " - " . $row['city'] . ", " .$row['state'] . " | ";
}
?>
```
I want to keep the empty rows out.
|
2011/02/23
|
[
"https://Stackoverflow.com/questions/5095471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237153/"
] |
why u not put
>
> Try SELECT column\_name FROM table\_name WHERE column\_name!=''
>
>
>
|
Alex's empty check is good, and you can also check all three of them inline if you want to display incomplete records:
```
echo (! empty($row['firstname']) ? $row['firstname'] : "")
.(! empty($row['city']) ? " - ".$row['city'] : "")
.(! empty($row['state']) ? ", ".$row['state'] : "")
. " | ";
```
|
5,095,471 |
I have a small PHP mysql query looking at a table in my database. It's pulling all rows and then echoing out the record.
Problem is I have a few empty rows in the table so what I get is a weird looking record.
This is what I got:
```
<?php
$con = mysql_connect("localhost","username","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("username", $con);
$result = mysql_query("SELECT * FROM wallnames2011 WHERE firstname IS NOT NULL");
while($row = mysql_fetch_array($result)){
echo $row['firstname'] . " - " . $row['city'] . ", " .$row['state'] . " | ";
}
?>
```
I want to keep the empty rows out.
|
2011/02/23
|
[
"https://Stackoverflow.com/questions/5095471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237153/"
] |
Alex's empty check is good, and you can also check all three of them inline if you want to display incomplete records:
```
echo (! empty($row['firstname']) ? $row['firstname'] : "")
.(! empty($row['city']) ? " - ".$row['city'] : "")
.(! empty($row['state']) ? ", ".$row['state'] : "")
. " | ";
```
|
I think in the "where" clause mention all field names like `first_name IS NOT NULL AND last_name IS NOT NULL`.
|
5,095,471 |
I have a small PHP mysql query looking at a table in my database. It's pulling all rows and then echoing out the record.
Problem is I have a few empty rows in the table so what I get is a weird looking record.
This is what I got:
```
<?php
$con = mysql_connect("localhost","username","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("username", $con);
$result = mysql_query("SELECT * FROM wallnames2011 WHERE firstname IS NOT NULL");
while($row = mysql_fetch_array($result)){
echo $row['firstname'] . " - " . $row['city'] . ", " .$row['state'] . " | ";
}
?>
```
I want to keep the empty rows out.
|
2011/02/23
|
[
"https://Stackoverflow.com/questions/5095471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237153/"
] |
Alex's empty check is good, and you can also check all three of them inline if you want to display incomplete records:
```
echo (! empty($row['firstname']) ? $row['firstname'] : "")
.(! empty($row['city']) ? " - ".$row['city'] : "")
.(! empty($row['state']) ? ", ".$row['state'] : "")
. " | ";
```
|
To print out only `rowname` and result from rows where result `IS NOT NULL`, try this:
```
if ($result = $mysqli->query($query)) {
/* fetch associative array */
$i=1;
while($a = $result->fetch_assoc()) {
$i++;
foreach ($a as $key => $value) {
if($value != NULL) {
echo $key." = ".$value."<br/>";
}
}
echo "-- <br />";
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
```
|
5,095,471 |
I have a small PHP mysql query looking at a table in my database. It's pulling all rows and then echoing out the record.
Problem is I have a few empty rows in the table so what I get is a weird looking record.
This is what I got:
```
<?php
$con = mysql_connect("localhost","username","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("username", $con);
$result = mysql_query("SELECT * FROM wallnames2011 WHERE firstname IS NOT NULL");
while($row = mysql_fetch_array($result)){
echo $row['firstname'] . " - " . $row['city'] . ", " .$row['state'] . " | ";
}
?>
```
I want to keep the empty rows out.
|
2011/02/23
|
[
"https://Stackoverflow.com/questions/5095471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237153/"
] |
why u not put
>
> Try SELECT column\_name FROM table\_name WHERE column\_name!=''
>
>
>
|
I think in the "where" clause mention all field names like `first_name IS NOT NULL AND last_name IS NOT NULL`.
|
5,095,471 |
I have a small PHP mysql query looking at a table in my database. It's pulling all rows and then echoing out the record.
Problem is I have a few empty rows in the table so what I get is a weird looking record.
This is what I got:
```
<?php
$con = mysql_connect("localhost","username","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("username", $con);
$result = mysql_query("SELECT * FROM wallnames2011 WHERE firstname IS NOT NULL");
while($row = mysql_fetch_array($result)){
echo $row['firstname'] . " - " . $row['city'] . ", " .$row['state'] . " | ";
}
?>
```
I want to keep the empty rows out.
|
2011/02/23
|
[
"https://Stackoverflow.com/questions/5095471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237153/"
] |
Try SELECT column\_name
FROM table\_name
WHERE TRIM(column\_name) IS NOT NULL
|
I think in the "where" clause mention all field names like `first_name IS NOT NULL AND last_name IS NOT NULL`.
|
5,095,471 |
I have a small PHP mysql query looking at a table in my database. It's pulling all rows and then echoing out the record.
Problem is I have a few empty rows in the table so what I get is a weird looking record.
This is what I got:
```
<?php
$con = mysql_connect("localhost","username","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("username", $con);
$result = mysql_query("SELECT * FROM wallnames2011 WHERE firstname IS NOT NULL");
while($row = mysql_fetch_array($result)){
echo $row['firstname'] . " - " . $row['city'] . ", " .$row['state'] . " | ";
}
?>
```
I want to keep the empty rows out.
|
2011/02/23
|
[
"https://Stackoverflow.com/questions/5095471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/237153/"
] |
Try SELECT column\_name
FROM table\_name
WHERE TRIM(column\_name) IS NOT NULL
|
Alex's empty check is good, and you can also check all three of them inline if you want to display incomplete records:
```
echo (! empty($row['firstname']) ? $row['firstname'] : "")
.(! empty($row['city']) ? " - ".$row['city'] : "")
.(! empty($row['state']) ? ", ".$row['state'] : "")
. " | ";
```
|
2,495,932 |
Question: Take $\prec$ to be primitive and define $\preceq$ and $\sim$ in terms of $\prec$.
Would I write:
$x\preceq y$: $x \prec y$ (or would I not include this here?), not $(y \prec x)$;
$x \sim y$: not $(x \prec y)$ and not $(y \prec x)$?
I know how to take $\preceq$ and define $\prec$ and $\sim$ in terms of $\preceq$ but not starting with $\prec$.
|
2017/10/30
|
[
"https://math.stackexchange.com/questions/2495932",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/481752/"
] |
Isn't it a matter of angle chasing?
[](https://i.stack.imgur.com/UccpS.jpg)
|
Find $\angle AMD$ from the isosceles triangle MAD instead.
See if $\angle AMD + \angle AMB + \angle BMP = 180^0$ or not.
Added:
M is a point between P and D. There are only two cases that can happen:- (1) PM and MD form a straight line; or (2) PM and MD together form a crooked V; [but not both].
If $\angle AMD + \angle AMB + \angle BMP = 180^0$, case (2) is untrue. Then. we are left with case (1) only. The method used above is the theorem quoted as "adjacent angles supplementary" and is the major method used by Euclide to prove collinearity.
|
46,287,242 |
I'm typing my first obiect program - BlackJack, and I have problem with print card image.
My class Card extended JLabel and has ImageIcon property.
```
package Blackjack;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class Card extends JLabel{
private final String suit, faceName;
private int cardValue;
private boolean isVisible = false;
private BufferedImage cardImage;
public ImageIcon cardIcon;
public Card(String suit, String faceName){
this.suit = suit;
this.faceName = faceName;
//this.cardImage = getCardImage();
this.cardIcon = new ImageIcon(getCardImage());
switch(faceName){
case "2":
this.cardValue = 2;
break;
case "3":
this.cardValue = 3;
break;
case "4":
this.cardValue = 4;
break;
case "5":
this.cardValue = 5;
break;
case "6":
this.cardValue = 6;
break;
case "7":
this.cardValue = 7;
break;
case "8":
this.cardValue = 8;
break;
case "9":
this.cardValue = 9;
break;
case "10":
this.cardValue = 10;
break;
case "Jack":
this.cardValue = 10;
break;
case "Queen":
this.cardValue = 10;
break;
case "King":
this.cardValue = 10;
break;
case "Ace":
this.cardValue = 11;
break;
}
}
public void setCardVisible(boolean v){
isVisible = v;
}
public boolean getVisible(){
return isVisible;
}
public String getCardName(){
if (isVisible)
return faceName + " of " + suit;
else
return "Karta zakryta";
}
public int getCardValue(){
if (isVisible)
return cardValue;
else
return 0;
}
public BufferedImage getCardImage(){ //dopisać
String fileName;
if (faceName.equals("10"))
fileName = "T";
else if (faceName.equals("Jack"))
fileName = "J";
else if (faceName.equals("Queen"))
fileName = "Q";
else if (faceName.equals("King"))
fileName = "K";
else if (faceName.equals("Ace"))
fileName = "A";
else
fileName = faceName;
fileName = fileName + suit.substring(0, 1).toUpperCase();
File imgFile = new File("img/" + fileName + ".png");
try{
if (isVisible)
cardImage = ImageIO.read(imgFile);
else
cardImage = ImageIO.read(new File("img/RE.png"));
}
catch (IOException e) {
System.err.println("Blad odczytu obrazka");
e.printStackTrace();
}
Dimension dimension = new Dimension(cardImage.getWidth(), cardImage.getHeight());
setPreferredSize(dimension);
return cardImage;
}
}
```
Next class is Table extended JPanel
```
package Blackjack;
import java.awt.Color;
import javax.swing.JPanel;
public class Table extends JPanel{
private Deck deck;
private Player player;
private Dealer dealer;
private Hand dealerHand;
private Hand playerHand;
public Table(Deck d, Dealer dealer, Player player){
this.deck = d;
this.deck.shuffleDeck();
this.dealer = dealer;
this.player = player;
this.dealerHand = dealer.getPlayerHand();
this.playerHand = player.getPlayerHand();
this.setBackground(Color.GREEN);
}
public Player getPlayer(){
return player;
}
public Dealer getDealer(){
return dealer;
}
public Deck getDeck(){
return deck;
}
}
```
And class Game extended JFrame
```
package Blackjack;
import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Game extends JFrame{
private Table table;
public Game(Table t){
JFrame frame = new JFrame("BlackJack game");
frame.setSize(800, 500);
frame.setLayout(new BorderLayout());
frame.add(t, BorderLayout.CENTER);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main (String[] args){
Deck deck = new Deck();
Player player = new Player();
Dealer dealer = new Dealer();
Table table = new Table (deck, dealer, player);
player.hitCard(deck.drawCard());
player.getPlayerHand().getCardsInHand().get(0).setCardVisible(true);
table.getDealer().hitCard(table.getDeck().drawCard());
dealer.getPlayerHand().getCardsInHand().get(0).setCardVisible(true);
player.hitCard(deck.drawCard());
player.getPlayerHand().getCardsInHand().get(1).setCardVisible(true);
dealer.hitCard(deck.drawCard());
table.add(player.getPlayerHand().getCardsInHand().get(0));
for (Card c : player.getPlayerHand().getCardsInHand())
System.out.println(c.getCardName());
for (Card c : dealer.getPlayerHand().getCardsInHand())
System.out.println(c.getCardName());
Game g = new Game(table);
}
}
```
How should I correctly add card image on my window? Because this
```
table.add(player.getPlayerHand().getCardsInHand().get(0));
```
didn't work... I see only empty green window with JPanels.
|
2017/09/18
|
[
"https://Stackoverflow.com/questions/46287242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8627376/"
] |
The primary problem is, you never actually set the `icon` property of the `JLabel`, so it has nothing to show
What I would recommend doing, is creating an instance of the face and back image and when the visible state changes, change the `icon` property
```
public class Card extends JLabel {
private final String suit, faceName;
private int cardValue;
private boolean isVisible = false;
private BufferedImage faceImage;
private BufferedImage backImage;
public Card(String suit, String faceName) {
this.suit = suit;
this.faceName = faceName;
this.faceImage = getCardFaceImage();
backImage = getCardBackImage();
setCardVisible(false);
switch (faceName) {
case "2":
this.cardValue = 2;
break;
case "3":
this.cardValue = 3;
break;
case "4":
this.cardValue = 4;
break;
case "5":
this.cardValue = 5;
break;
case "6":
this.cardValue = 6;
break;
case "7":
this.cardValue = 7;
break;
case "8":
this.cardValue = 8;
break;
case "9":
this.cardValue = 9;
break;
case "10":
this.cardValue = 10;
break;
case "Jack":
this.cardValue = 10;
break;
case "Queen":
this.cardValue = 10;
break;
case "King":
this.cardValue = 10;
break;
case "Ace":
this.cardValue = 11;
break;
}
}
public void setCardVisible(boolean v) {
isVisible = v;
if (isVisible) {
setIcon(new ImageIcon(faceImage));
} else {
setIcon(new ImageIcon(backImage));
}
}
public boolean isCardVisible() {
return isVisible;
}
public String getCardName() {
if (isVisible) {
return faceName + " of " + suit;
} else {
return "Karta zakryta";
}
}
public int getCardValue() {
if (isVisible) {
return cardValue;
} else {
return 0;
}
}
protected BufferedImage getCardFaceImage() { //dopisać
String fileName;
if (faceName.equals("10")) {
fileName = "T";
} else if (faceName.equals("Jack")) {
fileName = "J";
} else if (faceName.equals("Queen")) {
fileName = "Q";
} else if (faceName.equals("King")) {
fileName = "K";
} else if (faceName.equals("Ace")) {
fileName = "A";
} else {
fileName = faceName;
}
BufferedImage img = new BufferedImage(100, 200, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.RED);
g2d.fill(new Rectangle(100, 200));
g2d.dispose();
// fileName = fileName + suit.substring(0, 1).toUpperCase();
// File imgFile = new File("img/" + fileName + ".png");
// try {
// if (isVisible) {
// cardImage = ImageIO.read(imgFile);
// } else {
// cardImage = ImageIO.read(new File("img/RE.png"));
// }
// } catch (IOException e) {
// System.err.println("Blad odczytu obrazka");
// e.printStackTrace();
// }
// Dimension dimension = new Dimension(cardImage.getWidth(), cardImage.getHeight());
// setPreferredSize(dimension);
return img;
}
protected BufferedImage getCardBackImage() { //dopisać
BufferedImage img = new BufferedImage(100, 200, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setColor(Color.BLUE);
g2d.fill(new Rectangle(100, 200));
g2d.dispose();
return img;
}
}
```
You don't need to change the `preferredSize`, the `JLabel` will take care of that itself.
When you change the state of the card's visibility, don't forget to switch the images...
```
public void setCardVisible(boolean v) {
isVisible = v;
if (isVisible) {
setIcon(new ImageIcon(faceImage));
} else {
setIcon(new ImageIcon(backImage));
}
}
```
And don't forget to call this in your constructor, after you've loaded the images ;)
As a general recommendation, instead of dealing with `String` as card name/suits, which allows a lot of possible errors, constraint the values to a small, known group using `enum`
```
public enum CardFace {
TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, JACK, QUEEN, KING, ACE
}
public enum CardSuit {
HEARTS, DIAMONDS, CLUBS, SPADES
}
public class Card extends JLabel {
private CardSuit suit;
private CardFace face;
//...
public Card(String CardSuits, CardFace faceName) {
```
While this might seem like a nit pick (and it kind of is), you can expand the `enum`s to do other tasks, for example, you can assign each instance with it's name
```
public enum CardFace {
TWO("Two"), ...;
private String name;
private CardFace(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
```
You could even assign the face value to the `enum`...
```
public enum CardFace {
TWO("Two", 2), ...;
private String name;
private int value;
private CardFace(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public int getValue() {
return value;
}
}
```
|
Instead of creating another `JFrame` (also pointed out by @user1803551) within the extended class, just set the frame up as this. This will still give you only one window.
```
public class Game extends JFrame{
private Table table;
public Game(Table t){
setSize(800, 500);
setLayout(new BorderLayout());
add(t, BorderLayout.CENTER);
//setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main (String[] args){
Deck deck = new Deck();
Player player = new Player();
Dealer dealer = new Dealer();
Table table = new Table (deck, dealer, player);
player.hitCard(deck.drawCard());
player.getPlayerHand().getCardsInHand().get(0).setCardVisible(true);
table.getDealer().hitCard(table.getDeck().drawCard());
dealer.getPlayerHand().getCardsInHand().get(0).setCardVisible(true);
player.hitCard(deck.drawCard());
player.getPlayerHand().getCardsInHand().get(1).setCardVisible(true);
dealer.hitCard(deck.drawCard());
table.add(player.getPlayerHand().getCardsInHand().get(0));
for (Card c : player.getPlayerHand().getCardsInHand())
System.out.println(c.getCardName());
for (Card c : dealer.getPlayerHand().getCardsInHand())
System.out.println(c.getCardName());
Game g = new Game(table);
//g.setLayout(new BorderLayout());
//g.add(table, BorderLayout.CENTER); // your table
g.setVisible(true);
}
```
Anything you add to the frame can be done direct from the `Game` class.
EDIT: added the layout and the `Table` (Removed again)
EDIT2:
Within your code I've noticed you do use `System.out.println()` for debug output. Without more information on your output, there's not much else to suggest apart from validating that your images are being loaded correctly, or even the file exists (`File.exists()`) which will show whether the path is correct too. If they load, then output the dimensions of the image and ensure the `JLable` is also set.
My best suggestion would be to use more of the debug output to find where the problem lies. The classes `Deck` and `Dealer` are missing which only leads us to speculate.
|
52,503,263 |
I don't know why as I'm following the official documentation but the functions of onChipAdd and onChipDelete are not called when adding and deleting chips.
```
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.chips');
var instances = M.Chips.init(elems, {
placeholder: 'Entrer un filtre',
secondaryPlaceholder: '+Filtre',
autocompleteOptions: {
data: {
{% for tag in tags %}
{{ tag }}: null,
{% endfor %}
},
limit: Infinity,
minLength: 1
},
onChipAdd: function (e, data) { console.log("test") },
onChipDelete: function (e, data) { console.log("test") }
});
});
```
Thanks
|
2018/09/25
|
[
"https://Stackoverflow.com/questions/52503263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4334777/"
] |
Ok, I got the answer on the chat with the team:
```
function chipAddCallback() {
const lastTagAdded = this.chipsData[this.chipsData.length - 1].tag;
const message = `"${lastTagAdded}" Chip added!`;
console.log(message);
}
function chipDeleteCallback() {
console.log("Chip Deleted!");
}
function init() {
$(".chips").chips({
placeholder: "Entrer un filtre",
secondaryPlaceholder: "+Filtre",
onChipAdd: chipAddCallback,
onChipDelete: chipDeleteCallback,
autocompleteOptions: {
data: {
{% for tag in tags %}
{{ tag }}: null,
{% endfor %}
},
limit: Infinity,
minLength: 1
}
});
}
$(init);
```
I don't know why this beaviour for calling the init is the good one, but it's working
|
You've to use `options` like this to call the callback functions of chips.
```
<div class="chips"></div>
<script>
document.addEventListener('DOMContentLoaded', function () {
var options = {
onChipAdd() {
console.log("added");
},
onChipSelect() {
console.log("Selected");
},
onChipDelete() {
console.log("Deleted");
},
placeholder: 'Entrer un filtre',
secondaryPlaceholder: '+Filtre',
autocompleteOptions: {
data: {
'Apple': null,
'Microsoft': null,
'Google': null
},
limit: Infinity,
minLength: 1
}
}
var elems = document.querySelector('.chips');
var instances = M.Chips.init(elems, options);
});
</script>
```
[](https://i.stack.imgur.com/TIsu9.gif)
|
52,503,263 |
I don't know why as I'm following the official documentation but the functions of onChipAdd and onChipDelete are not called when adding and deleting chips.
```
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.chips');
var instances = M.Chips.init(elems, {
placeholder: 'Entrer un filtre',
secondaryPlaceholder: '+Filtre',
autocompleteOptions: {
data: {
{% for tag in tags %}
{{ tag }}: null,
{% endfor %}
},
limit: Infinity,
minLength: 1
},
onChipAdd: function (e, data) { console.log("test") },
onChipDelete: function (e, data) { console.log("test") }
});
});
```
Thanks
|
2018/09/25
|
[
"https://Stackoverflow.com/questions/52503263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4334777/"
] |
Ok, I got the answer on the chat with the team:
```
function chipAddCallback() {
const lastTagAdded = this.chipsData[this.chipsData.length - 1].tag;
const message = `"${lastTagAdded}" Chip added!`;
console.log(message);
}
function chipDeleteCallback() {
console.log("Chip Deleted!");
}
function init() {
$(".chips").chips({
placeholder: "Entrer un filtre",
secondaryPlaceholder: "+Filtre",
onChipAdd: chipAddCallback,
onChipDelete: chipDeleteCallback,
autocompleteOptions: {
data: {
{% for tag in tags %}
{{ tag }}: null,
{% endfor %}
},
limit: Infinity,
minLength: 1
}
});
}
$(init);
```
I don't know why this beaviour for calling the init is the good one, but it's working
|
The below code works fine for me. I modified Germa's answer above a little bit. The only thing different is that onChipAdd, onChipSelect and onChipDelete are arrow functions. Check it out and give it a try for yourself.
```
document.addEventListener('DOMContentLoaded', function() {
let elems = document.querySelector('.chips');
let options = {
onChipAdd: () => console.log("added"),
onChipSelect: () => console.log("Selected"),
onChipDelete: () => console.log("Deleted"),
placeholder: 'Entrer un filtre',
secondaryPlaceholder: '+ filtre',
autocompleteOptions: {
data: {
'Apple': null,
'Microsoft': null,
'Google': null
},
limit: Infinity,
minLength: 1
}
}
let instances = M.Chips.init(elems, options);
});
```
|
43,501,782 |
I'm looking through an API, and all the examples are given using [cURL](https://curl.haxx.se/docs/manpage.html). I don't use cURL myself, and am looking for equivalent URL strings that I can send as GET arguments.
For example, say the cURL command is this:
```
$ curl -X GET "https://thesite.com/api/orgs" \
-u "NEekIy8ngCpv8TbOjrliapP0D1Bu9SN9:"
```
What would be the equivalent URL string to this? Something that could be copied and pasted into a browser, and would return the appropriate JSON response. Something like:
`https://thesite.com/api/orgs?user=NEekIy8ngCpv8TbOjrliapP0D1Bu9SN9` ??
The [cURL docs](https://curl.haxx.se/docs/manpage.html) say that `-u` is `user:password`, which is why I figured that the GET variable(s) for the previous cURL command were `user=NEekIy8ngCpv8TbOjrliapP0D1Bu9SN9` (and `password=` ?)
Is this the right conversion? No matter where I look, I can't find an equivalency chart anywhere. Even a quick code I could write in PHP or JS to create a cURL object, and then return the formatted URL string would suffice.
|
2017/04/19
|
[
"https://Stackoverflow.com/questions/43501782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3170465/"
] |
This is related to the Authorization HTTP header and [HTTP Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication), which will contain the username and the password. But this username is not a GET parameter, it goes into an HTTP Header, so it cannot be used it in the query string (?user=...).
The string equivalent to this, that should work when put into an address bar of a browser is :
```
user:[email protected]/api/orgs
```
If you use
```
[email protected]/api/orgs
```
You will be prompted for a message box asking for username and password.
This works if the method from server side is "basic" or "digest". There are plenty of other auth methods used. As I'm not specialized in this topic, I cannot tell you if it will always work.
Also have a look at this last note on the linked page :
>
> The use of these URLs is deprecated. ...
>
>
>
|
You can use [file\_get\_contents](http://php.net/manual/en/function.file-get-contents.php) it does the same as curl
Code example:
```
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
```
To send $\_POST and $\_GET requests you can use [Guzzle](http://docs.guzzlephp.org/en/latest/) <http://docs.guzzlephp.org/en/latest/>
Code example:
```
<?php
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://api.github.com/user', [
'auth' => ['user', 'pass']
]);
echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
?>
```
|
4,862,754 |
```
string filePath = ExportAndSaveInvoiceAsHtml(invoiceId);
Response.AddHeader("Content-Disposition", "attachment;filename=" + Path.GetFileName(filePath));
Response.WriteFile(filePath);
// Using Response.End() solves the problem
// Response.End();
```
I want to enable users to download HTML invoice (from gridView of invoices). The resulting file contains the invoice file data + unwanted the page html also.
If i use Response.End(), it solves the problem, but then it always throws exception. Read in some threads that exception is by design. But then is it sure, it wont cause problem like response truncation or so anytime ?
How else can i write JUST the file data.
Btw, earlier we wrote invoice as PDF, and that time not using Response.End() caused incomplete file download.
Can someone give basics of writing custom data/file to Response stream.
|
2011/02/01
|
[
"https://Stackoverflow.com/questions/4862754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/520348/"
] |
That's because the response is *buffered*. You have to call [Response.End()](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.end.aspx) to flush the buffers and ensure the client gets the complete response before the handler thread completes.
The [ThreadAbortException](http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx) thrown by `Response.End()` is by design and can safely be ignored.
|
Instead of Response.End() you can use
```
HttpContext.Current.ApplicationInstance.CompleteRequest()
```
This method tend to avoid throwing exceptions :)
|
2 |
Are discussion question okay? I'd like to start a discussion on why XSS should be renamed Script Injection, and if there is agreement on that (I've got a few arguments), if and how we could go about promoting it.
If the question would get shot down anyway, I wouldn't want to waste time writing down the arguments...
|
2010/11/11
|
[
"https://security.meta.stackexchange.com/questions/2",
"https://security.meta.stackexchange.com",
"https://security.meta.stackexchange.com/users/18/"
] |
Contrary to my previous answer (which I still prefer - but it looks like its not gonna happen) - if this is an all-inclusive, all-things-information-security, then we should also put more emphasis on other parts of infosec too, such as risk management, cryptography, etc.
E.g. the following Area51 proposals should also be merged into here:
* <http://area51.stackexchange.com/proposals/4500/infosec-and-risk-management>
* <http://area51.stackexchange.com/proposals/14373/php-specific-security-issues-and-best-practices>
* <http://area51.stackexchange.com/proposals/18054/white-hat-hacking>
* <http://area51.stackexchange.com/proposals/11464/code-review>
* <http://area51.stackexchange.com/proposals/15811/cryptography>
I also dislike the name "IT Security" (see [this question](https://security.meta.stackexchange.com/questions/9/is-the-site-name-it-security-or-app-security)), since IT is often understood as "the IT department of large corporations", which is still more focused on firewalls and user management. I'd even prefer "InfoSecurity", which is more true to the spirit.
|
As I said [here](https://security.meta.stackexchange.com/q/9/33), I think this site should be focused on Application Security only, thats a wide enough topic - but not just web security.
While I might understand why @Robert would want to merge them, it's crystal clear that SO could not have included SF - completely different worlds...
|
2 |
Are discussion question okay? I'd like to start a discussion on why XSS should be renamed Script Injection, and if there is agreement on that (I've got a few arguments), if and how we could go about promoting it.
If the question would get shot down anyway, I wouldn't want to waste time writing down the arguments...
|
2010/11/11
|
[
"https://security.meta.stackexchange.com/questions/2",
"https://security.meta.stackexchange.com",
"https://security.meta.stackexchange.com/users/18/"
] |
I agree with AviD on the professional vs end-user demarcation. I think the core assumption is that security professionals (or IT folks with a security responsibility) will be the ones coming here and posing questions or delivering answers.
So from your question, how to implement a specific security task may well be appropriate, but discussing whether application a or b is better at the task is very subjective. What would be most appropriate is to discuss how the security professional should manage the task, and what risks or gotchas to be aware of.
I feel it should also include the security around frameworks, infrastructure and the other pieces that enable applications, as at the end of the day it is all about making the business secure.
|
As I said [here](https://security.meta.stackexchange.com/q/9/33), I think this site should be focused on Application Security only, thats a wide enough topic - but not just web security.
While I might understand why @Robert would want to merge them, it's crystal clear that SO could not have included SF - completely different worlds...
|
2 |
Are discussion question okay? I'd like to start a discussion on why XSS should be renamed Script Injection, and if there is agreement on that (I've got a few arguments), if and how we could go about promoting it.
If the question would get shot down anyway, I wouldn't want to waste time writing down the arguments...
|
2010/11/11
|
[
"https://security.meta.stackexchange.com/questions/2",
"https://security.meta.stackexchange.com",
"https://security.meta.stackexchange.com/users/18/"
] |
Contrary to my previous answer (which I still prefer - but it looks like its not gonna happen) - if this is an all-inclusive, all-things-information-security, then we should also put more emphasis on other parts of infosec too, such as risk management, cryptography, etc.
E.g. the following Area51 proposals should also be merged into here:
* <http://area51.stackexchange.com/proposals/4500/infosec-and-risk-management>
* <http://area51.stackexchange.com/proposals/14373/php-specific-security-issues-and-best-practices>
* <http://area51.stackexchange.com/proposals/18054/white-hat-hacking>
* <http://area51.stackexchange.com/proposals/11464/code-review>
* <http://area51.stackexchange.com/proposals/15811/cryptography>
I also dislike the name "IT Security" (see [this question](https://security.meta.stackexchange.com/questions/9/is-the-site-name-it-security-or-app-security)), since IT is often understood as "the IT department of large corporations", which is still more focused on firewalls and user management. I'd even prefer "InfoSecurity", which is more true to the spirit.
|
I agree with AviD on the professional vs end-user demarcation. I think the core assumption is that security professionals (or IT folks with a security responsibility) will be the ones coming here and posing questions or delivering answers.
So from your question, how to implement a specific security task may well be appropriate, but discussing whether application a or b is better at the task is very subjective. What would be most appropriate is to discuss how the security professional should manage the task, and what risks or gotchas to be aware of.
I feel it should also include the security around frameworks, infrastructure and the other pieces that enable applications, as at the end of the day it is all about making the business secure.
|
281,787 |
Going forward, “rep-whore” (and its derivatives) will be treated like any other term that’s inconsistent with the community’s “be nice” policy: it will be removed.
It’s totally okay if you’ve used it in the past.
================================================
Nobody’s judging the many users who’ve used it. And users will NOT start being suspended/banned/fed-to-the-Sarlaac for using it in the near future without knowing about the change. We’re all partly products of what’s “normal” in our environment, and for a long time, use of that term *was* normal, and intended as a shorthand for “users who know a behavior is harmful, but do it anyway, entirely because it generates rep.” It was used - without malice - by good-hearted users in lots of old posts. It has probably been used by employees occasionally in the past. There’s no shame or judgment implied here; it’s just time to recognize that it's not consistent with "be nice.” And its use actually undermines our ability to get the most out of needed discussions on user behavior, incentives, etc. To be clear, it *is* absolutely okay to talk about *specific behaviors* that may represent unintended consequences of the rep-based feedback loop, and to continue to question them - just don’t do it by name-calling.
The short version of the "why"
==============================
* It’s inconsistent with our “be nice" policy:
+ It’s vulgar, and may be construed as being gendered (albeit not intentionally, in my observations).
+ The term makes the problem about the *person, not the action*. (And it doesn’t help to verbify it as “rep-whoring” - that’s still only describing it as something a person-type would do, vs. a specific thing that was done.)
* Naming “user types” with pejorative terms tends to lead to over-use of those terms, and undermines actual dialogue that might help us better understand what's going wrong.
That really covers it. But we like to be as open as possible about our underlying thinking, so if you're curious, or have a lot of time to kill...
The longer version
==================
**The term clearly doesn't jibe with “being nice”:**
Here are the relevant parts of the [Be Nice policy](https://stackoverflow.com/help/be-nice):
>
> * No Name Calling - Focus on the post, not the person. That includes terms that feel personal even when they're applied to posts (like "lazy", "ignorant", or "whiny").\*
> * Rudeness and belittling language are not okay.
> * Avoid vulgar terms and anything sexually suggestive.
> * Be welcoming, be patient, and **assume good intentions** (emphasis mine)
>
>
>
Frankly, those are good enough reasons - this community has always been fairly united in our commitment to discuss problems openly, **but with strong commitment to respect and courtesy, and a focus on the content or behavior, not the person.**
So, even if this term *were* super-useful in helping us solve problems and improve the site, I think most folks here would agree that we shouldn’t be scrapping big chunks of our “be nice” policy just for the sake of expediency. But here’s the funny thing:
**Using terms like “rep-whore” tends to *undermine* our ability to break down situations and learn where the system does have real problems or unintended consequences.**
**Labeling users with names that almost no one would call themselves reduces two-sided discourse and learning.** We actually learn the most when we listen to those who *don’t* agree with us (yet, anyway - I like to think they’ll eventually come around). But when we say, “the problem is rep-whores,” to explain someone answering questions that we think should be closed instead, it reduces the number of folks motivated to say, “Oh, hey - I guess I’m one of those ‘rep-whores’. Is that what you call someone who just answers questions when they can, but doesn’t keep track of what’s on- and off-topic?” Note that I’m *not* saying that’s usually the actual case, but the problem is that we'd never know if it were. By just describing it as “rep-whoring,” we've cut off much hope of learning if another motivation might apply - we’ve *assumed* we know the motivation, and given it a nasty name, so any users involved who might wish to actually explain their motivations don’t even think we're talking about (non-whore-esque) folks like them.
**There’s a funny thing about *naming* something.** Once a thing has a name, you tend to start seeing it everywhere. That's part of the positive power of language: by giving a complex thing a shorthand term, it’s easier to identify it quickly, just by matching a couple of key variables. Heuristics like that are what let us function at higher efficiency. But they come with costs: false positives and loss of nuance. The entire *point* of these types of categorization is to allow faster pattern matching, with fewer inputs and less analysis. But that means that things with *some* shared attributes, or even just similar ones, can get (wrongly) lumped in buckets pretty quickly.
Which is how we find ourselves making assumptions about others. I may think:
>
> “Someone who answers a question that we’d normally close is obviously only motivated by rep, and clearly doesn't care that it’s hurting the site.”
>
>
>
Maybe. Maybe they *are* only motivated by rep. Or maybe it’s something else: Maybe they don’t know (or care) what’s on-topic; they choose to answer questions where they can help, but don’t want to have to also serve as a filter for what’s currently allowed.
Personally, *I* happen to think that’s okay. I’m actually good with the idea that helping here doesn't require, “helping in all the ways, including ones you don’t enjoy.” Now, you may not agree, and think it’s a problem. That's good! And if that were the situation, *that’s* what we need to be talking about. But by ascribing the problems to “rep-whores,” I’ve eliminated that fact-finding step, and potentially even *prevented* us from getting to some of the real issues that we might want to discuss, all to save a few minutes by slapping a convenient name on the situation.
**Caring about getting lots of rep is a little like caring about getting lots of money - it seems to be a problem that is only diagnosed as afflicting *other people.*** Posts about rep-whores are pretty consistently written by folks who say they’re *not* at all motivated by rep - that *they* would only do things for more altruistic reasons. Which… I happen to believe is true. I think almost all of them *are actually motivated by the desire to help, or to contribute to a useful resource.* So here’s the question: given that we know *we’d* only choose behaviors if we thought they were good for the site, why are we so quick to assume that rep is the *primary* driver of others’ behavior, regardless of the harm it might cause? I think part of it may be what's apparently known as the [actor–observer asymmetry/bias](https://en.wikipedia.org/wiki/Actor%E2%80%93observer_asymmetry). The gist is this - when *you* swerve your car without warning, you know you’re a responsible driver coping as best you can with challenging circumstances - you saw something in the road, or your kid finally succeeded in pitching a gummy bear into your ear. But when you see someone *else* swerve their car, you assume they’re a bad driver. Or texting. Or drunk.
**In conclusion…**
Let’s keep talking about rep, and unintended consequences. To be honest, we *want* people to care about it, but not *too* much, and not as an end unto itself. Rep *is* supposed to be motivating, largely as a feedback loop. It's designed to confirm that you’re achieving what you all really came here to do: share your experiences in way that generates a resource that will actually make a difference. That little green "+10" is a proxy for someone saying, "that was useful". Your effort here mattered. So it’s okay to like getting it. I do. But it’s also okay - in fact it’s important - to call out places where it may be over-incentivizing things we don’t want. Let's just do it without using terms that’ll make Julia Roberts sad:
[](https://i.stack.imgur.com/rsiXM.jpg)
**For now, don’t worry about purging old uses of the term.**
This isn’t intended to create a lot of new work, particularly for mods, so we don’t want folks searching through tons of old posts and throwing up hundreds of flags. But if you run into new uses of the term, treat em like any other thing inconsistent with “be nice” (edit ‘em out when possible, etc.)
|
2016/07/29
|
[
"https://meta.stackexchange.com/questions/281787",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147336/"
] |
Yeah... This seems like a good idea. The term has moved from its original jocular uses to something considerably more mean-spirited. I suspect most folks using the term now have some sort of nasty boogieman in mind rather than [good ol' Marc Gravell](https://meta.stackexchange.com/questions/15540/award-bounties-at-the-end-of-the-day/15553#15553).
And [when folks here are more concerned about what other people think of them](https://meta.stackoverflow.com/questions/254549/how-to-decide-which-questions-i-should-not-answer) than they are about programming, I think the term becomes decidedly counter-productive, no less a distraction than rep itself.
FWIW, "whore" has triggered fast deletion on flagged comments for quite a while, and has been banned outright on Stack Overflow for over two years *because* it was being used to harass people:

|
This feels a bit like [bowdlerisation](https://en.wikipedia.org/wiki/Thomas_Bowdler). I've *personally* avoided it and favour the term 'Power Gamer' or 'Bounty Hunter' (drawing from my mispent youth as a pen and paper gamer).
To me the 'be nice' policy isn't about language use. It's about ensuring that as many of my users (as a mod) feel as comfortable as possible, and I've almost never seen the term used as such.
I've never seen anyone actually *use* the term 'repwhore' in anger. It's used in terms of 'repwhorage' in some situations. (Interestingly, the term's been only used 6 times on Root Access. Mostly by me, referring to me. I encourage others to try this on, and it's been used 4 times on meta SU -- this isn't exactly common.) It might be different on other sites.
I feel 'be nice' is not about the *words*; it's about the *actions* and *overall intent*. If someone on a site I'm seeing went "hey, I'm not comfortable with someone calling me a repwhore" I'd obviously encourage the person who used that term to be more *precise* over what issues they have are. If someone called themselves a repwhore, or referred to an answer as repwhorage, it's a very different thing,
So, I think the solution here might not be to worry about the *term*. If it needs to be gone, encouraging *precision* and *focusing on the actions* is good moderation.
So as a mod, it feels like it's an attempt to solve a non existent problem. We can simply deal with people not being nice for its own sake without declaring war on a phrase.
|
281,787 |
Going forward, “rep-whore” (and its derivatives) will be treated like any other term that’s inconsistent with the community’s “be nice” policy: it will be removed.
It’s totally okay if you’ve used it in the past.
================================================
Nobody’s judging the many users who’ve used it. And users will NOT start being suspended/banned/fed-to-the-Sarlaac for using it in the near future without knowing about the change. We’re all partly products of what’s “normal” in our environment, and for a long time, use of that term *was* normal, and intended as a shorthand for “users who know a behavior is harmful, but do it anyway, entirely because it generates rep.” It was used - without malice - by good-hearted users in lots of old posts. It has probably been used by employees occasionally in the past. There’s no shame or judgment implied here; it’s just time to recognize that it's not consistent with "be nice.” And its use actually undermines our ability to get the most out of needed discussions on user behavior, incentives, etc. To be clear, it *is* absolutely okay to talk about *specific behaviors* that may represent unintended consequences of the rep-based feedback loop, and to continue to question them - just don’t do it by name-calling.
The short version of the "why"
==============================
* It’s inconsistent with our “be nice" policy:
+ It’s vulgar, and may be construed as being gendered (albeit not intentionally, in my observations).
+ The term makes the problem about the *person, not the action*. (And it doesn’t help to verbify it as “rep-whoring” - that’s still only describing it as something a person-type would do, vs. a specific thing that was done.)
* Naming “user types” with pejorative terms tends to lead to over-use of those terms, and undermines actual dialogue that might help us better understand what's going wrong.
That really covers it. But we like to be as open as possible about our underlying thinking, so if you're curious, or have a lot of time to kill...
The longer version
==================
**The term clearly doesn't jibe with “being nice”:**
Here are the relevant parts of the [Be Nice policy](https://stackoverflow.com/help/be-nice):
>
> * No Name Calling - Focus on the post, not the person. That includes terms that feel personal even when they're applied to posts (like "lazy", "ignorant", or "whiny").\*
> * Rudeness and belittling language are not okay.
> * Avoid vulgar terms and anything sexually suggestive.
> * Be welcoming, be patient, and **assume good intentions** (emphasis mine)
>
>
>
Frankly, those are good enough reasons - this community has always been fairly united in our commitment to discuss problems openly, **but with strong commitment to respect and courtesy, and a focus on the content or behavior, not the person.**
So, even if this term *were* super-useful in helping us solve problems and improve the site, I think most folks here would agree that we shouldn’t be scrapping big chunks of our “be nice” policy just for the sake of expediency. But here’s the funny thing:
**Using terms like “rep-whore” tends to *undermine* our ability to break down situations and learn where the system does have real problems or unintended consequences.**
**Labeling users with names that almost no one would call themselves reduces two-sided discourse and learning.** We actually learn the most when we listen to those who *don’t* agree with us (yet, anyway - I like to think they’ll eventually come around). But when we say, “the problem is rep-whores,” to explain someone answering questions that we think should be closed instead, it reduces the number of folks motivated to say, “Oh, hey - I guess I’m one of those ‘rep-whores’. Is that what you call someone who just answers questions when they can, but doesn’t keep track of what’s on- and off-topic?” Note that I’m *not* saying that’s usually the actual case, but the problem is that we'd never know if it were. By just describing it as “rep-whoring,” we've cut off much hope of learning if another motivation might apply - we’ve *assumed* we know the motivation, and given it a nasty name, so any users involved who might wish to actually explain their motivations don’t even think we're talking about (non-whore-esque) folks like them.
**There’s a funny thing about *naming* something.** Once a thing has a name, you tend to start seeing it everywhere. That's part of the positive power of language: by giving a complex thing a shorthand term, it’s easier to identify it quickly, just by matching a couple of key variables. Heuristics like that are what let us function at higher efficiency. But they come with costs: false positives and loss of nuance. The entire *point* of these types of categorization is to allow faster pattern matching, with fewer inputs and less analysis. But that means that things with *some* shared attributes, or even just similar ones, can get (wrongly) lumped in buckets pretty quickly.
Which is how we find ourselves making assumptions about others. I may think:
>
> “Someone who answers a question that we’d normally close is obviously only motivated by rep, and clearly doesn't care that it’s hurting the site.”
>
>
>
Maybe. Maybe they *are* only motivated by rep. Or maybe it’s something else: Maybe they don’t know (or care) what’s on-topic; they choose to answer questions where they can help, but don’t want to have to also serve as a filter for what’s currently allowed.
Personally, *I* happen to think that’s okay. I’m actually good with the idea that helping here doesn't require, “helping in all the ways, including ones you don’t enjoy.” Now, you may not agree, and think it’s a problem. That's good! And if that were the situation, *that’s* what we need to be talking about. But by ascribing the problems to “rep-whores,” I’ve eliminated that fact-finding step, and potentially even *prevented* us from getting to some of the real issues that we might want to discuss, all to save a few minutes by slapping a convenient name on the situation.
**Caring about getting lots of rep is a little like caring about getting lots of money - it seems to be a problem that is only diagnosed as afflicting *other people.*** Posts about rep-whores are pretty consistently written by folks who say they’re *not* at all motivated by rep - that *they* would only do things for more altruistic reasons. Which… I happen to believe is true. I think almost all of them *are actually motivated by the desire to help, or to contribute to a useful resource.* So here’s the question: given that we know *we’d* only choose behaviors if we thought they were good for the site, why are we so quick to assume that rep is the *primary* driver of others’ behavior, regardless of the harm it might cause? I think part of it may be what's apparently known as the [actor–observer asymmetry/bias](https://en.wikipedia.org/wiki/Actor%E2%80%93observer_asymmetry). The gist is this - when *you* swerve your car without warning, you know you’re a responsible driver coping as best you can with challenging circumstances - you saw something in the road, or your kid finally succeeded in pitching a gummy bear into your ear. But when you see someone *else* swerve their car, you assume they’re a bad driver. Or texting. Or drunk.
**In conclusion…**
Let’s keep talking about rep, and unintended consequences. To be honest, we *want* people to care about it, but not *too* much, and not as an end unto itself. Rep *is* supposed to be motivating, largely as a feedback loop. It's designed to confirm that you’re achieving what you all really came here to do: share your experiences in way that generates a resource that will actually make a difference. That little green "+10" is a proxy for someone saying, "that was useful". Your effort here mattered. So it’s okay to like getting it. I do. But it’s also okay - in fact it’s important - to call out places where it may be over-incentivizing things we don’t want. Let's just do it without using terms that’ll make Julia Roberts sad:
[](https://i.stack.imgur.com/rsiXM.jpg)
**For now, don’t worry about purging old uses of the term.**
This isn’t intended to create a lot of new work, particularly for mods, so we don’t want folks searching through tons of old posts and throwing up hundreds of flags. But if you run into new uses of the term, treat em like any other thing inconsistent with “be nice” (edit ‘em out when possible, etc.)
|
2016/07/29
|
[
"https://meta.stackexchange.com/questions/281787",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147336/"
] |
Yeah... This seems like a good idea. The term has moved from its original jocular uses to something considerably more mean-spirited. I suspect most folks using the term now have some sort of nasty boogieman in mind rather than [good ol' Marc Gravell](https://meta.stackexchange.com/questions/15540/award-bounties-at-the-end-of-the-day/15553#15553).
And [when folks here are more concerned about what other people think of them](https://meta.stackoverflow.com/questions/254549/how-to-decide-which-questions-i-should-not-answer) than they are about programming, I think the term becomes decidedly counter-productive, no less a distraction than rep itself.
FWIW, "whore" has triggered fast deletion on flagged comments for quite a while, and has been banned outright on Stack Overflow for over two years *because* it was being used to harass people:

|
I've never used the term *rep-whore* and I agree that it sounds pejorative and belittling. Those who answer off-topic questions just to earn a few tens of reputation points should be called *SE user* because we did it one way or another in the past. However, what do you call a user who constantly answer off-topic questions?
The linked question was posted on English Language and Usage, [What's a less offensive substitute for “rep-whores”?](https://english.stackexchange.com/questions/226736/whats-a-less-offensive-substitute-for-rep-whores) and it suggests multiple alternatives.
(In order of the number of upvotes)
>
> Rep-hound
>
>
> Rep-farmer
>
>
> Rep-junkie
>
>
> Rep-monger
>
>
> Rep-minded
>
>
> Rep-reaper
>
>
> Rep-chaser
>
>
> ...
>
>
>
|
281,787 |
Going forward, “rep-whore” (and its derivatives) will be treated like any other term that’s inconsistent with the community’s “be nice” policy: it will be removed.
It’s totally okay if you’ve used it in the past.
================================================
Nobody’s judging the many users who’ve used it. And users will NOT start being suspended/banned/fed-to-the-Sarlaac for using it in the near future without knowing about the change. We’re all partly products of what’s “normal” in our environment, and for a long time, use of that term *was* normal, and intended as a shorthand for “users who know a behavior is harmful, but do it anyway, entirely because it generates rep.” It was used - without malice - by good-hearted users in lots of old posts. It has probably been used by employees occasionally in the past. There’s no shame or judgment implied here; it’s just time to recognize that it's not consistent with "be nice.” And its use actually undermines our ability to get the most out of needed discussions on user behavior, incentives, etc. To be clear, it *is* absolutely okay to talk about *specific behaviors* that may represent unintended consequences of the rep-based feedback loop, and to continue to question them - just don’t do it by name-calling.
The short version of the "why"
==============================
* It’s inconsistent with our “be nice" policy:
+ It’s vulgar, and may be construed as being gendered (albeit not intentionally, in my observations).
+ The term makes the problem about the *person, not the action*. (And it doesn’t help to verbify it as “rep-whoring” - that’s still only describing it as something a person-type would do, vs. a specific thing that was done.)
* Naming “user types” with pejorative terms tends to lead to over-use of those terms, and undermines actual dialogue that might help us better understand what's going wrong.
That really covers it. But we like to be as open as possible about our underlying thinking, so if you're curious, or have a lot of time to kill...
The longer version
==================
**The term clearly doesn't jibe with “being nice”:**
Here are the relevant parts of the [Be Nice policy](https://stackoverflow.com/help/be-nice):
>
> * No Name Calling - Focus on the post, not the person. That includes terms that feel personal even when they're applied to posts (like "lazy", "ignorant", or "whiny").\*
> * Rudeness and belittling language are not okay.
> * Avoid vulgar terms and anything sexually suggestive.
> * Be welcoming, be patient, and **assume good intentions** (emphasis mine)
>
>
>
Frankly, those are good enough reasons - this community has always been fairly united in our commitment to discuss problems openly, **but with strong commitment to respect and courtesy, and a focus on the content or behavior, not the person.**
So, even if this term *were* super-useful in helping us solve problems and improve the site, I think most folks here would agree that we shouldn’t be scrapping big chunks of our “be nice” policy just for the sake of expediency. But here’s the funny thing:
**Using terms like “rep-whore” tends to *undermine* our ability to break down situations and learn where the system does have real problems or unintended consequences.**
**Labeling users with names that almost no one would call themselves reduces two-sided discourse and learning.** We actually learn the most when we listen to those who *don’t* agree with us (yet, anyway - I like to think they’ll eventually come around). But when we say, “the problem is rep-whores,” to explain someone answering questions that we think should be closed instead, it reduces the number of folks motivated to say, “Oh, hey - I guess I’m one of those ‘rep-whores’. Is that what you call someone who just answers questions when they can, but doesn’t keep track of what’s on- and off-topic?” Note that I’m *not* saying that’s usually the actual case, but the problem is that we'd never know if it were. By just describing it as “rep-whoring,” we've cut off much hope of learning if another motivation might apply - we’ve *assumed* we know the motivation, and given it a nasty name, so any users involved who might wish to actually explain their motivations don’t even think we're talking about (non-whore-esque) folks like them.
**There’s a funny thing about *naming* something.** Once a thing has a name, you tend to start seeing it everywhere. That's part of the positive power of language: by giving a complex thing a shorthand term, it’s easier to identify it quickly, just by matching a couple of key variables. Heuristics like that are what let us function at higher efficiency. But they come with costs: false positives and loss of nuance. The entire *point* of these types of categorization is to allow faster pattern matching, with fewer inputs and less analysis. But that means that things with *some* shared attributes, or even just similar ones, can get (wrongly) lumped in buckets pretty quickly.
Which is how we find ourselves making assumptions about others. I may think:
>
> “Someone who answers a question that we’d normally close is obviously only motivated by rep, and clearly doesn't care that it’s hurting the site.”
>
>
>
Maybe. Maybe they *are* only motivated by rep. Or maybe it’s something else: Maybe they don’t know (or care) what’s on-topic; they choose to answer questions where they can help, but don’t want to have to also serve as a filter for what’s currently allowed.
Personally, *I* happen to think that’s okay. I’m actually good with the idea that helping here doesn't require, “helping in all the ways, including ones you don’t enjoy.” Now, you may not agree, and think it’s a problem. That's good! And if that were the situation, *that’s* what we need to be talking about. But by ascribing the problems to “rep-whores,” I’ve eliminated that fact-finding step, and potentially even *prevented* us from getting to some of the real issues that we might want to discuss, all to save a few minutes by slapping a convenient name on the situation.
**Caring about getting lots of rep is a little like caring about getting lots of money - it seems to be a problem that is only diagnosed as afflicting *other people.*** Posts about rep-whores are pretty consistently written by folks who say they’re *not* at all motivated by rep - that *they* would only do things for more altruistic reasons. Which… I happen to believe is true. I think almost all of them *are actually motivated by the desire to help, or to contribute to a useful resource.* So here’s the question: given that we know *we’d* only choose behaviors if we thought they were good for the site, why are we so quick to assume that rep is the *primary* driver of others’ behavior, regardless of the harm it might cause? I think part of it may be what's apparently known as the [actor–observer asymmetry/bias](https://en.wikipedia.org/wiki/Actor%E2%80%93observer_asymmetry). The gist is this - when *you* swerve your car without warning, you know you’re a responsible driver coping as best you can with challenging circumstances - you saw something in the road, or your kid finally succeeded in pitching a gummy bear into your ear. But when you see someone *else* swerve their car, you assume they’re a bad driver. Or texting. Or drunk.
**In conclusion…**
Let’s keep talking about rep, and unintended consequences. To be honest, we *want* people to care about it, but not *too* much, and not as an end unto itself. Rep *is* supposed to be motivating, largely as a feedback loop. It's designed to confirm that you’re achieving what you all really came here to do: share your experiences in way that generates a resource that will actually make a difference. That little green "+10" is a proxy for someone saying, "that was useful". Your effort here mattered. So it’s okay to like getting it. I do. But it’s also okay - in fact it’s important - to call out places where it may be over-incentivizing things we don’t want. Let's just do it without using terms that’ll make Julia Roberts sad:
[](https://i.stack.imgur.com/rsiXM.jpg)
**For now, don’t worry about purging old uses of the term.**
This isn’t intended to create a lot of new work, particularly for mods, so we don’t want folks searching through tons of old posts and throwing up hundreds of flags. But if you run into new uses of the term, treat em like any other thing inconsistent with “be nice” (edit ‘em out when possible, etc.)
|
2016/07/29
|
[
"https://meta.stackexchange.com/questions/281787",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147336/"
] |
>
> It's time...
>
>
>
...it's time to keep the [promise](https://meta.stackoverflow.com/a/320971/839601) made three months ago:
>
> we'll start looking at [increasing the number of close votes based on rep](https://meta.stackexchange.com/questions/266500/proposal-to-make-close-votes-scale-with-rep)
>
>
>
You seem to be blaming users for unnecessary rudeness and trying to cut their ways to express it. That may be true and right, but if you think of it the [root cause](https://softwareengineering.stackexchange.com/a/154741/31260) for their attitude may lie elsewhere.
For example, if many inappropriate questions aren't closed quickly enough and this makes a wide open door for answers to leak into them, it may cause negative feelings for those who care about content quality. If this is the case, banning particular negative terms won't help. The negative feelings will stay; people will simply invent other terms to express them, and things won't really get nicer.
I think it's time to look closer at these things in the historical perspective.
For example, how come that after years of plugging users' mouths and twisting their arms with *summers of love* and *hunting the snark*, the second-highest-voted question at MSO is [Why is Stack Overflow so **negative** of late?](https://meta.stackoverflow.com/q/251758/839601) Makes one wonder if this way works, doesn't it?
---
You see, negative feelings (and their respective terms) may simply indicate that a community lacks power and tools to protect itself from inappropriate content.
I heard that the author who best explained these matters is a member of Stack Exchange's board of directors -- ([Clay Shirky](http://www.shirky.com/writings/group_enemy.html "who wrote 'A Group Is Its Own Worst Enemy'")) -- maybe it's time to have a word with him.
>
> thing you have to accept: Members are different than users. A pattern will arise in which there is some group of users that cares more than average about the integrity and success of the group as a whole. And that becomes your core group, Art Kleiner's phrase for "the group within the group that matters most."
>
>
> The core group... was undifferentiated from the group of random users that came in. They were separate in their own minds, because they knew what they wanted to do, but they couldn't defend themselves against the other users. But in all successful online communities that I've looked at, a core group arises that cares about and gardens effectively. Gardens the environment, to keep it growing, to keep it healthy.
>
>
> Now, the software does not always allow the core group to express itself, which is why I say you have to accept this. Because if the software doesn't allow the core group to express itself, it will invent new ways of doing so...
>
>
>
I think it would be very **nice** of you to pay a bit more attention to the [concerns of your core group](https://meta.stackoverflow.com/a/254973/839601 "example here: 'SO has experienced geometric growth since its inception, doubling in size every 18 months or so. That stopped in the fall of last year, it has been roughly stable since then with a hint of contraction. This has been brought up in meta many times in the past few months. Hopefully the site owners are paying attention...'").
|
I've never used the term *rep-whore* and I agree that it sounds pejorative and belittling. Those who answer off-topic questions just to earn a few tens of reputation points should be called *SE user* because we did it one way or another in the past. However, what do you call a user who constantly answer off-topic questions?
The linked question was posted on English Language and Usage, [What's a less offensive substitute for “rep-whores”?](https://english.stackexchange.com/questions/226736/whats-a-less-offensive-substitute-for-rep-whores) and it suggests multiple alternatives.
(In order of the number of upvotes)
>
> Rep-hound
>
>
> Rep-farmer
>
>
> Rep-junkie
>
>
> Rep-monger
>
>
> Rep-minded
>
>
> Rep-reaper
>
>
> Rep-chaser
>
>
> ...
>
>
>
|
281,787 |
Going forward, “rep-whore” (and its derivatives) will be treated like any other term that’s inconsistent with the community’s “be nice” policy: it will be removed.
It’s totally okay if you’ve used it in the past.
================================================
Nobody’s judging the many users who’ve used it. And users will NOT start being suspended/banned/fed-to-the-Sarlaac for using it in the near future without knowing about the change. We’re all partly products of what’s “normal” in our environment, and for a long time, use of that term *was* normal, and intended as a shorthand for “users who know a behavior is harmful, but do it anyway, entirely because it generates rep.” It was used - without malice - by good-hearted users in lots of old posts. It has probably been used by employees occasionally in the past. There’s no shame or judgment implied here; it’s just time to recognize that it's not consistent with "be nice.” And its use actually undermines our ability to get the most out of needed discussions on user behavior, incentives, etc. To be clear, it *is* absolutely okay to talk about *specific behaviors* that may represent unintended consequences of the rep-based feedback loop, and to continue to question them - just don’t do it by name-calling.
The short version of the "why"
==============================
* It’s inconsistent with our “be nice" policy:
+ It’s vulgar, and may be construed as being gendered (albeit not intentionally, in my observations).
+ The term makes the problem about the *person, not the action*. (And it doesn’t help to verbify it as “rep-whoring” - that’s still only describing it as something a person-type would do, vs. a specific thing that was done.)
* Naming “user types” with pejorative terms tends to lead to over-use of those terms, and undermines actual dialogue that might help us better understand what's going wrong.
That really covers it. But we like to be as open as possible about our underlying thinking, so if you're curious, or have a lot of time to kill...
The longer version
==================
**The term clearly doesn't jibe with “being nice”:**
Here are the relevant parts of the [Be Nice policy](https://stackoverflow.com/help/be-nice):
>
> * No Name Calling - Focus on the post, not the person. That includes terms that feel personal even when they're applied to posts (like "lazy", "ignorant", or "whiny").\*
> * Rudeness and belittling language are not okay.
> * Avoid vulgar terms and anything sexually suggestive.
> * Be welcoming, be patient, and **assume good intentions** (emphasis mine)
>
>
>
Frankly, those are good enough reasons - this community has always been fairly united in our commitment to discuss problems openly, **but with strong commitment to respect and courtesy, and a focus on the content or behavior, not the person.**
So, even if this term *were* super-useful in helping us solve problems and improve the site, I think most folks here would agree that we shouldn’t be scrapping big chunks of our “be nice” policy just for the sake of expediency. But here’s the funny thing:
**Using terms like “rep-whore” tends to *undermine* our ability to break down situations and learn where the system does have real problems or unintended consequences.**
**Labeling users with names that almost no one would call themselves reduces two-sided discourse and learning.** We actually learn the most when we listen to those who *don’t* agree with us (yet, anyway - I like to think they’ll eventually come around). But when we say, “the problem is rep-whores,” to explain someone answering questions that we think should be closed instead, it reduces the number of folks motivated to say, “Oh, hey - I guess I’m one of those ‘rep-whores’. Is that what you call someone who just answers questions when they can, but doesn’t keep track of what’s on- and off-topic?” Note that I’m *not* saying that’s usually the actual case, but the problem is that we'd never know if it were. By just describing it as “rep-whoring,” we've cut off much hope of learning if another motivation might apply - we’ve *assumed* we know the motivation, and given it a nasty name, so any users involved who might wish to actually explain their motivations don’t even think we're talking about (non-whore-esque) folks like them.
**There’s a funny thing about *naming* something.** Once a thing has a name, you tend to start seeing it everywhere. That's part of the positive power of language: by giving a complex thing a shorthand term, it’s easier to identify it quickly, just by matching a couple of key variables. Heuristics like that are what let us function at higher efficiency. But they come with costs: false positives and loss of nuance. The entire *point* of these types of categorization is to allow faster pattern matching, with fewer inputs and less analysis. But that means that things with *some* shared attributes, or even just similar ones, can get (wrongly) lumped in buckets pretty quickly.
Which is how we find ourselves making assumptions about others. I may think:
>
> “Someone who answers a question that we’d normally close is obviously only motivated by rep, and clearly doesn't care that it’s hurting the site.”
>
>
>
Maybe. Maybe they *are* only motivated by rep. Or maybe it’s something else: Maybe they don’t know (or care) what’s on-topic; they choose to answer questions where they can help, but don’t want to have to also serve as a filter for what’s currently allowed.
Personally, *I* happen to think that’s okay. I’m actually good with the idea that helping here doesn't require, “helping in all the ways, including ones you don’t enjoy.” Now, you may not agree, and think it’s a problem. That's good! And if that were the situation, *that’s* what we need to be talking about. But by ascribing the problems to “rep-whores,” I’ve eliminated that fact-finding step, and potentially even *prevented* us from getting to some of the real issues that we might want to discuss, all to save a few minutes by slapping a convenient name on the situation.
**Caring about getting lots of rep is a little like caring about getting lots of money - it seems to be a problem that is only diagnosed as afflicting *other people.*** Posts about rep-whores are pretty consistently written by folks who say they’re *not* at all motivated by rep - that *they* would only do things for more altruistic reasons. Which… I happen to believe is true. I think almost all of them *are actually motivated by the desire to help, or to contribute to a useful resource.* So here’s the question: given that we know *we’d* only choose behaviors if we thought they were good for the site, why are we so quick to assume that rep is the *primary* driver of others’ behavior, regardless of the harm it might cause? I think part of it may be what's apparently known as the [actor–observer asymmetry/bias](https://en.wikipedia.org/wiki/Actor%E2%80%93observer_asymmetry). The gist is this - when *you* swerve your car without warning, you know you’re a responsible driver coping as best you can with challenging circumstances - you saw something in the road, or your kid finally succeeded in pitching a gummy bear into your ear. But when you see someone *else* swerve their car, you assume they’re a bad driver. Or texting. Or drunk.
**In conclusion…**
Let’s keep talking about rep, and unintended consequences. To be honest, we *want* people to care about it, but not *too* much, and not as an end unto itself. Rep *is* supposed to be motivating, largely as a feedback loop. It's designed to confirm that you’re achieving what you all really came here to do: share your experiences in way that generates a resource that will actually make a difference. That little green "+10" is a proxy for someone saying, "that was useful". Your effort here mattered. So it’s okay to like getting it. I do. But it’s also okay - in fact it’s important - to call out places where it may be over-incentivizing things we don’t want. Let's just do it without using terms that’ll make Julia Roberts sad:
[](https://i.stack.imgur.com/rsiXM.jpg)
**For now, don’t worry about purging old uses of the term.**
This isn’t intended to create a lot of new work, particularly for mods, so we don’t want folks searching through tons of old posts and throwing up hundreds of flags. But if you run into new uses of the term, treat em like any other thing inconsistent with “be nice” (edit ‘em out when possible, etc.)
|
2016/07/29
|
[
"https://meta.stackexchange.com/questions/281787",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147336/"
] |
This feels a bit like [bowdlerisation](https://en.wikipedia.org/wiki/Thomas_Bowdler). I've *personally* avoided it and favour the term 'Power Gamer' or 'Bounty Hunter' (drawing from my mispent youth as a pen and paper gamer).
To me the 'be nice' policy isn't about language use. It's about ensuring that as many of my users (as a mod) feel as comfortable as possible, and I've almost never seen the term used as such.
I've never seen anyone actually *use* the term 'repwhore' in anger. It's used in terms of 'repwhorage' in some situations. (Interestingly, the term's been only used 6 times on Root Access. Mostly by me, referring to me. I encourage others to try this on, and it's been used 4 times on meta SU -- this isn't exactly common.) It might be different on other sites.
I feel 'be nice' is not about the *words*; it's about the *actions* and *overall intent*. If someone on a site I'm seeing went "hey, I'm not comfortable with someone calling me a repwhore" I'd obviously encourage the person who used that term to be more *precise* over what issues they have are. If someone called themselves a repwhore, or referred to an answer as repwhorage, it's a very different thing,
So, I think the solution here might not be to worry about the *term*. If it needs to be gone, encouraging *precision* and *focusing on the actions* is good moderation.
So as a mod, it feels like it's an attempt to solve a non existent problem. We can simply deal with people not being nice for its own sake without declaring war on a phrase.
|
I've never used the term *rep-whore* and I agree that it sounds pejorative and belittling. Those who answer off-topic questions just to earn a few tens of reputation points should be called *SE user* because we did it one way or another in the past. However, what do you call a user who constantly answer off-topic questions?
The linked question was posted on English Language and Usage, [What's a less offensive substitute for “rep-whores”?](https://english.stackexchange.com/questions/226736/whats-a-less-offensive-substitute-for-rep-whores) and it suggests multiple alternatives.
(In order of the number of upvotes)
>
> Rep-hound
>
>
> Rep-farmer
>
>
> Rep-junkie
>
>
> Rep-monger
>
>
> Rep-minded
>
>
> Rep-reaper
>
>
> Rep-chaser
>
>
> ...
>
>
>
|
281,787 |
Going forward, “rep-whore” (and its derivatives) will be treated like any other term that’s inconsistent with the community’s “be nice” policy: it will be removed.
It’s totally okay if you’ve used it in the past.
================================================
Nobody’s judging the many users who’ve used it. And users will NOT start being suspended/banned/fed-to-the-Sarlaac for using it in the near future without knowing about the change. We’re all partly products of what’s “normal” in our environment, and for a long time, use of that term *was* normal, and intended as a shorthand for “users who know a behavior is harmful, but do it anyway, entirely because it generates rep.” It was used - without malice - by good-hearted users in lots of old posts. It has probably been used by employees occasionally in the past. There’s no shame or judgment implied here; it’s just time to recognize that it's not consistent with "be nice.” And its use actually undermines our ability to get the most out of needed discussions on user behavior, incentives, etc. To be clear, it *is* absolutely okay to talk about *specific behaviors* that may represent unintended consequences of the rep-based feedback loop, and to continue to question them - just don’t do it by name-calling.
The short version of the "why"
==============================
* It’s inconsistent with our “be nice" policy:
+ It’s vulgar, and may be construed as being gendered (albeit not intentionally, in my observations).
+ The term makes the problem about the *person, not the action*. (And it doesn’t help to verbify it as “rep-whoring” - that’s still only describing it as something a person-type would do, vs. a specific thing that was done.)
* Naming “user types” with pejorative terms tends to lead to over-use of those terms, and undermines actual dialogue that might help us better understand what's going wrong.
That really covers it. But we like to be as open as possible about our underlying thinking, so if you're curious, or have a lot of time to kill...
The longer version
==================
**The term clearly doesn't jibe with “being nice”:**
Here are the relevant parts of the [Be Nice policy](https://stackoverflow.com/help/be-nice):
>
> * No Name Calling - Focus on the post, not the person. That includes terms that feel personal even when they're applied to posts (like "lazy", "ignorant", or "whiny").\*
> * Rudeness and belittling language are not okay.
> * Avoid vulgar terms and anything sexually suggestive.
> * Be welcoming, be patient, and **assume good intentions** (emphasis mine)
>
>
>
Frankly, those are good enough reasons - this community has always been fairly united in our commitment to discuss problems openly, **but with strong commitment to respect and courtesy, and a focus on the content or behavior, not the person.**
So, even if this term *were* super-useful in helping us solve problems and improve the site, I think most folks here would agree that we shouldn’t be scrapping big chunks of our “be nice” policy just for the sake of expediency. But here’s the funny thing:
**Using terms like “rep-whore” tends to *undermine* our ability to break down situations and learn where the system does have real problems or unintended consequences.**
**Labeling users with names that almost no one would call themselves reduces two-sided discourse and learning.** We actually learn the most when we listen to those who *don’t* agree with us (yet, anyway - I like to think they’ll eventually come around). But when we say, “the problem is rep-whores,” to explain someone answering questions that we think should be closed instead, it reduces the number of folks motivated to say, “Oh, hey - I guess I’m one of those ‘rep-whores’. Is that what you call someone who just answers questions when they can, but doesn’t keep track of what’s on- and off-topic?” Note that I’m *not* saying that’s usually the actual case, but the problem is that we'd never know if it were. By just describing it as “rep-whoring,” we've cut off much hope of learning if another motivation might apply - we’ve *assumed* we know the motivation, and given it a nasty name, so any users involved who might wish to actually explain their motivations don’t even think we're talking about (non-whore-esque) folks like them.
**There’s a funny thing about *naming* something.** Once a thing has a name, you tend to start seeing it everywhere. That's part of the positive power of language: by giving a complex thing a shorthand term, it’s easier to identify it quickly, just by matching a couple of key variables. Heuristics like that are what let us function at higher efficiency. But they come with costs: false positives and loss of nuance. The entire *point* of these types of categorization is to allow faster pattern matching, with fewer inputs and less analysis. But that means that things with *some* shared attributes, or even just similar ones, can get (wrongly) lumped in buckets pretty quickly.
Which is how we find ourselves making assumptions about others. I may think:
>
> “Someone who answers a question that we’d normally close is obviously only motivated by rep, and clearly doesn't care that it’s hurting the site.”
>
>
>
Maybe. Maybe they *are* only motivated by rep. Or maybe it’s something else: Maybe they don’t know (or care) what’s on-topic; they choose to answer questions where they can help, but don’t want to have to also serve as a filter for what’s currently allowed.
Personally, *I* happen to think that’s okay. I’m actually good with the idea that helping here doesn't require, “helping in all the ways, including ones you don’t enjoy.” Now, you may not agree, and think it’s a problem. That's good! And if that were the situation, *that’s* what we need to be talking about. But by ascribing the problems to “rep-whores,” I’ve eliminated that fact-finding step, and potentially even *prevented* us from getting to some of the real issues that we might want to discuss, all to save a few minutes by slapping a convenient name on the situation.
**Caring about getting lots of rep is a little like caring about getting lots of money - it seems to be a problem that is only diagnosed as afflicting *other people.*** Posts about rep-whores are pretty consistently written by folks who say they’re *not* at all motivated by rep - that *they* would only do things for more altruistic reasons. Which… I happen to believe is true. I think almost all of them *are actually motivated by the desire to help, or to contribute to a useful resource.* So here’s the question: given that we know *we’d* only choose behaviors if we thought they were good for the site, why are we so quick to assume that rep is the *primary* driver of others’ behavior, regardless of the harm it might cause? I think part of it may be what's apparently known as the [actor–observer asymmetry/bias](https://en.wikipedia.org/wiki/Actor%E2%80%93observer_asymmetry). The gist is this - when *you* swerve your car without warning, you know you’re a responsible driver coping as best you can with challenging circumstances - you saw something in the road, or your kid finally succeeded in pitching a gummy bear into your ear. But when you see someone *else* swerve their car, you assume they’re a bad driver. Or texting. Or drunk.
**In conclusion…**
Let’s keep talking about rep, and unintended consequences. To be honest, we *want* people to care about it, but not *too* much, and not as an end unto itself. Rep *is* supposed to be motivating, largely as a feedback loop. It's designed to confirm that you’re achieving what you all really came here to do: share your experiences in way that generates a resource that will actually make a difference. That little green "+10" is a proxy for someone saying, "that was useful". Your effort here mattered. So it’s okay to like getting it. I do. But it’s also okay - in fact it’s important - to call out places where it may be over-incentivizing things we don’t want. Let's just do it without using terms that’ll make Julia Roberts sad:
[](https://i.stack.imgur.com/rsiXM.jpg)
**For now, don’t worry about purging old uses of the term.**
This isn’t intended to create a lot of new work, particularly for mods, so we don’t want folks searching through tons of old posts and throwing up hundreds of flags. But if you run into new uses of the term, treat em like any other thing inconsistent with “be nice” (edit ‘em out when possible, etc.)
|
2016/07/29
|
[
"https://meta.stackexchange.com/questions/281787",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147336/"
] |
TL;DR:
------
Please don't just try to cure the symptoms when curing the cancer is this simple.
Retract reputation gained from questions that are closed (or that were closed within a certain time frame, starting with the creation of the question), and you'll most likely fix this whole rep-system-abuse that's been going on for **way too long.**
---
When I first read the title I was feeling happy. I felt excited. Simply because I thought to myself "Hey, they're changing something! Maybe it'll put an end to all the rep-vampires!".. But no. All you're doing is banning a term that has been used for ages, because it's pejorative.
Congrats.
---------
**Yes**, this term is pejorative. **And yes**, it is negative. **And yes**, it - just going by the wording - does target the person instead of the action. **And yes**, it is highly unprofessional. **And yes**, that is a problem. But it's not **the problem!**
*Note: I highly support banning this term, I just don't think that it'll change anything on its own, except for frustrating people even more.*
Why do terms like this exist? Why are users calling other users out for *"rep-whoring"*, *"rep-chasing"* and other terms? Because it's an **actual problem that has to be dealt with.** So instead of just straight-up banning the term what you could've done instead is taking care of the problem.
How?
----
Retract reputation gained from questions closed for specific reasons. It's that simple. It would end the [FGITW-problem](https://meta.stackexchange.com/tags/fastest-gun/info "what's this"), it'd prevent the usage of terms like "rep-whore" (simply because the action that "rep-whore" describes is no longer existent), and it shouldn't be that hard to implement, whereas solely enforcing a term-ban would do two things:
1. It'd certainly cost you a part of your user base. I don't think I'll have to explain why.
2. It'd require a lot of resources. I burn through a lot of flags everyday, I'm present in the SOCVR-room & I do a lot to keep this site clean from trash, spam and the like, but I don't want to hunt down a certain term, and, taking into account how long this term has been used, it'd be a lot of usages to hunt down.
Why is this such a big problem?
-------------------------------
Because it defies the purpose of this network. Stack Exchange is supposed to be a Q&A-network, right? The ultimate goal is to have a collection of every possible question, alongside with the correct answer. In order to have a collection of that size you'll have to filter out the garbage, and that's what a lot of people are doing by using the tools given to them, flags, close votes and hammers.
Reputation on the other hand is the currency of this network. It depicts - to a certain extent - how much "trust" you've gained, and how much effort you've put into this project. However, thanks to people answering questions FGITW-style, this currency loses its meaning.
(*Side-note: I am not talking about new users. I try to explain them the system that Stack Exchange is based on, and move on. I'm talking about the high-rep users that do this knowingly, as in answering known duplicates, off-topic questions, and so on.*)
In my opinion these people are actively damaging the Stack Exchange network.
The reputation system is getting abused, and yet they can continue what they're doing. All I can do in this case is downvote it, but - in most cases - the OP has already upvoted & accepted that answer, so my downvote does what? Lower his rep gain from 25 (Upvote + Accept) to 23? To be honest, I can't be bothered.
|
* **People are supposed to be seeking rep.**
* **If people seeking rep are doing the "wrong things", you are giving rep for the "wrong things".**
* **The main "wrong thing" is duplicates which are *answered* instead of *closed as duplicates*.**
Flagging a duplicate gets no rep.
Answering "how to make teh join" or "fix this pivot for me" will get you 50 points even though it is an exact duplicate.
That's the problem you need to fix:
* Add 10 Rep for everyone voting to close as duplicate (when subsequently closed).
* Negative rep for answering when the question is later flagged as a duplicate
Then people will stop doing that. Not until.
**The incentive structure is the reification of the will of the organisation**
|
281,787 |
Going forward, “rep-whore” (and its derivatives) will be treated like any other term that’s inconsistent with the community’s “be nice” policy: it will be removed.
It’s totally okay if you’ve used it in the past.
================================================
Nobody’s judging the many users who’ve used it. And users will NOT start being suspended/banned/fed-to-the-Sarlaac for using it in the near future without knowing about the change. We’re all partly products of what’s “normal” in our environment, and for a long time, use of that term *was* normal, and intended as a shorthand for “users who know a behavior is harmful, but do it anyway, entirely because it generates rep.” It was used - without malice - by good-hearted users in lots of old posts. It has probably been used by employees occasionally in the past. There’s no shame or judgment implied here; it’s just time to recognize that it's not consistent with "be nice.” And its use actually undermines our ability to get the most out of needed discussions on user behavior, incentives, etc. To be clear, it *is* absolutely okay to talk about *specific behaviors* that may represent unintended consequences of the rep-based feedback loop, and to continue to question them - just don’t do it by name-calling.
The short version of the "why"
==============================
* It’s inconsistent with our “be nice" policy:
+ It’s vulgar, and may be construed as being gendered (albeit not intentionally, in my observations).
+ The term makes the problem about the *person, not the action*. (And it doesn’t help to verbify it as “rep-whoring” - that’s still only describing it as something a person-type would do, vs. a specific thing that was done.)
* Naming “user types” with pejorative terms tends to lead to over-use of those terms, and undermines actual dialogue that might help us better understand what's going wrong.
That really covers it. But we like to be as open as possible about our underlying thinking, so if you're curious, or have a lot of time to kill...
The longer version
==================
**The term clearly doesn't jibe with “being nice”:**
Here are the relevant parts of the [Be Nice policy](https://stackoverflow.com/help/be-nice):
>
> * No Name Calling - Focus on the post, not the person. That includes terms that feel personal even when they're applied to posts (like "lazy", "ignorant", or "whiny").\*
> * Rudeness and belittling language are not okay.
> * Avoid vulgar terms and anything sexually suggestive.
> * Be welcoming, be patient, and **assume good intentions** (emphasis mine)
>
>
>
Frankly, those are good enough reasons - this community has always been fairly united in our commitment to discuss problems openly, **but with strong commitment to respect and courtesy, and a focus on the content or behavior, not the person.**
So, even if this term *were* super-useful in helping us solve problems and improve the site, I think most folks here would agree that we shouldn’t be scrapping big chunks of our “be nice” policy just for the sake of expediency. But here’s the funny thing:
**Using terms like “rep-whore” tends to *undermine* our ability to break down situations and learn where the system does have real problems or unintended consequences.**
**Labeling users with names that almost no one would call themselves reduces two-sided discourse and learning.** We actually learn the most when we listen to those who *don’t* agree with us (yet, anyway - I like to think they’ll eventually come around). But when we say, “the problem is rep-whores,” to explain someone answering questions that we think should be closed instead, it reduces the number of folks motivated to say, “Oh, hey - I guess I’m one of those ‘rep-whores’. Is that what you call someone who just answers questions when they can, but doesn’t keep track of what’s on- and off-topic?” Note that I’m *not* saying that’s usually the actual case, but the problem is that we'd never know if it were. By just describing it as “rep-whoring,” we've cut off much hope of learning if another motivation might apply - we’ve *assumed* we know the motivation, and given it a nasty name, so any users involved who might wish to actually explain their motivations don’t even think we're talking about (non-whore-esque) folks like them.
**There’s a funny thing about *naming* something.** Once a thing has a name, you tend to start seeing it everywhere. That's part of the positive power of language: by giving a complex thing a shorthand term, it’s easier to identify it quickly, just by matching a couple of key variables. Heuristics like that are what let us function at higher efficiency. But they come with costs: false positives and loss of nuance. The entire *point* of these types of categorization is to allow faster pattern matching, with fewer inputs and less analysis. But that means that things with *some* shared attributes, or even just similar ones, can get (wrongly) lumped in buckets pretty quickly.
Which is how we find ourselves making assumptions about others. I may think:
>
> “Someone who answers a question that we’d normally close is obviously only motivated by rep, and clearly doesn't care that it’s hurting the site.”
>
>
>
Maybe. Maybe they *are* only motivated by rep. Or maybe it’s something else: Maybe they don’t know (or care) what’s on-topic; they choose to answer questions where they can help, but don’t want to have to also serve as a filter for what’s currently allowed.
Personally, *I* happen to think that’s okay. I’m actually good with the idea that helping here doesn't require, “helping in all the ways, including ones you don’t enjoy.” Now, you may not agree, and think it’s a problem. That's good! And if that were the situation, *that’s* what we need to be talking about. But by ascribing the problems to “rep-whores,” I’ve eliminated that fact-finding step, and potentially even *prevented* us from getting to some of the real issues that we might want to discuss, all to save a few minutes by slapping a convenient name on the situation.
**Caring about getting lots of rep is a little like caring about getting lots of money - it seems to be a problem that is only diagnosed as afflicting *other people.*** Posts about rep-whores are pretty consistently written by folks who say they’re *not* at all motivated by rep - that *they* would only do things for more altruistic reasons. Which… I happen to believe is true. I think almost all of them *are actually motivated by the desire to help, or to contribute to a useful resource.* So here’s the question: given that we know *we’d* only choose behaviors if we thought they were good for the site, why are we so quick to assume that rep is the *primary* driver of others’ behavior, regardless of the harm it might cause? I think part of it may be what's apparently known as the [actor–observer asymmetry/bias](https://en.wikipedia.org/wiki/Actor%E2%80%93observer_asymmetry). The gist is this - when *you* swerve your car without warning, you know you’re a responsible driver coping as best you can with challenging circumstances - you saw something in the road, or your kid finally succeeded in pitching a gummy bear into your ear. But when you see someone *else* swerve their car, you assume they’re a bad driver. Or texting. Or drunk.
**In conclusion…**
Let’s keep talking about rep, and unintended consequences. To be honest, we *want* people to care about it, but not *too* much, and not as an end unto itself. Rep *is* supposed to be motivating, largely as a feedback loop. It's designed to confirm that you’re achieving what you all really came here to do: share your experiences in way that generates a resource that will actually make a difference. That little green "+10" is a proxy for someone saying, "that was useful". Your effort here mattered. So it’s okay to like getting it. I do. But it’s also okay - in fact it’s important - to call out places where it may be over-incentivizing things we don’t want. Let's just do it without using terms that’ll make Julia Roberts sad:
[](https://i.stack.imgur.com/rsiXM.jpg)
**For now, don’t worry about purging old uses of the term.**
This isn’t intended to create a lot of new work, particularly for mods, so we don’t want folks searching through tons of old posts and throwing up hundreds of flags. But if you run into new uses of the term, treat em like any other thing inconsistent with “be nice” (edit ‘em out when possible, etc.)
|
2016/07/29
|
[
"https://meta.stackexchange.com/questions/281787",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147336/"
] |
>
> It's time...
>
>
>
...it's time to keep the [promise](https://meta.stackoverflow.com/a/320971/839601) made three months ago:
>
> we'll start looking at [increasing the number of close votes based on rep](https://meta.stackexchange.com/questions/266500/proposal-to-make-close-votes-scale-with-rep)
>
>
>
You seem to be blaming users for unnecessary rudeness and trying to cut their ways to express it. That may be true and right, but if you think of it the [root cause](https://softwareengineering.stackexchange.com/a/154741/31260) for their attitude may lie elsewhere.
For example, if many inappropriate questions aren't closed quickly enough and this makes a wide open door for answers to leak into them, it may cause negative feelings for those who care about content quality. If this is the case, banning particular negative terms won't help. The negative feelings will stay; people will simply invent other terms to express them, and things won't really get nicer.
I think it's time to look closer at these things in the historical perspective.
For example, how come that after years of plugging users' mouths and twisting their arms with *summers of love* and *hunting the snark*, the second-highest-voted question at MSO is [Why is Stack Overflow so **negative** of late?](https://meta.stackoverflow.com/q/251758/839601) Makes one wonder if this way works, doesn't it?
---
You see, negative feelings (and their respective terms) may simply indicate that a community lacks power and tools to protect itself from inappropriate content.
I heard that the author who best explained these matters is a member of Stack Exchange's board of directors -- ([Clay Shirky](http://www.shirky.com/writings/group_enemy.html "who wrote 'A Group Is Its Own Worst Enemy'")) -- maybe it's time to have a word with him.
>
> thing you have to accept: Members are different than users. A pattern will arise in which there is some group of users that cares more than average about the integrity and success of the group as a whole. And that becomes your core group, Art Kleiner's phrase for "the group within the group that matters most."
>
>
> The core group... was undifferentiated from the group of random users that came in. They were separate in their own minds, because they knew what they wanted to do, but they couldn't defend themselves against the other users. But in all successful online communities that I've looked at, a core group arises that cares about and gardens effectively. Gardens the environment, to keep it growing, to keep it healthy.
>
>
> Now, the software does not always allow the core group to express itself, which is why I say you have to accept this. Because if the software doesn't allow the core group to express itself, it will invent new ways of doing so...
>
>
>
I think it would be very **nice** of you to pay a bit more attention to the [concerns of your core group](https://meta.stackoverflow.com/a/254973/839601 "example here: 'SO has experienced geometric growth since its inception, doubling in size every 18 months or so. That stopped in the fall of last year, it has been roughly stable since then with a hint of contraction. This has been brought up in meta many times in the past few months. Hopefully the site owners are paying attention...'").
|
For what it's worth, if anyone wishes to call me a whore - either for rep or otherwise - I find this acceptable. I cannot guarantee a third party won't moderate our communication regardless, but i'm just going on-record as saying I do not feel people who say this to me are breaking any sort of social contract. I will not accept **intimidation**, **name-calling**, or **nastiness**; but if i'm being **whore-like**, **whorish**, or just generally **whorey**, then please do call me out on it. It's much better that I stop than I continue in ignorance.
I'm not going to give a short and long version of why this is the socially responsible thing to do, instead i'll make 2 points:
1. I have seen the word 'whore' many times on the internet, and 99.999% of the time it was used for it's more modern definition - that of someone doing something unpleasant for some unrelated gain. Yes it might have started with sex for money, but these days it could be posts for rep, moderation for power, click-bait for ad revenue, etc. To stop using this word's new definition because that new definition has become more popular than the original definition will only, in my opinion, preserve the nastiness of the original definition and in the process we will lose a useful adjective.
2. This one is a little harder to explain, but essentially, SE in its current form is really rather good at moderating intimidation, name-calling and nastiness. That is because the whole context of the interaction is right there for all to see, mods can be summoned near-instantaneously to pass judgement, and most of the time they do so very well. This is important, because when it comes to nastiness context is everything. To ban a word regardless of it's context is anti-logical, anti-social, and ultimately anti-progressive. People *must* have the freedom to offend others, and to ultimately be banned for it. SE is fundamentally a democratic website, and for some words to be banned due to a technicality before they can go through the democratic process of *being read* would be at odds with the site's culture.
|
281,787 |
Going forward, “rep-whore” (and its derivatives) will be treated like any other term that’s inconsistent with the community’s “be nice” policy: it will be removed.
It’s totally okay if you’ve used it in the past.
================================================
Nobody’s judging the many users who’ve used it. And users will NOT start being suspended/banned/fed-to-the-Sarlaac for using it in the near future without knowing about the change. We’re all partly products of what’s “normal” in our environment, and for a long time, use of that term *was* normal, and intended as a shorthand for “users who know a behavior is harmful, but do it anyway, entirely because it generates rep.” It was used - without malice - by good-hearted users in lots of old posts. It has probably been used by employees occasionally in the past. There’s no shame or judgment implied here; it’s just time to recognize that it's not consistent with "be nice.” And its use actually undermines our ability to get the most out of needed discussions on user behavior, incentives, etc. To be clear, it *is* absolutely okay to talk about *specific behaviors* that may represent unintended consequences of the rep-based feedback loop, and to continue to question them - just don’t do it by name-calling.
The short version of the "why"
==============================
* It’s inconsistent with our “be nice" policy:
+ It’s vulgar, and may be construed as being gendered (albeit not intentionally, in my observations).
+ The term makes the problem about the *person, not the action*. (And it doesn’t help to verbify it as “rep-whoring” - that’s still only describing it as something a person-type would do, vs. a specific thing that was done.)
* Naming “user types” with pejorative terms tends to lead to over-use of those terms, and undermines actual dialogue that might help us better understand what's going wrong.
That really covers it. But we like to be as open as possible about our underlying thinking, so if you're curious, or have a lot of time to kill...
The longer version
==================
**The term clearly doesn't jibe with “being nice”:**
Here are the relevant parts of the [Be Nice policy](https://stackoverflow.com/help/be-nice):
>
> * No Name Calling - Focus on the post, not the person. That includes terms that feel personal even when they're applied to posts (like "lazy", "ignorant", or "whiny").\*
> * Rudeness and belittling language are not okay.
> * Avoid vulgar terms and anything sexually suggestive.
> * Be welcoming, be patient, and **assume good intentions** (emphasis mine)
>
>
>
Frankly, those are good enough reasons - this community has always been fairly united in our commitment to discuss problems openly, **but with strong commitment to respect and courtesy, and a focus on the content or behavior, not the person.**
So, even if this term *were* super-useful in helping us solve problems and improve the site, I think most folks here would agree that we shouldn’t be scrapping big chunks of our “be nice” policy just for the sake of expediency. But here’s the funny thing:
**Using terms like “rep-whore” tends to *undermine* our ability to break down situations and learn where the system does have real problems or unintended consequences.**
**Labeling users with names that almost no one would call themselves reduces two-sided discourse and learning.** We actually learn the most when we listen to those who *don’t* agree with us (yet, anyway - I like to think they’ll eventually come around). But when we say, “the problem is rep-whores,” to explain someone answering questions that we think should be closed instead, it reduces the number of folks motivated to say, “Oh, hey - I guess I’m one of those ‘rep-whores’. Is that what you call someone who just answers questions when they can, but doesn’t keep track of what’s on- and off-topic?” Note that I’m *not* saying that’s usually the actual case, but the problem is that we'd never know if it were. By just describing it as “rep-whoring,” we've cut off much hope of learning if another motivation might apply - we’ve *assumed* we know the motivation, and given it a nasty name, so any users involved who might wish to actually explain their motivations don’t even think we're talking about (non-whore-esque) folks like them.
**There’s a funny thing about *naming* something.** Once a thing has a name, you tend to start seeing it everywhere. That's part of the positive power of language: by giving a complex thing a shorthand term, it’s easier to identify it quickly, just by matching a couple of key variables. Heuristics like that are what let us function at higher efficiency. But they come with costs: false positives and loss of nuance. The entire *point* of these types of categorization is to allow faster pattern matching, with fewer inputs and less analysis. But that means that things with *some* shared attributes, or even just similar ones, can get (wrongly) lumped in buckets pretty quickly.
Which is how we find ourselves making assumptions about others. I may think:
>
> “Someone who answers a question that we’d normally close is obviously only motivated by rep, and clearly doesn't care that it’s hurting the site.”
>
>
>
Maybe. Maybe they *are* only motivated by rep. Or maybe it’s something else: Maybe they don’t know (or care) what’s on-topic; they choose to answer questions where they can help, but don’t want to have to also serve as a filter for what’s currently allowed.
Personally, *I* happen to think that’s okay. I’m actually good with the idea that helping here doesn't require, “helping in all the ways, including ones you don’t enjoy.” Now, you may not agree, and think it’s a problem. That's good! And if that were the situation, *that’s* what we need to be talking about. But by ascribing the problems to “rep-whores,” I’ve eliminated that fact-finding step, and potentially even *prevented* us from getting to some of the real issues that we might want to discuss, all to save a few minutes by slapping a convenient name on the situation.
**Caring about getting lots of rep is a little like caring about getting lots of money - it seems to be a problem that is only diagnosed as afflicting *other people.*** Posts about rep-whores are pretty consistently written by folks who say they’re *not* at all motivated by rep - that *they* would only do things for more altruistic reasons. Which… I happen to believe is true. I think almost all of them *are actually motivated by the desire to help, or to contribute to a useful resource.* So here’s the question: given that we know *we’d* only choose behaviors if we thought they were good for the site, why are we so quick to assume that rep is the *primary* driver of others’ behavior, regardless of the harm it might cause? I think part of it may be what's apparently known as the [actor–observer asymmetry/bias](https://en.wikipedia.org/wiki/Actor%E2%80%93observer_asymmetry). The gist is this - when *you* swerve your car without warning, you know you’re a responsible driver coping as best you can with challenging circumstances - you saw something in the road, or your kid finally succeeded in pitching a gummy bear into your ear. But when you see someone *else* swerve their car, you assume they’re a bad driver. Or texting. Or drunk.
**In conclusion…**
Let’s keep talking about rep, and unintended consequences. To be honest, we *want* people to care about it, but not *too* much, and not as an end unto itself. Rep *is* supposed to be motivating, largely as a feedback loop. It's designed to confirm that you’re achieving what you all really came here to do: share your experiences in way that generates a resource that will actually make a difference. That little green "+10" is a proxy for someone saying, "that was useful". Your effort here mattered. So it’s okay to like getting it. I do. But it’s also okay - in fact it’s important - to call out places where it may be over-incentivizing things we don’t want. Let's just do it without using terms that’ll make Julia Roberts sad:
[](https://i.stack.imgur.com/rsiXM.jpg)
**For now, don’t worry about purging old uses of the term.**
This isn’t intended to create a lot of new work, particularly for mods, so we don’t want folks searching through tons of old posts and throwing up hundreds of flags. But if you run into new uses of the term, treat em like any other thing inconsistent with “be nice” (edit ‘em out when possible, etc.)
|
2016/07/29
|
[
"https://meta.stackexchange.com/questions/281787",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147336/"
] |
This feels a bit like [bowdlerisation](https://en.wikipedia.org/wiki/Thomas_Bowdler). I've *personally* avoided it and favour the term 'Power Gamer' or 'Bounty Hunter' (drawing from my mispent youth as a pen and paper gamer).
To me the 'be nice' policy isn't about language use. It's about ensuring that as many of my users (as a mod) feel as comfortable as possible, and I've almost never seen the term used as such.
I've never seen anyone actually *use* the term 'repwhore' in anger. It's used in terms of 'repwhorage' in some situations. (Interestingly, the term's been only used 6 times on Root Access. Mostly by me, referring to me. I encourage others to try this on, and it's been used 4 times on meta SU -- this isn't exactly common.) It might be different on other sites.
I feel 'be nice' is not about the *words*; it's about the *actions* and *overall intent*. If someone on a site I'm seeing went "hey, I'm not comfortable with someone calling me a repwhore" I'd obviously encourage the person who used that term to be more *precise* over what issues they have are. If someone called themselves a repwhore, or referred to an answer as repwhorage, it's a very different thing,
So, I think the solution here might not be to worry about the *term*. If it needs to be gone, encouraging *precision* and *focusing on the actions* is good moderation.
So as a mod, it feels like it's an attempt to solve a non existent problem. We can simply deal with people not being nice for its own sake without declaring war on a phrase.
|
For what it's worth, if anyone wishes to call me a whore - either for rep or otherwise - I find this acceptable. I cannot guarantee a third party won't moderate our communication regardless, but i'm just going on-record as saying I do not feel people who say this to me are breaking any sort of social contract. I will not accept **intimidation**, **name-calling**, or **nastiness**; but if i'm being **whore-like**, **whorish**, or just generally **whorey**, then please do call me out on it. It's much better that I stop than I continue in ignorance.
I'm not going to give a short and long version of why this is the socially responsible thing to do, instead i'll make 2 points:
1. I have seen the word 'whore' many times on the internet, and 99.999% of the time it was used for it's more modern definition - that of someone doing something unpleasant for some unrelated gain. Yes it might have started with sex for money, but these days it could be posts for rep, moderation for power, click-bait for ad revenue, etc. To stop using this word's new definition because that new definition has become more popular than the original definition will only, in my opinion, preserve the nastiness of the original definition and in the process we will lose a useful adjective.
2. This one is a little harder to explain, but essentially, SE in its current form is really rather good at moderating intimidation, name-calling and nastiness. That is because the whole context of the interaction is right there for all to see, mods can be summoned near-instantaneously to pass judgement, and most of the time they do so very well. This is important, because when it comes to nastiness context is everything. To ban a word regardless of it's context is anti-logical, anti-social, and ultimately anti-progressive. People *must* have the freedom to offend others, and to ultimately be banned for it. SE is fundamentally a democratic website, and for some words to be banned due to a technicality before they can go through the democratic process of *being read* would be at odds with the site's culture.
|
281,787 |
Going forward, “rep-whore” (and its derivatives) will be treated like any other term that’s inconsistent with the community’s “be nice” policy: it will be removed.
It’s totally okay if you’ve used it in the past.
================================================
Nobody’s judging the many users who’ve used it. And users will NOT start being suspended/banned/fed-to-the-Sarlaac for using it in the near future without knowing about the change. We’re all partly products of what’s “normal” in our environment, and for a long time, use of that term *was* normal, and intended as a shorthand for “users who know a behavior is harmful, but do it anyway, entirely because it generates rep.” It was used - without malice - by good-hearted users in lots of old posts. It has probably been used by employees occasionally in the past. There’s no shame or judgment implied here; it’s just time to recognize that it's not consistent with "be nice.” And its use actually undermines our ability to get the most out of needed discussions on user behavior, incentives, etc. To be clear, it *is* absolutely okay to talk about *specific behaviors* that may represent unintended consequences of the rep-based feedback loop, and to continue to question them - just don’t do it by name-calling.
The short version of the "why"
==============================
* It’s inconsistent with our “be nice" policy:
+ It’s vulgar, and may be construed as being gendered (albeit not intentionally, in my observations).
+ The term makes the problem about the *person, not the action*. (And it doesn’t help to verbify it as “rep-whoring” - that’s still only describing it as something a person-type would do, vs. a specific thing that was done.)
* Naming “user types” with pejorative terms tends to lead to over-use of those terms, and undermines actual dialogue that might help us better understand what's going wrong.
That really covers it. But we like to be as open as possible about our underlying thinking, so if you're curious, or have a lot of time to kill...
The longer version
==================
**The term clearly doesn't jibe with “being nice”:**
Here are the relevant parts of the [Be Nice policy](https://stackoverflow.com/help/be-nice):
>
> * No Name Calling - Focus on the post, not the person. That includes terms that feel personal even when they're applied to posts (like "lazy", "ignorant", or "whiny").\*
> * Rudeness and belittling language are not okay.
> * Avoid vulgar terms and anything sexually suggestive.
> * Be welcoming, be patient, and **assume good intentions** (emphasis mine)
>
>
>
Frankly, those are good enough reasons - this community has always been fairly united in our commitment to discuss problems openly, **but with strong commitment to respect and courtesy, and a focus on the content or behavior, not the person.**
So, even if this term *were* super-useful in helping us solve problems and improve the site, I think most folks here would agree that we shouldn’t be scrapping big chunks of our “be nice” policy just for the sake of expediency. But here’s the funny thing:
**Using terms like “rep-whore” tends to *undermine* our ability to break down situations and learn where the system does have real problems or unintended consequences.**
**Labeling users with names that almost no one would call themselves reduces two-sided discourse and learning.** We actually learn the most when we listen to those who *don’t* agree with us (yet, anyway - I like to think they’ll eventually come around). But when we say, “the problem is rep-whores,” to explain someone answering questions that we think should be closed instead, it reduces the number of folks motivated to say, “Oh, hey - I guess I’m one of those ‘rep-whores’. Is that what you call someone who just answers questions when they can, but doesn’t keep track of what’s on- and off-topic?” Note that I’m *not* saying that’s usually the actual case, but the problem is that we'd never know if it were. By just describing it as “rep-whoring,” we've cut off much hope of learning if another motivation might apply - we’ve *assumed* we know the motivation, and given it a nasty name, so any users involved who might wish to actually explain their motivations don’t even think we're talking about (non-whore-esque) folks like them.
**There’s a funny thing about *naming* something.** Once a thing has a name, you tend to start seeing it everywhere. That's part of the positive power of language: by giving a complex thing a shorthand term, it’s easier to identify it quickly, just by matching a couple of key variables. Heuristics like that are what let us function at higher efficiency. But they come with costs: false positives and loss of nuance. The entire *point* of these types of categorization is to allow faster pattern matching, with fewer inputs and less analysis. But that means that things with *some* shared attributes, or even just similar ones, can get (wrongly) lumped in buckets pretty quickly.
Which is how we find ourselves making assumptions about others. I may think:
>
> “Someone who answers a question that we’d normally close is obviously only motivated by rep, and clearly doesn't care that it’s hurting the site.”
>
>
>
Maybe. Maybe they *are* only motivated by rep. Or maybe it’s something else: Maybe they don’t know (or care) what’s on-topic; they choose to answer questions where they can help, but don’t want to have to also serve as a filter for what’s currently allowed.
Personally, *I* happen to think that’s okay. I’m actually good with the idea that helping here doesn't require, “helping in all the ways, including ones you don’t enjoy.” Now, you may not agree, and think it’s a problem. That's good! And if that were the situation, *that’s* what we need to be talking about. But by ascribing the problems to “rep-whores,” I’ve eliminated that fact-finding step, and potentially even *prevented* us from getting to some of the real issues that we might want to discuss, all to save a few minutes by slapping a convenient name on the situation.
**Caring about getting lots of rep is a little like caring about getting lots of money - it seems to be a problem that is only diagnosed as afflicting *other people.*** Posts about rep-whores are pretty consistently written by folks who say they’re *not* at all motivated by rep - that *they* would only do things for more altruistic reasons. Which… I happen to believe is true. I think almost all of them *are actually motivated by the desire to help, or to contribute to a useful resource.* So here’s the question: given that we know *we’d* only choose behaviors if we thought they were good for the site, why are we so quick to assume that rep is the *primary* driver of others’ behavior, regardless of the harm it might cause? I think part of it may be what's apparently known as the [actor–observer asymmetry/bias](https://en.wikipedia.org/wiki/Actor%E2%80%93observer_asymmetry). The gist is this - when *you* swerve your car without warning, you know you’re a responsible driver coping as best you can with challenging circumstances - you saw something in the road, or your kid finally succeeded in pitching a gummy bear into your ear. But when you see someone *else* swerve their car, you assume they’re a bad driver. Or texting. Or drunk.
**In conclusion…**
Let’s keep talking about rep, and unintended consequences. To be honest, we *want* people to care about it, but not *too* much, and not as an end unto itself. Rep *is* supposed to be motivating, largely as a feedback loop. It's designed to confirm that you’re achieving what you all really came here to do: share your experiences in way that generates a resource that will actually make a difference. That little green "+10" is a proxy for someone saying, "that was useful". Your effort here mattered. So it’s okay to like getting it. I do. But it’s also okay - in fact it’s important - to call out places where it may be over-incentivizing things we don’t want. Let's just do it without using terms that’ll make Julia Roberts sad:
[](https://i.stack.imgur.com/rsiXM.jpg)
**For now, don’t worry about purging old uses of the term.**
This isn’t intended to create a lot of new work, particularly for mods, so we don’t want folks searching through tons of old posts and throwing up hundreds of flags. But if you run into new uses of the term, treat em like any other thing inconsistent with “be nice” (edit ‘em out when possible, etc.)
|
2016/07/29
|
[
"https://meta.stackexchange.com/questions/281787",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147336/"
] |
TL;DR:
------
Please don't just try to cure the symptoms when curing the cancer is this simple.
Retract reputation gained from questions that are closed (or that were closed within a certain time frame, starting with the creation of the question), and you'll most likely fix this whole rep-system-abuse that's been going on for **way too long.**
---
When I first read the title I was feeling happy. I felt excited. Simply because I thought to myself "Hey, they're changing something! Maybe it'll put an end to all the rep-vampires!".. But no. All you're doing is banning a term that has been used for ages, because it's pejorative.
Congrats.
---------
**Yes**, this term is pejorative. **And yes**, it is negative. **And yes**, it - just going by the wording - does target the person instead of the action. **And yes**, it is highly unprofessional. **And yes**, that is a problem. But it's not **the problem!**
*Note: I highly support banning this term, I just don't think that it'll change anything on its own, except for frustrating people even more.*
Why do terms like this exist? Why are users calling other users out for *"rep-whoring"*, *"rep-chasing"* and other terms? Because it's an **actual problem that has to be dealt with.** So instead of just straight-up banning the term what you could've done instead is taking care of the problem.
How?
----
Retract reputation gained from questions closed for specific reasons. It's that simple. It would end the [FGITW-problem](https://meta.stackexchange.com/tags/fastest-gun/info "what's this"), it'd prevent the usage of terms like "rep-whore" (simply because the action that "rep-whore" describes is no longer existent), and it shouldn't be that hard to implement, whereas solely enforcing a term-ban would do two things:
1. It'd certainly cost you a part of your user base. I don't think I'll have to explain why.
2. It'd require a lot of resources. I burn through a lot of flags everyday, I'm present in the SOCVR-room & I do a lot to keep this site clean from trash, spam and the like, but I don't want to hunt down a certain term, and, taking into account how long this term has been used, it'd be a lot of usages to hunt down.
Why is this such a big problem?
-------------------------------
Because it defies the purpose of this network. Stack Exchange is supposed to be a Q&A-network, right? The ultimate goal is to have a collection of every possible question, alongside with the correct answer. In order to have a collection of that size you'll have to filter out the garbage, and that's what a lot of people are doing by using the tools given to them, flags, close votes and hammers.
Reputation on the other hand is the currency of this network. It depicts - to a certain extent - how much "trust" you've gained, and how much effort you've put into this project. However, thanks to people answering questions FGITW-style, this currency loses its meaning.
(*Side-note: I am not talking about new users. I try to explain them the system that Stack Exchange is based on, and move on. I'm talking about the high-rep users that do this knowingly, as in answering known duplicates, off-topic questions, and so on.*)
In my opinion these people are actively damaging the Stack Exchange network.
The reputation system is getting abused, and yet they can continue what they're doing. All I can do in this case is downvote it, but - in most cases - the OP has already upvoted & accepted that answer, so my downvote does what? Lower his rep gain from 25 (Upvote + Accept) to 23? To be honest, I can't be bothered.
|
I've never used the term *rep-whore* and I agree that it sounds pejorative and belittling. Those who answer off-topic questions just to earn a few tens of reputation points should be called *SE user* because we did it one way or another in the past. However, what do you call a user who constantly answer off-topic questions?
The linked question was posted on English Language and Usage, [What's a less offensive substitute for “rep-whores”?](https://english.stackexchange.com/questions/226736/whats-a-less-offensive-substitute-for-rep-whores) and it suggests multiple alternatives.
(In order of the number of upvotes)
>
> Rep-hound
>
>
> Rep-farmer
>
>
> Rep-junkie
>
>
> Rep-monger
>
>
> Rep-minded
>
>
> Rep-reaper
>
>
> Rep-chaser
>
>
> ...
>
>
>
|
281,787 |
Going forward, “rep-whore” (and its derivatives) will be treated like any other term that’s inconsistent with the community’s “be nice” policy: it will be removed.
It’s totally okay if you’ve used it in the past.
================================================
Nobody’s judging the many users who’ve used it. And users will NOT start being suspended/banned/fed-to-the-Sarlaac for using it in the near future without knowing about the change. We’re all partly products of what’s “normal” in our environment, and for a long time, use of that term *was* normal, and intended as a shorthand for “users who know a behavior is harmful, but do it anyway, entirely because it generates rep.” It was used - without malice - by good-hearted users in lots of old posts. It has probably been used by employees occasionally in the past. There’s no shame or judgment implied here; it’s just time to recognize that it's not consistent with "be nice.” And its use actually undermines our ability to get the most out of needed discussions on user behavior, incentives, etc. To be clear, it *is* absolutely okay to talk about *specific behaviors* that may represent unintended consequences of the rep-based feedback loop, and to continue to question them - just don’t do it by name-calling.
The short version of the "why"
==============================
* It’s inconsistent with our “be nice" policy:
+ It’s vulgar, and may be construed as being gendered (albeit not intentionally, in my observations).
+ The term makes the problem about the *person, not the action*. (And it doesn’t help to verbify it as “rep-whoring” - that’s still only describing it as something a person-type would do, vs. a specific thing that was done.)
* Naming “user types” with pejorative terms tends to lead to over-use of those terms, and undermines actual dialogue that might help us better understand what's going wrong.
That really covers it. But we like to be as open as possible about our underlying thinking, so if you're curious, or have a lot of time to kill...
The longer version
==================
**The term clearly doesn't jibe with “being nice”:**
Here are the relevant parts of the [Be Nice policy](https://stackoverflow.com/help/be-nice):
>
> * No Name Calling - Focus on the post, not the person. That includes terms that feel personal even when they're applied to posts (like "lazy", "ignorant", or "whiny").\*
> * Rudeness and belittling language are not okay.
> * Avoid vulgar terms and anything sexually suggestive.
> * Be welcoming, be patient, and **assume good intentions** (emphasis mine)
>
>
>
Frankly, those are good enough reasons - this community has always been fairly united in our commitment to discuss problems openly, **but with strong commitment to respect and courtesy, and a focus on the content or behavior, not the person.**
So, even if this term *were* super-useful in helping us solve problems and improve the site, I think most folks here would agree that we shouldn’t be scrapping big chunks of our “be nice” policy just for the sake of expediency. But here’s the funny thing:
**Using terms like “rep-whore” tends to *undermine* our ability to break down situations and learn where the system does have real problems or unintended consequences.**
**Labeling users with names that almost no one would call themselves reduces two-sided discourse and learning.** We actually learn the most when we listen to those who *don’t* agree with us (yet, anyway - I like to think they’ll eventually come around). But when we say, “the problem is rep-whores,” to explain someone answering questions that we think should be closed instead, it reduces the number of folks motivated to say, “Oh, hey - I guess I’m one of those ‘rep-whores’. Is that what you call someone who just answers questions when they can, but doesn’t keep track of what’s on- and off-topic?” Note that I’m *not* saying that’s usually the actual case, but the problem is that we'd never know if it were. By just describing it as “rep-whoring,” we've cut off much hope of learning if another motivation might apply - we’ve *assumed* we know the motivation, and given it a nasty name, so any users involved who might wish to actually explain their motivations don’t even think we're talking about (non-whore-esque) folks like them.
**There’s a funny thing about *naming* something.** Once a thing has a name, you tend to start seeing it everywhere. That's part of the positive power of language: by giving a complex thing a shorthand term, it’s easier to identify it quickly, just by matching a couple of key variables. Heuristics like that are what let us function at higher efficiency. But they come with costs: false positives and loss of nuance. The entire *point* of these types of categorization is to allow faster pattern matching, with fewer inputs and less analysis. But that means that things with *some* shared attributes, or even just similar ones, can get (wrongly) lumped in buckets pretty quickly.
Which is how we find ourselves making assumptions about others. I may think:
>
> “Someone who answers a question that we’d normally close is obviously only motivated by rep, and clearly doesn't care that it’s hurting the site.”
>
>
>
Maybe. Maybe they *are* only motivated by rep. Or maybe it’s something else: Maybe they don’t know (or care) what’s on-topic; they choose to answer questions where they can help, but don’t want to have to also serve as a filter for what’s currently allowed.
Personally, *I* happen to think that’s okay. I’m actually good with the idea that helping here doesn't require, “helping in all the ways, including ones you don’t enjoy.” Now, you may not agree, and think it’s a problem. That's good! And if that were the situation, *that’s* what we need to be talking about. But by ascribing the problems to “rep-whores,” I’ve eliminated that fact-finding step, and potentially even *prevented* us from getting to some of the real issues that we might want to discuss, all to save a few minutes by slapping a convenient name on the situation.
**Caring about getting lots of rep is a little like caring about getting lots of money - it seems to be a problem that is only diagnosed as afflicting *other people.*** Posts about rep-whores are pretty consistently written by folks who say they’re *not* at all motivated by rep - that *they* would only do things for more altruistic reasons. Which… I happen to believe is true. I think almost all of them *are actually motivated by the desire to help, or to contribute to a useful resource.* So here’s the question: given that we know *we’d* only choose behaviors if we thought they were good for the site, why are we so quick to assume that rep is the *primary* driver of others’ behavior, regardless of the harm it might cause? I think part of it may be what's apparently known as the [actor–observer asymmetry/bias](https://en.wikipedia.org/wiki/Actor%E2%80%93observer_asymmetry). The gist is this - when *you* swerve your car without warning, you know you’re a responsible driver coping as best you can with challenging circumstances - you saw something in the road, or your kid finally succeeded in pitching a gummy bear into your ear. But when you see someone *else* swerve their car, you assume they’re a bad driver. Or texting. Or drunk.
**In conclusion…**
Let’s keep talking about rep, and unintended consequences. To be honest, we *want* people to care about it, but not *too* much, and not as an end unto itself. Rep *is* supposed to be motivating, largely as a feedback loop. It's designed to confirm that you’re achieving what you all really came here to do: share your experiences in way that generates a resource that will actually make a difference. That little green "+10" is a proxy for someone saying, "that was useful". Your effort here mattered. So it’s okay to like getting it. I do. But it’s also okay - in fact it’s important - to call out places where it may be over-incentivizing things we don’t want. Let's just do it without using terms that’ll make Julia Roberts sad:
[](https://i.stack.imgur.com/rsiXM.jpg)
**For now, don’t worry about purging old uses of the term.**
This isn’t intended to create a lot of new work, particularly for mods, so we don’t want folks searching through tons of old posts and throwing up hundreds of flags. But if you run into new uses of the term, treat em like any other thing inconsistent with “be nice” (edit ‘em out when possible, etc.)
|
2016/07/29
|
[
"https://meta.stackexchange.com/questions/281787",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147336/"
] |
Yeah... This seems like a good idea. The term has moved from its original jocular uses to something considerably more mean-spirited. I suspect most folks using the term now have some sort of nasty boogieman in mind rather than [good ol' Marc Gravell](https://meta.stackexchange.com/questions/15540/award-bounties-at-the-end-of-the-day/15553#15553).
And [when folks here are more concerned about what other people think of them](https://meta.stackoverflow.com/questions/254549/how-to-decide-which-questions-i-should-not-answer) than they are about programming, I think the term becomes decidedly counter-productive, no less a distraction than rep itself.
FWIW, "whore" has triggered fast deletion on flagged comments for quite a while, and has been banned outright on Stack Overflow for over two years *because* it was being used to harass people:

|
For what it's worth, if anyone wishes to call me a whore - either for rep or otherwise - I find this acceptable. I cannot guarantee a third party won't moderate our communication regardless, but i'm just going on-record as saying I do not feel people who say this to me are breaking any sort of social contract. I will not accept **intimidation**, **name-calling**, or **nastiness**; but if i'm being **whore-like**, **whorish**, or just generally **whorey**, then please do call me out on it. It's much better that I stop than I continue in ignorance.
I'm not going to give a short and long version of why this is the socially responsible thing to do, instead i'll make 2 points:
1. I have seen the word 'whore' many times on the internet, and 99.999% of the time it was used for it's more modern definition - that of someone doing something unpleasant for some unrelated gain. Yes it might have started with sex for money, but these days it could be posts for rep, moderation for power, click-bait for ad revenue, etc. To stop using this word's new definition because that new definition has become more popular than the original definition will only, in my opinion, preserve the nastiness of the original definition and in the process we will lose a useful adjective.
2. This one is a little harder to explain, but essentially, SE in its current form is really rather good at moderating intimidation, name-calling and nastiness. That is because the whole context of the interaction is right there for all to see, mods can be summoned near-instantaneously to pass judgement, and most of the time they do so very well. This is important, because when it comes to nastiness context is everything. To ban a word regardless of it's context is anti-logical, anti-social, and ultimately anti-progressive. People *must* have the freedom to offend others, and to ultimately be banned for it. SE is fundamentally a democratic website, and for some words to be banned due to a technicality before they can go through the democratic process of *being read* would be at odds with the site's culture.
|
281,787 |
Going forward, “rep-whore” (and its derivatives) will be treated like any other term that’s inconsistent with the community’s “be nice” policy: it will be removed.
It’s totally okay if you’ve used it in the past.
================================================
Nobody’s judging the many users who’ve used it. And users will NOT start being suspended/banned/fed-to-the-Sarlaac for using it in the near future without knowing about the change. We’re all partly products of what’s “normal” in our environment, and for a long time, use of that term *was* normal, and intended as a shorthand for “users who know a behavior is harmful, but do it anyway, entirely because it generates rep.” It was used - without malice - by good-hearted users in lots of old posts. It has probably been used by employees occasionally in the past. There’s no shame or judgment implied here; it’s just time to recognize that it's not consistent with "be nice.” And its use actually undermines our ability to get the most out of needed discussions on user behavior, incentives, etc. To be clear, it *is* absolutely okay to talk about *specific behaviors* that may represent unintended consequences of the rep-based feedback loop, and to continue to question them - just don’t do it by name-calling.
The short version of the "why"
==============================
* It’s inconsistent with our “be nice" policy:
+ It’s vulgar, and may be construed as being gendered (albeit not intentionally, in my observations).
+ The term makes the problem about the *person, not the action*. (And it doesn’t help to verbify it as “rep-whoring” - that’s still only describing it as something a person-type would do, vs. a specific thing that was done.)
* Naming “user types” with pejorative terms tends to lead to over-use of those terms, and undermines actual dialogue that might help us better understand what's going wrong.
That really covers it. But we like to be as open as possible about our underlying thinking, so if you're curious, or have a lot of time to kill...
The longer version
==================
**The term clearly doesn't jibe with “being nice”:**
Here are the relevant parts of the [Be Nice policy](https://stackoverflow.com/help/be-nice):
>
> * No Name Calling - Focus on the post, not the person. That includes terms that feel personal even when they're applied to posts (like "lazy", "ignorant", or "whiny").\*
> * Rudeness and belittling language are not okay.
> * Avoid vulgar terms and anything sexually suggestive.
> * Be welcoming, be patient, and **assume good intentions** (emphasis mine)
>
>
>
Frankly, those are good enough reasons - this community has always been fairly united in our commitment to discuss problems openly, **but with strong commitment to respect and courtesy, and a focus on the content or behavior, not the person.**
So, even if this term *were* super-useful in helping us solve problems and improve the site, I think most folks here would agree that we shouldn’t be scrapping big chunks of our “be nice” policy just for the sake of expediency. But here’s the funny thing:
**Using terms like “rep-whore” tends to *undermine* our ability to break down situations and learn where the system does have real problems or unintended consequences.**
**Labeling users with names that almost no one would call themselves reduces two-sided discourse and learning.** We actually learn the most when we listen to those who *don’t* agree with us (yet, anyway - I like to think they’ll eventually come around). But when we say, “the problem is rep-whores,” to explain someone answering questions that we think should be closed instead, it reduces the number of folks motivated to say, “Oh, hey - I guess I’m one of those ‘rep-whores’. Is that what you call someone who just answers questions when they can, but doesn’t keep track of what’s on- and off-topic?” Note that I’m *not* saying that’s usually the actual case, but the problem is that we'd never know if it were. By just describing it as “rep-whoring,” we've cut off much hope of learning if another motivation might apply - we’ve *assumed* we know the motivation, and given it a nasty name, so any users involved who might wish to actually explain their motivations don’t even think we're talking about (non-whore-esque) folks like them.
**There’s a funny thing about *naming* something.** Once a thing has a name, you tend to start seeing it everywhere. That's part of the positive power of language: by giving a complex thing a shorthand term, it’s easier to identify it quickly, just by matching a couple of key variables. Heuristics like that are what let us function at higher efficiency. But they come with costs: false positives and loss of nuance. The entire *point* of these types of categorization is to allow faster pattern matching, with fewer inputs and less analysis. But that means that things with *some* shared attributes, or even just similar ones, can get (wrongly) lumped in buckets pretty quickly.
Which is how we find ourselves making assumptions about others. I may think:
>
> “Someone who answers a question that we’d normally close is obviously only motivated by rep, and clearly doesn't care that it’s hurting the site.”
>
>
>
Maybe. Maybe they *are* only motivated by rep. Or maybe it’s something else: Maybe they don’t know (or care) what’s on-topic; they choose to answer questions where they can help, but don’t want to have to also serve as a filter for what’s currently allowed.
Personally, *I* happen to think that’s okay. I’m actually good with the idea that helping here doesn't require, “helping in all the ways, including ones you don’t enjoy.” Now, you may not agree, and think it’s a problem. That's good! And if that were the situation, *that’s* what we need to be talking about. But by ascribing the problems to “rep-whores,” I’ve eliminated that fact-finding step, and potentially even *prevented* us from getting to some of the real issues that we might want to discuss, all to save a few minutes by slapping a convenient name on the situation.
**Caring about getting lots of rep is a little like caring about getting lots of money - it seems to be a problem that is only diagnosed as afflicting *other people.*** Posts about rep-whores are pretty consistently written by folks who say they’re *not* at all motivated by rep - that *they* would only do things for more altruistic reasons. Which… I happen to believe is true. I think almost all of them *are actually motivated by the desire to help, or to contribute to a useful resource.* So here’s the question: given that we know *we’d* only choose behaviors if we thought they were good for the site, why are we so quick to assume that rep is the *primary* driver of others’ behavior, regardless of the harm it might cause? I think part of it may be what's apparently known as the [actor–observer asymmetry/bias](https://en.wikipedia.org/wiki/Actor%E2%80%93observer_asymmetry). The gist is this - when *you* swerve your car without warning, you know you’re a responsible driver coping as best you can with challenging circumstances - you saw something in the road, or your kid finally succeeded in pitching a gummy bear into your ear. But when you see someone *else* swerve their car, you assume they’re a bad driver. Or texting. Or drunk.
**In conclusion…**
Let’s keep talking about rep, and unintended consequences. To be honest, we *want* people to care about it, but not *too* much, and not as an end unto itself. Rep *is* supposed to be motivating, largely as a feedback loop. It's designed to confirm that you’re achieving what you all really came here to do: share your experiences in way that generates a resource that will actually make a difference. That little green "+10" is a proxy for someone saying, "that was useful". Your effort here mattered. So it’s okay to like getting it. I do. But it’s also okay - in fact it’s important - to call out places where it may be over-incentivizing things we don’t want. Let's just do it without using terms that’ll make Julia Roberts sad:
[](https://i.stack.imgur.com/rsiXM.jpg)
**For now, don’t worry about purging old uses of the term.**
This isn’t intended to create a lot of new work, particularly for mods, so we don’t want folks searching through tons of old posts and throwing up hundreds of flags. But if you run into new uses of the term, treat em like any other thing inconsistent with “be nice” (edit ‘em out when possible, etc.)
|
2016/07/29
|
[
"https://meta.stackexchange.com/questions/281787",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/147336/"
] |
>
> It's time...
>
>
>
...it's time to keep the [promise](https://meta.stackoverflow.com/a/320971/839601) made three months ago:
>
> we'll start looking at [increasing the number of close votes based on rep](https://meta.stackexchange.com/questions/266500/proposal-to-make-close-votes-scale-with-rep)
>
>
>
You seem to be blaming users for unnecessary rudeness and trying to cut their ways to express it. That may be true and right, but if you think of it the [root cause](https://softwareengineering.stackexchange.com/a/154741/31260) for their attitude may lie elsewhere.
For example, if many inappropriate questions aren't closed quickly enough and this makes a wide open door for answers to leak into them, it may cause negative feelings for those who care about content quality. If this is the case, banning particular negative terms won't help. The negative feelings will stay; people will simply invent other terms to express them, and things won't really get nicer.
I think it's time to look closer at these things in the historical perspective.
For example, how come that after years of plugging users' mouths and twisting their arms with *summers of love* and *hunting the snark*, the second-highest-voted question at MSO is [Why is Stack Overflow so **negative** of late?](https://meta.stackoverflow.com/q/251758/839601) Makes one wonder if this way works, doesn't it?
---
You see, negative feelings (and their respective terms) may simply indicate that a community lacks power and tools to protect itself from inappropriate content.
I heard that the author who best explained these matters is a member of Stack Exchange's board of directors -- ([Clay Shirky](http://www.shirky.com/writings/group_enemy.html "who wrote 'A Group Is Its Own Worst Enemy'")) -- maybe it's time to have a word with him.
>
> thing you have to accept: Members are different than users. A pattern will arise in which there is some group of users that cares more than average about the integrity and success of the group as a whole. And that becomes your core group, Art Kleiner's phrase for "the group within the group that matters most."
>
>
> The core group... was undifferentiated from the group of random users that came in. They were separate in their own minds, because they knew what they wanted to do, but they couldn't defend themselves against the other users. But in all successful online communities that I've looked at, a core group arises that cares about and gardens effectively. Gardens the environment, to keep it growing, to keep it healthy.
>
>
> Now, the software does not always allow the core group to express itself, which is why I say you have to accept this. Because if the software doesn't allow the core group to express itself, it will invent new ways of doing so...
>
>
>
I think it would be very **nice** of you to pay a bit more attention to the [concerns of your core group](https://meta.stackoverflow.com/a/254973/839601 "example here: 'SO has experienced geometric growth since its inception, doubling in size every 18 months or so. That stopped in the fall of last year, it has been roughly stable since then with a hint of contraction. This has been brought up in meta many times in the past few months. Hopefully the site owners are paying attention...'").
|
This feels a bit like [bowdlerisation](https://en.wikipedia.org/wiki/Thomas_Bowdler). I've *personally* avoided it and favour the term 'Power Gamer' or 'Bounty Hunter' (drawing from my mispent youth as a pen and paper gamer).
To me the 'be nice' policy isn't about language use. It's about ensuring that as many of my users (as a mod) feel as comfortable as possible, and I've almost never seen the term used as such.
I've never seen anyone actually *use* the term 'repwhore' in anger. It's used in terms of 'repwhorage' in some situations. (Interestingly, the term's been only used 6 times on Root Access. Mostly by me, referring to me. I encourage others to try this on, and it's been used 4 times on meta SU -- this isn't exactly common.) It might be different on other sites.
I feel 'be nice' is not about the *words*; it's about the *actions* and *overall intent*. If someone on a site I'm seeing went "hey, I'm not comfortable with someone calling me a repwhore" I'd obviously encourage the person who used that term to be more *precise* over what issues they have are. If someone called themselves a repwhore, or referred to an answer as repwhorage, it's a very different thing,
So, I think the solution here might not be to worry about the *term*. If it needs to be gone, encouraging *precision* and *focusing on the actions* is good moderation.
So as a mod, it feels like it's an attempt to solve a non existent problem. We can simply deal with people not being nice for its own sake without declaring war on a phrase.
|
1,673,276 |
Suppose $\vec{w}=\frac{g}{||\vec{v}||} \vec{v}$, what is the derivative of $\vec{w}$ w.r.t. $\vec{v}$?
Don't know how to deal with the norm of $\vec{v}$ here...
Thanks in advance. :-)
Edit:
$L$ is a function of $\vec{w}$ and $g$. Based on $\vec{w}=\frac{g}{||\vec{v}||} \vec{v}$, we have
$$\nabla{g}{L}=\frac{\nabla{\vec{w}}{L} \cdot \vec{v}}{||\vec{v}||}$$
$$\nabla{\vec{v}}{L}=\frac{g}{||\vec{v}||}\nabla{\vec{w}}{L}-\frac{g\nabla{g}{L}}{||\vec{v}||^2}\vec{v}$$
Could you show how to get exactly the second equation? It seems a bit weird to me.
|
2016/02/26
|
[
"https://math.stackexchange.com/questions/1673276",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/311922/"
] |
**Hint.**
Apply the chain rule, using the fact that $$f(\vec{v})=\frac{\vec{v}}{||\vec{v}||} = F(\vec{v})\vec{v}$$ where $$F(\vec{v})= \frac{1}{\sqrt{\Vert \vec{v} \Vert^2}}$$ and $$h(\vec{v})=\Vert \vec{v} \Vert^2= (\vec{v},\vec{v})$$ is a bilinear map so its Fréchet derivative is $$h^\prime(\vec{v}).\vec{r} = 2 (\vec{v},\vec{r})$$ and applying the chain rule $$F^\prime(\vec{v}).\vec{r}=-\frac{(\vec{v},\vec{r})}{\Vert \vec{v} \Vert^3}$$
Applying again the chain rule to $f$:
$$f^\prime(\vec{v}).\vec{r}=(F^\prime(\vec{v}).\vec{r})\vec{v} + F(\vec{v})\vec{r}$$ you finally get
$$f^\prime(\vec{v}).\vec{r} = -\frac{(\vec{v},\vec{r})}{\Vert \vec{v} \Vert^3}\vec{v}+\frac{\vec{r}}{\Vert \vec{v} \Vert}$$
If $g$ is also a map depending on $\vec{v}$, you need to applying the chain rule once more.
|
The ''derivative'' of a vector function of a vector is not a single number, but a matrix that contains all the partial derivative of the vector function with respect to the components of the independent vector, called the [Jacobian matrix](https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant#Jacobian_matrix).
In your case, supposing that, $\vec W$ and $\vec v$ are vectors of a $n-$ dimensional real vector space, we have:
$$
\frac{\partial \vec w}{\partial \vec v}=
\begin{bmatrix}
\frac{\partial w\_1}{\partial v\_1}&\frac{\partial w\_1}{\partial v\_2} &\cdots&\frac{\partial w\_1}{\partial v\_n}\\
\frac{\partial w\_2}{\partial v\_1}&\frac{\partial w\_2}{\partial v\_2} &\cdots&\frac{\partial w\_2}{\partial v\_n}\\
\cdots\\
\frac{\partial w\_n}{\partial v\_1}&\frac{\partial w\_n}{\partial v\_2} &\cdots&\frac{\partial w\_n}{\partial v\_n}\\
\end{bmatrix}
$$
Using this definition you can evaluate the elements of the matrix for your function. If $n=2$, we have:
$$
\begin{bmatrix}
w\_1\\
w\_2
\end{bmatrix}
=
\begin{bmatrix}
\frac{gv\_1}{\sqrt{v\_1^2+v\_2^2}}\\
\frac{gv\_2}{\sqrt{v\_1^2+v\_2^2}}
\end{bmatrix}
$$
so we can find the partial derivatives as:
$$
\frac{\partial w\_1}{\partial v\_1}=\frac{gv\_2^2}{\sqrt{\left(v\_1^2+v\_2^2\right)^3}}
\qquad
\frac{\partial w\_1}{\partial v\_2}=\frac{-gv\_1v\_2}{\sqrt{\left(v\_1^2+v\_2^2\right)^3}}
$$
and so one... and you can do the same if $n>2$.
|
23,286,254 |
I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.
This is the input list:
```
L = [1,term1, 3, term2, x, term3,... z, termN]
```
and I want to convert this list to a list of tuples (or directly to a dictionary) like this:
```
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
```
How can we do that easily in Python?
|
2014/04/25
|
[
"https://Stackoverflow.com/questions/23286254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
# Create an iterator
>>> it = iter(L)
# zip the iterator with itself
>>> zip(it, it)
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
```
You want to group three items at a time?
```
>>> zip(it, it, it)
```
You want to group N items at a time?
```
# Create N copies of the same iterator
it = [iter(L)] * N
# Unpack the copies of the iterator, and pass them as parameters to zip
>>> zip(*it)
```
|
The below code will take care of both even and odd sized list :
```
[set(L[i:i+2]) for i in range(0, len(L),2)]
```
|
23,286,254 |
I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.
This is the input list:
```
L = [1,term1, 3, term2, x, term3,... z, termN]
```
and I want to convert this list to a list of tuples (or directly to a dictionary) like this:
```
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
```
How can we do that easily in Python?
|
2014/04/25
|
[
"https://Stackoverflow.com/questions/23286254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
# Create an iterator
>>> it = iter(L)
# zip the iterator with itself
>>> zip(it, it)
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
```
You want to group three items at a time?
```
>>> zip(it, it, it)
```
You want to group N items at a time?
```
# Create N copies of the same iterator
it = [iter(L)] * N
# Unpack the copies of the iterator, and pass them as parameters to zip
>>> zip(*it)
```
|
```
[(L[i], L[i+1]) for i in xrange(0, len(L), 2)]
```
|
23,286,254 |
I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.
This is the input list:
```
L = [1,term1, 3, term2, x, term3,... z, termN]
```
and I want to convert this list to a list of tuples (or directly to a dictionary) like this:
```
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
```
How can we do that easily in Python?
|
2014/04/25
|
[
"https://Stackoverflow.com/questions/23286254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
# Create an iterator
>>> it = iter(L)
# zip the iterator with itself
>>> zip(it, it)
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
```
You want to group three items at a time?
```
>>> zip(it, it, it)
```
You want to group N items at a time?
```
# Create N copies of the same iterator
it = [iter(L)] * N
# Unpack the copies of the iterator, and pass them as parameters to zip
>>> zip(*it)
```
|
Using slicing?
```
L = [1, "term1", 2, "term2", 3, "term3"]
L = zip(L[::2], L[1::2])
print L
```
|
23,286,254 |
I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.
This is the input list:
```
L = [1,term1, 3, term2, x, term3,... z, termN]
```
and I want to convert this list to a list of tuples (or directly to a dictionary) like this:
```
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
```
How can we do that easily in Python?
|
2014/04/25
|
[
"https://Stackoverflow.com/questions/23286254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
# Create an iterator
>>> it = iter(L)
# zip the iterator with itself
>>> zip(it, it)
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
```
You want to group three items at a time?
```
>>> zip(it, it, it)
```
You want to group N items at a time?
```
# Create N copies of the same iterator
it = [iter(L)] * N
# Unpack the copies of the iterator, and pass them as parameters to zip
>>> zip(*it)
```
|
Try with the group clustering idiom:
```
zip(*[iter(L)]*2)
```
From <https://docs.python.org/2/library/functions.html>:
>
> The left-to-right evaluation order of the iterables is guaranteed.
> This makes possible an idiom for clustering a data series into
> n-length groups using zip(\*[iter(s)]\*n).
>
>
>
|
23,286,254 |
I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.
This is the input list:
```
L = [1,term1, 3, term2, x, term3,... z, termN]
```
and I want to convert this list to a list of tuples (or directly to a dictionary) like this:
```
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
```
How can we do that easily in Python?
|
2014/04/25
|
[
"https://Stackoverflow.com/questions/23286254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Using slicing?
```
L = [1, "term1", 2, "term2", 3, "term3"]
L = zip(L[::2], L[1::2])
print L
```
|
Try this ,
```
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
>>> it = iter(L)
>>> [(x, next(it)) for x in it ]
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
>>>
```
OR
--
```
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
>>> [i for i in zip(*[iter(L)]*2)]
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
```
OR
--
```
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
>>> map(None,*[iter(L)]*2)
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
>>>
```
|
23,286,254 |
I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.
This is the input list:
```
L = [1,term1, 3, term2, x, term3,... z, termN]
```
and I want to convert this list to a list of tuples (or directly to a dictionary) like this:
```
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
```
How can we do that easily in Python?
|
2014/04/25
|
[
"https://Stackoverflow.com/questions/23286254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
List directly into a dictionary using `zip` to pair consecutive even and odd elements:
```
m = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
d = { x : y for x, y in zip(m[::2], m[1::2]) }
```
or, since you are familiar with the tuple -> dict direction:
```
d = dict(t for t in zip(m[::2], m[1::2]))
```
even:
```
d = dict(zip(m[::2], m[1::2]))
```
|
The below code will take care of both even and odd sized list :
```
[set(L[i:i+2]) for i in range(0, len(L),2)]
```
|
23,286,254 |
I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.
This is the input list:
```
L = [1,term1, 3, term2, x, term3,... z, termN]
```
and I want to convert this list to a list of tuples (or directly to a dictionary) like this:
```
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
```
How can we do that easily in Python?
|
2014/04/25
|
[
"https://Stackoverflow.com/questions/23286254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
# Create an iterator
>>> it = iter(L)
# zip the iterator with itself
>>> zip(it, it)
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
```
You want to group three items at a time?
```
>>> zip(it, it, it)
```
You want to group N items at a time?
```
# Create N copies of the same iterator
it = [iter(L)] * N
# Unpack the copies of the iterator, and pass them as parameters to zip
>>> zip(*it)
```
|
Try this ,
```
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
>>> it = iter(L)
>>> [(x, next(it)) for x in it ]
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
>>>
```
OR
--
```
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
>>> [i for i in zip(*[iter(L)]*2)]
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
```
OR
--
```
>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
>>> map(None,*[iter(L)]*2)
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]
>>>
```
|
23,286,254 |
I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.
This is the input list:
```
L = [1,term1, 3, term2, x, term3,... z, termN]
```
and I want to convert this list to a list of tuples (or directly to a dictionary) like this:
```
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
```
How can we do that easily in Python?
|
2014/04/25
|
[
"https://Stackoverflow.com/questions/23286254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Using slicing?
```
L = [1, "term1", 2, "term2", 3, "term3"]
L = zip(L[::2], L[1::2])
print L
```
|
The below code will take care of both even and odd sized list :
```
[set(L[i:i+2]) for i in range(0, len(L),2)]
```
|
23,286,254 |
I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.
This is the input list:
```
L = [1,term1, 3, term2, x, term3,... z, termN]
```
and I want to convert this list to a list of tuples (or directly to a dictionary) like this:
```
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
```
How can we do that easily in Python?
|
2014/04/25
|
[
"https://Stackoverflow.com/questions/23286254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Try with the group clustering idiom:
```
zip(*[iter(L)]*2)
```
From <https://docs.python.org/2/library/functions.html>:
>
> The left-to-right evaluation order of the iterables is guaranteed.
> This makes possible an idiom for clustering a data series into
> n-length groups using zip(\*[iter(s)]\*n).
>
>
>
|
The below code will take care of both even and odd sized list :
```
[set(L[i:i+2]) for i in range(0, len(L),2)]
```
|
23,286,254 |
I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.
This is the input list:
```
L = [1,term1, 3, term2, x, term3,... z, termN]
```
and I want to convert this list to a list of tuples (or directly to a dictionary) like this:
```
[(1, term1), (3, term2), (x, term3), ...(z, termN)]
```
How can we do that easily in Python?
|
2014/04/25
|
[
"https://Stackoverflow.com/questions/23286254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
List directly into a dictionary using `zip` to pair consecutive even and odd elements:
```
m = [ 1, 2, 3, 4, 5, 6, 7, 8 ]
d = { x : y for x, y in zip(m[::2], m[1::2]) }
```
or, since you are familiar with the tuple -> dict direction:
```
d = dict(t for t in zip(m[::2], m[1::2]))
```
even:
```
d = dict(zip(m[::2], m[1::2]))
```
|
Using slicing?
```
L = [1, "term1", 2, "term2", 3, "term3"]
L = zip(L[::2], L[1::2])
print L
```
|
22,206,044 |
I followed a number of posts on SO, and finally I can draw a conclusion that when we
have something like :
```
Person name;
```
`name` is an object of class `person`.
It becomes instance when instantiate it :
```
name=new Person();
```
I am a beginner in C++, and so far I have seen we can access the functions and variables like:
```
Person name;
name.getValue;
name.callFunction();
```
We need not to use `new` operator for this. So can we say the differentiating factor between an object and instance can be ignored in C++?
|
2014/03/05
|
[
"https://Stackoverflow.com/questions/22206044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820722/"
] |
Object and instance are two words for the same thing.
|
"Object" and "instance" are almost interchangeable. In C++, an object is formally any region of storage. "Instance" is not a formally defined term, but we typically refer to "instances of type `X`", most commonly used with class types.
```
Foo f;
```
This declaration creates an object named `f`. The object's type is `Foo`. You could say the object `f` is an instance of `Foo`.
Your attempt to distinguish the terms was incorrect. The two things you've actually pointed out are two different ways of creating objects.
```
Person name;
```
In this case, we're creating an object `name` of type `Person`.
```
Person* name = new Person();
```
In this case, we're creating an object `name` of type `Person*` (pointer to `Person`). We are also creating another object of type `Person` using the expression `new Person()`. This expression returns a pointer, which we are initialising the `name` object with.
|
22,206,044 |
I followed a number of posts on SO, and finally I can draw a conclusion that when we
have something like :
```
Person name;
```
`name` is an object of class `person`.
It becomes instance when instantiate it :
```
name=new Person();
```
I am a beginner in C++, and so far I have seen we can access the functions and variables like:
```
Person name;
name.getValue;
name.callFunction();
```
We need not to use `new` operator for this. So can we say the differentiating factor between an object and instance can be ignored in C++?
|
2014/03/05
|
[
"https://Stackoverflow.com/questions/22206044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820722/"
] |
In C++ "object" and "instance" are used nearly interchangably.
There is a general programming design pattern of `class` and `instance`. The `class` holds the information about all `instance`s in that `class`.
In C++ when you declare a `class` or `struct`, the compiler makes code that describes how you create an `instance` of that `class`, what the data layout is, and provides some methods that can be used to interact with that `instance` (up to and including destruction).
`virtual` methods and inheritance seemingly moves some of the methods and layout to the instance: but the amount is quite limited. Instead, each instance holds pointers to `virtual` class data. In some languages, you can do things like replace individual methods of an instance at runtime: but not in C++.
When you create an instance of that `class` or `struct`, it can be via an automatic named variable on the stack (like `Foo f;`), an anonymous automatic named variable (like `some_function( Foo(17,22) )`), an instance on the free store (like `new Foo(17, 22)`), or via placement-`new` (which is how `std::vector` and `std::make_shared` creates instances).
Confusingly, there is a separate parallel `class`-`instance` pattern in C++ -- `class template`-`class`. The `class template` is the `class`, the instantiation is the instance. The `template` arguments and specializations indicate how, at compile time, you can "construct" the `class`es. Pattern matching on the `class template`s provide a limited amount of properties that are not tied to the instances ("class properties" in the pattern). (Arguably the function template-function is another instance of the pattern).
If you look at the [C++1y proposal for concepts lite](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3580.pdf) you will see where object and instance might mean different things in C++.
```
int x = 0;
int& foo = x;
int* bar = &x;
```
`x` is both an object and an instance of the type `int`.
`foo` is an instance of the type `int&`, but calling `foo` an object is probably wrong! It is a reference -- an alias, or a different name for some object (in this case `x`).
`bar` is a pointer to an `int`, which is an instance of type `int*`, and calling it an object is probably correct.
This is a useful distinction: a type does not have to denote an object type if it is a reference type. Object types behave differently than reference types in a number of important ways.
Now, some types have "reference semantics", in that they behave like references in many ways, but are actually `class`es. Are instances of such a type better called references or objects? In horrible cases, some instances have a mixture of both reference and object semantics: such is often a bad sign.
Via [latest standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3580.pdf) in 3.9 [Types] we have the kinds of types in C++. They describe what an *object type* is:
>
> Types describe objects (1.8), references (8.3.2), or functions (8.3.5)
>
>
>
and
>
> An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.
>
>
>
So calling the "instances" of things that are function types or reference types "objects" seems incorrect. Note that accessing the "representation" of a function or a reference instance is basically impossible: references alias into the object they refer to, and using the name of a function decays to a pointers-to-functions at the drop of a hat (and pointers-to-a-function are basically opaque handles that let you invoke them).
So arguably functions are not instances, and references are not instances.
On the third hand, we do talk about instantiations of `class` `template`s and function `template`s. 14.7 is "template instantiation and specialization", and points of instantiation (of a `template`) are all formal terms from the standard.
|
Object and instance are two words for the same thing.
|
22,206,044 |
I followed a number of posts on SO, and finally I can draw a conclusion that when we
have something like :
```
Person name;
```
`name` is an object of class `person`.
It becomes instance when instantiate it :
```
name=new Person();
```
I am a beginner in C++, and so far I have seen we can access the functions and variables like:
```
Person name;
name.getValue;
name.callFunction();
```
We need not to use `new` operator for this. So can we say the differentiating factor between an object and instance can be ignored in C++?
|
2014/03/05
|
[
"https://Stackoverflow.com/questions/22206044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820722/"
] |
Object and instance are two words for the same thing.
|
It is very simple but very important
Take a general example: what is the general meaning of object? its nothing but which occupies some space right....keep that in mind we now talk about Object in java or C++
example: here I am creating Object **Student std=new Student();**
where **Student** is a **Class** and **std** is a **Object** because we Created a memory for std with the help of **new** keyWord it means it internally occupies some space in memory right thats y we call **std** as **Object**
if you won`t create memory for an object so we call that **object** as **instance**.
example: Student std;
here **Student** is a class and **std** is a instance(means a just a copy that class),with this we won`t do anything untill unless we create a memory for that.
Thats all about object and Instance :)
|
22,206,044 |
I followed a number of posts on SO, and finally I can draw a conclusion that when we
have something like :
```
Person name;
```
`name` is an object of class `person`.
It becomes instance when instantiate it :
```
name=new Person();
```
I am a beginner in C++, and so far I have seen we can access the functions and variables like:
```
Person name;
name.getValue;
name.callFunction();
```
We need not to use `new` operator for this. So can we say the differentiating factor between an object and instance can be ignored in C++?
|
2014/03/05
|
[
"https://Stackoverflow.com/questions/22206044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820722/"
] |
First, you should know that there is no difference between "object" and "instance". They are synonyms. In C++, you also call instances of primitive types like `int` or `double` "objects". One of the design principles of C++ is that custom types (i.e. classes) can be made to behave exactly like primitive types. In fact, in C++, one often prefers to refer to "types" and not "classes".
So, *types* and *objects* it shall be. Now that we've settled this, I'm afraid I must tell you that your conclusions are wrong.
`Person` is a *type*.
`name` is a (not very well named) variable to access an *object* of that type.
A whole line of C++ code would look like this:
```
Person name;
```
This means: "create an object of type Person and let me access it via the name variable".
`new Person()` is much more complicated. You may be familiar with the `new` keyword from languages like Java, but in C++, it's a very different beast. It means that a new object of type `Person` is created, but it also means that **you are responsible for destroying it** later on. It also gives you a different kind of handle to the newly created object: a so-called *pointer*. A `Person` pointer looks like this:
```
Person*
```
A pointer is itself a type, and the types `Person*` and `Person` are not compatible. (I told you that this would be much more complicated :))
You will notice the incompatibility when you try to compile the following line:
```
Person name = new Person();
```
It won't compile; you will instead receive an error message. You'd have to do it like this instead:
```
Person* name_ptr = new Person();
```
And then you'd have to access all the members of `Person` with a different syntax:
```
name_ptr->getValue();
name_ptr->callFunction();
```
Finally, remember you must explicitly destroy the object in this case:
```
delete name_ptr;
```
If you forget this, bad things can happen. More precisely, your program will likely use more and more memory the longer it runs.
I think that pointers are too advanced yet for your level of C++ understanding. Stay away from them until you actually need them.
|
"Object" and "instance" are almost interchangeable. In C++, an object is formally any region of storage. "Instance" is not a formally defined term, but we typically refer to "instances of type `X`", most commonly used with class types.
```
Foo f;
```
This declaration creates an object named `f`. The object's type is `Foo`. You could say the object `f` is an instance of `Foo`.
Your attempt to distinguish the terms was incorrect. The two things you've actually pointed out are two different ways of creating objects.
```
Person name;
```
In this case, we're creating an object `name` of type `Person`.
```
Person* name = new Person();
```
In this case, we're creating an object `name` of type `Person*` (pointer to `Person`). We are also creating another object of type `Person` using the expression `new Person()`. This expression returns a pointer, which we are initialising the `name` object with.
|
22,206,044 |
I followed a number of posts on SO, and finally I can draw a conclusion that when we
have something like :
```
Person name;
```
`name` is an object of class `person`.
It becomes instance when instantiate it :
```
name=new Person();
```
I am a beginner in C++, and so far I have seen we can access the functions and variables like:
```
Person name;
name.getValue;
name.callFunction();
```
We need not to use `new` operator for this. So can we say the differentiating factor between an object and instance can be ignored in C++?
|
2014/03/05
|
[
"https://Stackoverflow.com/questions/22206044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820722/"
] |
In C++ "object" and "instance" are used nearly interchangably.
There is a general programming design pattern of `class` and `instance`. The `class` holds the information about all `instance`s in that `class`.
In C++ when you declare a `class` or `struct`, the compiler makes code that describes how you create an `instance` of that `class`, what the data layout is, and provides some methods that can be used to interact with that `instance` (up to and including destruction).
`virtual` methods and inheritance seemingly moves some of the methods and layout to the instance: but the amount is quite limited. Instead, each instance holds pointers to `virtual` class data. In some languages, you can do things like replace individual methods of an instance at runtime: but not in C++.
When you create an instance of that `class` or `struct`, it can be via an automatic named variable on the stack (like `Foo f;`), an anonymous automatic named variable (like `some_function( Foo(17,22) )`), an instance on the free store (like `new Foo(17, 22)`), or via placement-`new` (which is how `std::vector` and `std::make_shared` creates instances).
Confusingly, there is a separate parallel `class`-`instance` pattern in C++ -- `class template`-`class`. The `class template` is the `class`, the instantiation is the instance. The `template` arguments and specializations indicate how, at compile time, you can "construct" the `class`es. Pattern matching on the `class template`s provide a limited amount of properties that are not tied to the instances ("class properties" in the pattern). (Arguably the function template-function is another instance of the pattern).
If you look at the [C++1y proposal for concepts lite](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3580.pdf) you will see where object and instance might mean different things in C++.
```
int x = 0;
int& foo = x;
int* bar = &x;
```
`x` is both an object and an instance of the type `int`.
`foo` is an instance of the type `int&`, but calling `foo` an object is probably wrong! It is a reference -- an alias, or a different name for some object (in this case `x`).
`bar` is a pointer to an `int`, which is an instance of type `int*`, and calling it an object is probably correct.
This is a useful distinction: a type does not have to denote an object type if it is a reference type. Object types behave differently than reference types in a number of important ways.
Now, some types have "reference semantics", in that they behave like references in many ways, but are actually `class`es. Are instances of such a type better called references or objects? In horrible cases, some instances have a mixture of both reference and object semantics: such is often a bad sign.
Via [latest standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3580.pdf) in 3.9 [Types] we have the kinds of types in C++. They describe what an *object type* is:
>
> Types describe objects (1.8), references (8.3.2), or functions (8.3.5)
>
>
>
and
>
> An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.
>
>
>
So calling the "instances" of things that are function types or reference types "objects" seems incorrect. Note that accessing the "representation" of a function or a reference instance is basically impossible: references alias into the object they refer to, and using the name of a function decays to a pointers-to-functions at the drop of a hat (and pointers-to-a-function are basically opaque handles that let you invoke them).
So arguably functions are not instances, and references are not instances.
On the third hand, we do talk about instantiations of `class` `template`s and function `template`s. 14.7 is "template instantiation and specialization", and points of instantiation (of a `template`) are all formal terms from the standard.
|
"Object" and "instance" are almost interchangeable. In C++, an object is formally any region of storage. "Instance" is not a formally defined term, but we typically refer to "instances of type `X`", most commonly used with class types.
```
Foo f;
```
This declaration creates an object named `f`. The object's type is `Foo`. You could say the object `f` is an instance of `Foo`.
Your attempt to distinguish the terms was incorrect. The two things you've actually pointed out are two different ways of creating objects.
```
Person name;
```
In this case, we're creating an object `name` of type `Person`.
```
Person* name = new Person();
```
In this case, we're creating an object `name` of type `Person*` (pointer to `Person`). We are also creating another object of type `Person` using the expression `new Person()`. This expression returns a pointer, which we are initialising the `name` object with.
|
22,206,044 |
I followed a number of posts on SO, and finally I can draw a conclusion that when we
have something like :
```
Person name;
```
`name` is an object of class `person`.
It becomes instance when instantiate it :
```
name=new Person();
```
I am a beginner in C++, and so far I have seen we can access the functions and variables like:
```
Person name;
name.getValue;
name.callFunction();
```
We need not to use `new` operator for this. So can we say the differentiating factor between an object and instance can be ignored in C++?
|
2014/03/05
|
[
"https://Stackoverflow.com/questions/22206044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820722/"
] |
In C++ "object" and "instance" are used nearly interchangably.
There is a general programming design pattern of `class` and `instance`. The `class` holds the information about all `instance`s in that `class`.
In C++ when you declare a `class` or `struct`, the compiler makes code that describes how you create an `instance` of that `class`, what the data layout is, and provides some methods that can be used to interact with that `instance` (up to and including destruction).
`virtual` methods and inheritance seemingly moves some of the methods and layout to the instance: but the amount is quite limited. Instead, each instance holds pointers to `virtual` class data. In some languages, you can do things like replace individual methods of an instance at runtime: but not in C++.
When you create an instance of that `class` or `struct`, it can be via an automatic named variable on the stack (like `Foo f;`), an anonymous automatic named variable (like `some_function( Foo(17,22) )`), an instance on the free store (like `new Foo(17, 22)`), or via placement-`new` (which is how `std::vector` and `std::make_shared` creates instances).
Confusingly, there is a separate parallel `class`-`instance` pattern in C++ -- `class template`-`class`. The `class template` is the `class`, the instantiation is the instance. The `template` arguments and specializations indicate how, at compile time, you can "construct" the `class`es. Pattern matching on the `class template`s provide a limited amount of properties that are not tied to the instances ("class properties" in the pattern). (Arguably the function template-function is another instance of the pattern).
If you look at the [C++1y proposal for concepts lite](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3580.pdf) you will see where object and instance might mean different things in C++.
```
int x = 0;
int& foo = x;
int* bar = &x;
```
`x` is both an object and an instance of the type `int`.
`foo` is an instance of the type `int&`, but calling `foo` an object is probably wrong! It is a reference -- an alias, or a different name for some object (in this case `x`).
`bar` is a pointer to an `int`, which is an instance of type `int*`, and calling it an object is probably correct.
This is a useful distinction: a type does not have to denote an object type if it is a reference type. Object types behave differently than reference types in a number of important ways.
Now, some types have "reference semantics", in that they behave like references in many ways, but are actually `class`es. Are instances of such a type better called references or objects? In horrible cases, some instances have a mixture of both reference and object semantics: such is often a bad sign.
Via [latest standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3580.pdf) in 3.9 [Types] we have the kinds of types in C++. They describe what an *object type* is:
>
> Types describe objects (1.8), references (8.3.2), or functions (8.3.5)
>
>
>
and
>
> An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.
>
>
>
So calling the "instances" of things that are function types or reference types "objects" seems incorrect. Note that accessing the "representation" of a function or a reference instance is basically impossible: references alias into the object they refer to, and using the name of a function decays to a pointers-to-functions at the drop of a hat (and pointers-to-a-function are basically opaque handles that let you invoke them).
So arguably functions are not instances, and references are not instances.
On the third hand, we do talk about instantiations of `class` `template`s and function `template`s. 14.7 is "template instantiation and specialization", and points of instantiation (of a `template`) are all formal terms from the standard.
|
First, you should know that there is no difference between "object" and "instance". They are synonyms. In C++, you also call instances of primitive types like `int` or `double` "objects". One of the design principles of C++ is that custom types (i.e. classes) can be made to behave exactly like primitive types. In fact, in C++, one often prefers to refer to "types" and not "classes".
So, *types* and *objects* it shall be. Now that we've settled this, I'm afraid I must tell you that your conclusions are wrong.
`Person` is a *type*.
`name` is a (not very well named) variable to access an *object* of that type.
A whole line of C++ code would look like this:
```
Person name;
```
This means: "create an object of type Person and let me access it via the name variable".
`new Person()` is much more complicated. You may be familiar with the `new` keyword from languages like Java, but in C++, it's a very different beast. It means that a new object of type `Person` is created, but it also means that **you are responsible for destroying it** later on. It also gives you a different kind of handle to the newly created object: a so-called *pointer*. A `Person` pointer looks like this:
```
Person*
```
A pointer is itself a type, and the types `Person*` and `Person` are not compatible. (I told you that this would be much more complicated :))
You will notice the incompatibility when you try to compile the following line:
```
Person name = new Person();
```
It won't compile; you will instead receive an error message. You'd have to do it like this instead:
```
Person* name_ptr = new Person();
```
And then you'd have to access all the members of `Person` with a different syntax:
```
name_ptr->getValue();
name_ptr->callFunction();
```
Finally, remember you must explicitly destroy the object in this case:
```
delete name_ptr;
```
If you forget this, bad things can happen. More precisely, your program will likely use more and more memory the longer it runs.
I think that pointers are too advanced yet for your level of C++ understanding. Stay away from them until you actually need them.
|
22,206,044 |
I followed a number of posts on SO, and finally I can draw a conclusion that when we
have something like :
```
Person name;
```
`name` is an object of class `person`.
It becomes instance when instantiate it :
```
name=new Person();
```
I am a beginner in C++, and so far I have seen we can access the functions and variables like:
```
Person name;
name.getValue;
name.callFunction();
```
We need not to use `new` operator for this. So can we say the differentiating factor between an object and instance can be ignored in C++?
|
2014/03/05
|
[
"https://Stackoverflow.com/questions/22206044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820722/"
] |
First, you should know that there is no difference between "object" and "instance". They are synonyms. In C++, you also call instances of primitive types like `int` or `double` "objects". One of the design principles of C++ is that custom types (i.e. classes) can be made to behave exactly like primitive types. In fact, in C++, one often prefers to refer to "types" and not "classes".
So, *types* and *objects* it shall be. Now that we've settled this, I'm afraid I must tell you that your conclusions are wrong.
`Person` is a *type*.
`name` is a (not very well named) variable to access an *object* of that type.
A whole line of C++ code would look like this:
```
Person name;
```
This means: "create an object of type Person and let me access it via the name variable".
`new Person()` is much more complicated. You may be familiar with the `new` keyword from languages like Java, but in C++, it's a very different beast. It means that a new object of type `Person` is created, but it also means that **you are responsible for destroying it** later on. It also gives you a different kind of handle to the newly created object: a so-called *pointer*. A `Person` pointer looks like this:
```
Person*
```
A pointer is itself a type, and the types `Person*` and `Person` are not compatible. (I told you that this would be much more complicated :))
You will notice the incompatibility when you try to compile the following line:
```
Person name = new Person();
```
It won't compile; you will instead receive an error message. You'd have to do it like this instead:
```
Person* name_ptr = new Person();
```
And then you'd have to access all the members of `Person` with a different syntax:
```
name_ptr->getValue();
name_ptr->callFunction();
```
Finally, remember you must explicitly destroy the object in this case:
```
delete name_ptr;
```
If you forget this, bad things can happen. More precisely, your program will likely use more and more memory the longer it runs.
I think that pointers are too advanced yet for your level of C++ understanding. Stay away from them until you actually need them.
|
It is very simple but very important
Take a general example: what is the general meaning of object? its nothing but which occupies some space right....keep that in mind we now talk about Object in java or C++
example: here I am creating Object **Student std=new Student();**
where **Student** is a **Class** and **std** is a **Object** because we Created a memory for std with the help of **new** keyWord it means it internally occupies some space in memory right thats y we call **std** as **Object**
if you won`t create memory for an object so we call that **object** as **instance**.
example: Student std;
here **Student** is a class and **std** is a instance(means a just a copy that class),with this we won`t do anything untill unless we create a memory for that.
Thats all about object and Instance :)
|
22,206,044 |
I followed a number of posts on SO, and finally I can draw a conclusion that when we
have something like :
```
Person name;
```
`name` is an object of class `person`.
It becomes instance when instantiate it :
```
name=new Person();
```
I am a beginner in C++, and so far I have seen we can access the functions and variables like:
```
Person name;
name.getValue;
name.callFunction();
```
We need not to use `new` operator for this. So can we say the differentiating factor between an object and instance can be ignored in C++?
|
2014/03/05
|
[
"https://Stackoverflow.com/questions/22206044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820722/"
] |
In C++ "object" and "instance" are used nearly interchangably.
There is a general programming design pattern of `class` and `instance`. The `class` holds the information about all `instance`s in that `class`.
In C++ when you declare a `class` or `struct`, the compiler makes code that describes how you create an `instance` of that `class`, what the data layout is, and provides some methods that can be used to interact with that `instance` (up to and including destruction).
`virtual` methods and inheritance seemingly moves some of the methods and layout to the instance: but the amount is quite limited. Instead, each instance holds pointers to `virtual` class data. In some languages, you can do things like replace individual methods of an instance at runtime: but not in C++.
When you create an instance of that `class` or `struct`, it can be via an automatic named variable on the stack (like `Foo f;`), an anonymous automatic named variable (like `some_function( Foo(17,22) )`), an instance on the free store (like `new Foo(17, 22)`), or via placement-`new` (which is how `std::vector` and `std::make_shared` creates instances).
Confusingly, there is a separate parallel `class`-`instance` pattern in C++ -- `class template`-`class`. The `class template` is the `class`, the instantiation is the instance. The `template` arguments and specializations indicate how, at compile time, you can "construct" the `class`es. Pattern matching on the `class template`s provide a limited amount of properties that are not tied to the instances ("class properties" in the pattern). (Arguably the function template-function is another instance of the pattern).
If you look at the [C++1y proposal for concepts lite](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3580.pdf) you will see where object and instance might mean different things in C++.
```
int x = 0;
int& foo = x;
int* bar = &x;
```
`x` is both an object and an instance of the type `int`.
`foo` is an instance of the type `int&`, but calling `foo` an object is probably wrong! It is a reference -- an alias, or a different name for some object (in this case `x`).
`bar` is a pointer to an `int`, which is an instance of type `int*`, and calling it an object is probably correct.
This is a useful distinction: a type does not have to denote an object type if it is a reference type. Object types behave differently than reference types in a number of important ways.
Now, some types have "reference semantics", in that they behave like references in many ways, but are actually `class`es. Are instances of such a type better called references or objects? In horrible cases, some instances have a mixture of both reference and object semantics: such is often a bad sign.
Via [latest standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3580.pdf) in 3.9 [Types] we have the kinds of types in C++. They describe what an *object type* is:
>
> Types describe objects (1.8), references (8.3.2), or functions (8.3.5)
>
>
>
and
>
> An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.
>
>
>
So calling the "instances" of things that are function types or reference types "objects" seems incorrect. Note that accessing the "representation" of a function or a reference instance is basically impossible: references alias into the object they refer to, and using the name of a function decays to a pointers-to-functions at the drop of a hat (and pointers-to-a-function are basically opaque handles that let you invoke them).
So arguably functions are not instances, and references are not instances.
On the third hand, we do talk about instantiations of `class` `template`s and function `template`s. 14.7 is "template instantiation and specialization", and points of instantiation (of a `template`) are all formal terms from the standard.
|
It is very simple but very important
Take a general example: what is the general meaning of object? its nothing but which occupies some space right....keep that in mind we now talk about Object in java or C++
example: here I am creating Object **Student std=new Student();**
where **Student** is a **Class** and **std** is a **Object** because we Created a memory for std with the help of **new** keyWord it means it internally occupies some space in memory right thats y we call **std** as **Object**
if you won`t create memory for an object so we call that **object** as **instance**.
example: Student std;
here **Student** is a class and **std** is a instance(means a just a copy that class),with this we won`t do anything untill unless we create a memory for that.
Thats all about object and Instance :)
|
67,405,791 |
I just updated Android Studio to version 4.2. I was surprised to not see the Gradle tasks in my project.
In the previous version, 4.1.3, I could see the tasks as shown here:
[](https://i.stack.imgur.com/7fhMP.png)
But now I only see the dependencies in version 4.2:
[](https://i.stack.imgur.com/ScuhS.png)
I tried to clear Android Studio's cache and sync my project again, but there was no change.
Is this a feature change?
|
2021/05/05
|
[
"https://Stackoverflow.com/questions/67405791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424400/"
] |
Inside your android studio, select File option in toolbar -> then click on Settings option.
1. From settings, select the last option "Experimental"
2. Within there, select **Uncheck the option** that I have shared the screenshot below.
3. Then click Apply.[](https://i.stack.imgur.com/1sj02.png)
4. After that, Sync your project again from the file option, over their **Sync project with Gradle Files**
All set :)
|
This solution works for me
Go to File -> Settings -> Experimental and uncheck Do not build Gradle task list during Gradle sync, then sync the project File -> Sync Project with Gradle Files.
|
67,405,791 |
I just updated Android Studio to version 4.2. I was surprised to not see the Gradle tasks in my project.
In the previous version, 4.1.3, I could see the tasks as shown here:
[](https://i.stack.imgur.com/7fhMP.png)
But now I only see the dependencies in version 4.2:
[](https://i.stack.imgur.com/ScuhS.png)
I tried to clear Android Studio's cache and sync my project again, but there was no change.
Is this a feature change?
|
2021/05/05
|
[
"https://Stackoverflow.com/questions/67405791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424400/"
] |
**Solution 1:**
You can alternatively use the below gradle command to get all the tasks and run those in terminal
```
./gradlew tasks --all
```
**Solution 2.**
You can also create run configuration to run the tasks like below:
Step 1:
[](https://i.stack.imgur.com/EYUAn.png)
Step 2:
[](https://i.stack.imgur.com/ySify.png)
Step 3:
[](https://i.stack.imgur.com/zrswj.png)
Then your run configuration will be listed like in step 1 image. You can choose and simply run it as usual.
|
This solution works for me
Go to File -> Settings -> Experimental and uncheck Do not build Gradle task list during Gradle sync, then sync the project File -> Sync Project with Gradle Files.
|
67,405,791 |
I just updated Android Studio to version 4.2. I was surprised to not see the Gradle tasks in my project.
In the previous version, 4.1.3, I could see the tasks as shown here:
[](https://i.stack.imgur.com/7fhMP.png)
But now I only see the dependencies in version 4.2:
[](https://i.stack.imgur.com/ScuhS.png)
I tried to clear Android Studio's cache and sync my project again, but there was no change.
Is this a feature change?
|
2021/05/05
|
[
"https://Stackoverflow.com/questions/67405791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424400/"
] |
Go to `File -> Settings -> Experimental` and uncheck `Do not build Gradle task list during Gradle sync`, then sync the project `File -> Sync Project with Gradle Files`. If the problem is still there, just reboot Android Studio.
1.[](https://i.stack.imgur.com/TYDcw.png)
2.
[](https://i.stack.imgur.com/mgURV.png)
|
I had a similar issue and I solved it by executing the following terminal command in my Android Studio Terminal:
```
./gradlew tasks --all
```
|
67,405,791 |
I just updated Android Studio to version 4.2. I was surprised to not see the Gradle tasks in my project.
In the previous version, 4.1.3, I could see the tasks as shown here:
[](https://i.stack.imgur.com/7fhMP.png)
But now I only see the dependencies in version 4.2:
[](https://i.stack.imgur.com/ScuhS.png)
I tried to clear Android Studio's cache and sync my project again, but there was no change.
Is this a feature change?
|
2021/05/05
|
[
"https://Stackoverflow.com/questions/67405791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424400/"
] |
OK, I found why I got this behaviour in android studio 4.2.
It is intended behaviour. I found the answer in this post: <https://issuetracker.google.com/issues/185420705>.
>
> Gradle task list is large and slow to populate in Android projects.
> This feature by default is disabled for performance reasons. You can
> re-enable it in: Settings | Experimental | Do not build Gradle task
> list during Gradle sync.
>
>
>
Reload the Gradle project by clicking the "Sync Project with gradle Files" icon and the tasks will appear.
It could be cool that this experimental change is put in the release note of android studio `4.2`.
[](https://i.stack.imgur.com/ZBmQA.png)
[](https://i.stack.imgur.com/0T3V2.jpg)
|
This solution works for me
Go to File -> Settings -> Experimental and uncheck Do not build Gradle task list during Gradle sync, then sync the project File -> Sync Project with Gradle Files.
|
67,405,791 |
I just updated Android Studio to version 4.2. I was surprised to not see the Gradle tasks in my project.
In the previous version, 4.1.3, I could see the tasks as shown here:
[](https://i.stack.imgur.com/7fhMP.png)
But now I only see the dependencies in version 4.2:
[](https://i.stack.imgur.com/ScuhS.png)
I tried to clear Android Studio's cache and sync my project again, but there was no change.
Is this a feature change?
|
2021/05/05
|
[
"https://Stackoverflow.com/questions/67405791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424400/"
] |
OK, I found why I got this behaviour in android studio 4.2.
It is intended behaviour. I found the answer in this post: <https://issuetracker.google.com/issues/185420705>.
>
> Gradle task list is large and slow to populate in Android projects.
> This feature by default is disabled for performance reasons. You can
> re-enable it in: Settings | Experimental | Do not build Gradle task
> list during Gradle sync.
>
>
>
Reload the Gradle project by clicking the "Sync Project with gradle Files" icon and the tasks will appear.
It could be cool that this experimental change is put in the release note of android studio `4.2`.
[](https://i.stack.imgur.com/ZBmQA.png)
[](https://i.stack.imgur.com/0T3V2.jpg)
|
Go to `File -> Settings -> Experimental` and uncheck `Do not build Gradle task list during Gradle sync`, then sync the project `File -> Sync Project with Gradle Files`. If the problem is still there, just reboot Android Studio.
1.[](https://i.stack.imgur.com/TYDcw.png)
2.
[](https://i.stack.imgur.com/mgURV.png)
|
67,405,791 |
I just updated Android Studio to version 4.2. I was surprised to not see the Gradle tasks in my project.
In the previous version, 4.1.3, I could see the tasks as shown here:
[](https://i.stack.imgur.com/7fhMP.png)
But now I only see the dependencies in version 4.2:
[](https://i.stack.imgur.com/ScuhS.png)
I tried to clear Android Studio's cache and sync my project again, but there was no change.
Is this a feature change?
|
2021/05/05
|
[
"https://Stackoverflow.com/questions/67405791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424400/"
] |
Go to `File -> Settings -> Experimental` and uncheck `Do not build Gradle task list during Gradle sync`, then sync the project `File -> Sync Project with Gradle Files`. If the problem is still there, just reboot Android Studio.
1.[](https://i.stack.imgur.com/TYDcw.png)
2.
[](https://i.stack.imgur.com/mgURV.png)
|
This solution works for me
Go to File -> Settings -> Experimental and uncheck Do not build Gradle task list during Gradle sync, then sync the project File -> Sync Project with Gradle Files.
|
67,405,791 |
I just updated Android Studio to version 4.2. I was surprised to not see the Gradle tasks in my project.
In the previous version, 4.1.3, I could see the tasks as shown here:
[](https://i.stack.imgur.com/7fhMP.png)
But now I only see the dependencies in version 4.2:
[](https://i.stack.imgur.com/ScuhS.png)
I tried to clear Android Studio's cache and sync my project again, but there was no change.
Is this a feature change?
|
2021/05/05
|
[
"https://Stackoverflow.com/questions/67405791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4424400/"
] |
**Solution 1:**
You can alternatively use the below gradle command to get all the tasks and run those in terminal
```
./gradlew tasks --all
```
**Solution 2.**
You can also create run configuration to run the tasks like below:
Step 1:
[](https://i.stack.imgur.com/EYUAn.png)
Step 2:
[](https://i.stack.imgur.com/ySify.png)
Step 3:
[](https://i.stack.imgur.com/zrswj.png)
Then your run configuration will be listed like in step 1 image. You can choose and simply run it as usual.
|
I had a similar issue and I solved it by executing the following terminal command in my Android Studio Terminal:
```
./gradlew tasks --all
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.