qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
18,794,793 | How can I compare a single character from a string, and another string (which may or may not be greater than one character)
This program gives me almost 300 lines of random errors. The errors don't reference a specific line number either, just a lot of stuff about "char\* ", "", or "std::to\_string".
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) { // This line causes the problems
cout << test << endl;
}
return 0;
}
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18794793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1521753/"
] | `str[4]` is a `char` type, which will not compare with a `string`.
Compare apples with apples.
Use
```
test[0] == str[4]
```
instead. | You're mixing types. It doesn't know how to compare a string (`test`) to a char (`str[4]`).
If you change test to a `char` that will work fine. Or reference the specific character within test you want to compare such as `if (test[0] == str[4])` it should compile and run.
However, as this is merely an example and not really the true question what you'll want to do is look at the [functionality](http://en.cppreference.com/w/cpp/string/basic_string) that the `std::string` class supplies |
18,794,793 | How can I compare a single character from a string, and another string (which may or may not be greater than one character)
This program gives me almost 300 lines of random errors. The errors don't reference a specific line number either, just a lot of stuff about "char\* ", "", or "std::to\_string".
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) { // This line causes the problems
cout << test << endl;
}
return 0;
}
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18794793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1521753/"
] | You're comparing a char to a std::string, this is not a valid comparison.
You're looking for std::string::find, as follows:
```
if( test.find( str[4] ) != std::string::npos ) cout << test << "\n";
```
Note that this will return true if test *contains* `str[4]`. | Also you need `"D"` to be a char value not a string value if you are comparing it like that.
```
std::string myString = "Hello World";
const char *myStringChars = myString.c_str();
```
You have to turn it into a char array before can access it. Unless you do.
```
str.at(i);
```
which you can also write as
`str[i]` <-- what you did.
Essentially, this all boils down to test needs to initialized like `char test = 'D';`
Final Output..
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
char test = 'D';
if (test == str[4]) { // This line causes NO problems
cout << test << endl;
}
return 0;
}
``` |
18,794,793 | How can I compare a single character from a string, and another string (which may or may not be greater than one character)
This program gives me almost 300 lines of random errors. The errors don't reference a specific line number either, just a lot of stuff about "char\* ", "", or "std::to\_string".
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) { // This line causes the problems
cout << test << endl;
}
return 0;
}
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18794793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1521753/"
] | You need to convert str[4] (which is a char) to a string before you can compare it to another string. Here's a simple way to do this
```
if (test == string(1, str[4])) {
``` | You're comparing a char to a std::string, this is not a valid comparison.
You're looking for std::string::find, as follows:
```
if( test.find( str[4] ) != std::string::npos ) cout << test << "\n";
```
Note that this will return true if test *contains* `str[4]`. |
18,794,793 | How can I compare a single character from a string, and another string (which may or may not be greater than one character)
This program gives me almost 300 lines of random errors. The errors don't reference a specific line number either, just a lot of stuff about "char\* ", "", or "std::to\_string".
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
string test = "D";
if (test == str[4]) { // This line causes the problems
cout << test << endl;
}
return 0;
}
``` | 2013/09/13 | [
"https://Stackoverflow.com/questions/18794793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1521753/"
] | You need to convert str[4] (which is a char) to a string before you can compare it to another string. Here's a simple way to do this
```
if (test == string(1, str[4])) {
``` | Also you need `"D"` to be a char value not a string value if you are comparing it like that.
```
std::string myString = "Hello World";
const char *myStringChars = myString.c_str();
```
You have to turn it into a char array before can access it. Unless you do.
```
str.at(i);
```
which you can also write as
`str[i]` <-- what you did.
Essentially, this all boils down to test needs to initialized like `char test = 'D';`
Final Output..
```
#include <iostream>
#include <string>
using std::cout;
using std::string;
int main() {
string str = "MDCXIV";
char test = 'D';
if (test == str[4]) { // This line causes NO problems
cout << test << endl;
}
return 0;
}
``` |
30,127 | I've pored over the PHBs, the Rules Compendium, and similar questions at this site and other forums and I'm still confused about how magical weapons enhancements/properties interact with character powers and proficiency. Specifically, I've got two circumstances I need advice on.
**First case**: An invoker in my group has a +1 Staff of Earthen Might. Since her class is proficient with staffs, I know that any implement power she uses this with will apply the +1 to her attack and damage rolls with such powers. I get that.
Am I correct, though, that the +2 proficiency bonus for this staff (as well as the +1d6 critical damage) only applies when she smacks something with the staff as a basic melee attack (which she would qualify for because she is proficient with simple melee weapons)? I want to make sure that these other weapon stats apply to the weapon when used as a weapon only and not when it's used as an implement.
In addition, does anyone that is holding this weapon qualify for the property bonus (+2 to Athletics/Str ability checks when on earth or stone) and the daily action (slowing enemy on hit)? Or do they have to be proficient in staffs as an implement?
**Second case**: We recently got Aecris, the +1 magic longsword from H1 Keep on the Shadowfell. The fighter doesn't want it nor does our halfling barbarian (the fighter has built around bonuses from wielding greataxes and the barbarian is a whirling slayer and benefits from having an off-hand weapon).
However, we have an Eladrin psion in the group that was eyeing it because although she can't use it as an implement, she *is* proficient with longswords (due to her race, not her class), and it would boost her attack modifier for her basic melee attack. In this case, she would get the +3 attack bonus when she stabs with the sword, but she wouldn't get the +1 enhancement bonus to attack and damage rolls, correct? From what I gather, the enhancement bonus is wasted on her since as a psion she's only proficient in staffs and orbs - is that right? Would she qualify for the daily action of gaining a healing surge when dropping an undead enemy to 0 hp without proficiency?
If this is the case, what good is the +1 enhancement bonus on this weapon, then? 'Longswords' aren't listed as an implement proficiency for any class I'm familiar with.
**Edited to summarize what I think my primary questions are:**
* What are the requirements to benefit from a magical weapon's enhancement bonus (i.e. like a weapon that *doesn't* generally double as an implement, like a +1 magic sickle)?
* What are the requirements to have access to the same magical weapon's properties or powers, if any?
* If a character can benefit from a magical weapon's enhancement bonus, what power keyword(s) will this bonus be applied to - 'weapon' or 'implement'?
Thanks in advance! | 2013/11/14 | [
"https://rpg.stackexchange.com/questions/30127",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/9816/"
] | Here are the two things to remember:
* An enhancement bonus is an enhancement bonus is an enhancement bonus.
* Proficiency only applies to `weapon` attacks.
So for your first example, the invoker would get her staff's enhancement bonus (even if it's an enchanted quarterstaff (with a weapon enchantment) rather than an implement enchantment on a staff). She only gets the +2 proficiency bonus if she is using a power with the keyword `weapon` (probably only her Melee Basic, but if she has another weapon power it would apply to this as well).
For your second example, you've got it right. The psion would need at least one feat (multiclass Swordmage) or several (multiclass to any arcane class + Arcane Implement Proficiency) to be able to use it as an implement.
Powers and properties are allowed to be used as long as the wielder is proficient.
Longswords fall into the military category of weapons. If your character is proficient with military weapons he is proficient with the longsword. | **First case**
*An invoker in my group has a +1 Staff of Earthen Might. Since her class is proficient with staffs, I know that any implement power she uses this with will apply the +1 to her attack and damage rolls with such powers. I get that.*
That is correct.
*Am I correct, though, that the +2 proficiency bonus for this staff (as well as the +1d6 critical damage) only applies when she smacks something with the staff as a basic melee attack (which she would qualify for because she is proficient with simple melee weapons)?*
You got the proficiency part right. The critical part, however, also applies on implement attacks.
p. 217 of the rules compendium
>
> Extra Damage: Magic weapons **and implements**, as well as high crit weapons (page 269), can increase the damage dealth on a critical hit by contributing extra damage.
>
>
>
RC p.275 for weapons as implements
>
> When an adventurer uses a magic version of the weapon as an implement,
> he or she can use the magic weapon’s enhancement bonus, **critical hit
> effects**, properties, and powers.
>
>
>
*In addition, does anyone that is holding this weapon qualify for the property bonus (+2 to Athletics/Str ability checks when on earth or stone) and the daily action (slowing enemy on hit)? Or do they have to be proficient in staffs as an implement?*
To be able to use the implements properties (even if used as a weapon), you have to be able to use the staff as an implement.
RC p.275
>
> When an adventurer uses a magic version of the implement as a weapon, he or she can use the magic implement's enhancement bonus and critical hit effects. To use the implement's **properties and powers**, the adventurer must have **proficiency with the implement**.
>
>
>
RC p.274 specifics for staff
>
> This implement also counts as a quaterstaff. Even a creature who **doesn't have proficiency with the staff as an implement** can use it as a weapon, but if the staff is magical, the creature **cannot use its properties or powers**, only its enhancement bonus and critical hit effect.
>
>
>
So only those proficient with the staff **as implement** will be able to use the property (+2 to Athletics/Str ability checks when on earth or stone) and the daily action (slowing enemy on hit).
**Second Case**
*[...] her basic melee attack. In this case, she would get the +3 attack bonus when she stabs with the sword, but she wouldn't get the +1 enhancement bonus to attack and damage rolls, correct?*
Not exactly. For her basic melee attacks, she would add the the proficiency to attack and the +1 enhancement bonus to attack and damage. She would not, however, receive any bonus on her powers that don't have the `[weapon]` keyword, neither proficiency nor enhancement.
>
> Would she qualify for the daily action of gaining a healing surge when
> dropping an undead enemy to 0 hp without proficiency?
>
>
>
She's proficient with the longsword, but not as an implement. Since there are no keywords nor explicit description, the power seems to be usable with any kind of attack, and is not limited to `[weapon]` powers. She can use it after killing an ennemy with one of her non-weapon powers. Still, they should sell it and buy something else, this isn't an interesting weapon for the Psion.
>
> If this is the case, what good is the +1 enhancement bonus on this weapon, then? 'Longswords' aren't listed as an implement proficiency for any class I'm familiar with.
>
>
>
You need implement proficiency with a weapon when you want to use it for an `[implement]` attack. For `[weapon]` attacks (including melee basic attack for instance), the enhancement bonus will work. The bonus is good for anyone using `[weapon]` attacks, but swordmage for instance can use heavy blades as implements aswell. |
30,127 | I've pored over the PHBs, the Rules Compendium, and similar questions at this site and other forums and I'm still confused about how magical weapons enhancements/properties interact with character powers and proficiency. Specifically, I've got two circumstances I need advice on.
**First case**: An invoker in my group has a +1 Staff of Earthen Might. Since her class is proficient with staffs, I know that any implement power she uses this with will apply the +1 to her attack and damage rolls with such powers. I get that.
Am I correct, though, that the +2 proficiency bonus for this staff (as well as the +1d6 critical damage) only applies when she smacks something with the staff as a basic melee attack (which she would qualify for because she is proficient with simple melee weapons)? I want to make sure that these other weapon stats apply to the weapon when used as a weapon only and not when it's used as an implement.
In addition, does anyone that is holding this weapon qualify for the property bonus (+2 to Athletics/Str ability checks when on earth or stone) and the daily action (slowing enemy on hit)? Or do they have to be proficient in staffs as an implement?
**Second case**: We recently got Aecris, the +1 magic longsword from H1 Keep on the Shadowfell. The fighter doesn't want it nor does our halfling barbarian (the fighter has built around bonuses from wielding greataxes and the barbarian is a whirling slayer and benefits from having an off-hand weapon).
However, we have an Eladrin psion in the group that was eyeing it because although she can't use it as an implement, she *is* proficient with longswords (due to her race, not her class), and it would boost her attack modifier for her basic melee attack. In this case, she would get the +3 attack bonus when she stabs with the sword, but she wouldn't get the +1 enhancement bonus to attack and damage rolls, correct? From what I gather, the enhancement bonus is wasted on her since as a psion she's only proficient in staffs and orbs - is that right? Would she qualify for the daily action of gaining a healing surge when dropping an undead enemy to 0 hp without proficiency?
If this is the case, what good is the +1 enhancement bonus on this weapon, then? 'Longswords' aren't listed as an implement proficiency for any class I'm familiar with.
**Edited to summarize what I think my primary questions are:**
* What are the requirements to benefit from a magical weapon's enhancement bonus (i.e. like a weapon that *doesn't* generally double as an implement, like a +1 magic sickle)?
* What are the requirements to have access to the same magical weapon's properties or powers, if any?
* If a character can benefit from a magical weapon's enhancement bonus, what power keyword(s) will this bonus be applied to - 'weapon' or 'implement'?
Thanks in advance! | 2013/11/14 | [
"https://rpg.stackexchange.com/questions/30127",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/9816/"
] | There are three issues here, I think: Keywords, the two different kinds of proficiency, and permission by omission.
But before I go into those, a word: As always there are explicit features/feats/enchantments which break the rules, and that's why we call D&D an "exception-based" system: it deals in rules which apply universally unless (until) exceptions are made, so there is no need to enumerate the possible exceptions. We simply assume the rule unless told otherwise in a particular instance.
Keywords
--------
If a power has the `weapon` keyword, and *only* if the power has the `weapon` keyword, does a weapon enchantment (enhancement bonuses and other features) apply to that power. Ditto with the `implement` keyword and implement enchantments.
Proficiency and the Proficiency Bonus
-------------------------------------
"Proficiency" means that you've had training in the use of a weapon or implement, but mechanically it means totally different things whether you're talking about a weapon or an implement.
### Weapon Proficiency and the Proficiency Bonus
Proficiency with a weapon means that you can add that weapon's "proficiency bonus" to attack rolls. Only weapons have proficiency bonuses, they only apply to powers with the `weapon` keyword, and they have nothing to do with whether enhancement bonuses can be applied (see below for that bit).
### Implements, Enhancement Bonuses, and Permission by Omission
You need to be proficient with an implement in order to add its enhancement bonus to attacks and damage with implement powers. You do *not* need to be proficient with a weapon in order to add its enhancement bonus to attacks and damage with weapon powers, but you don't get its proficiency bonus to the attack roll. (In either case, you can only add the enhancement bonus of one item at a time to an attack unless you have a rules exception which says otherwise.)
I arrived at this conclusion because the magic implement rules say you need to be proficient for the enhancement bonus, but the magic weapon rules don't. Permission by omission is sloppy, but has solid precedent. | Here are the two things to remember:
* An enhancement bonus is an enhancement bonus is an enhancement bonus.
* Proficiency only applies to `weapon` attacks.
So for your first example, the invoker would get her staff's enhancement bonus (even if it's an enchanted quarterstaff (with a weapon enchantment) rather than an implement enchantment on a staff). She only gets the +2 proficiency bonus if she is using a power with the keyword `weapon` (probably only her Melee Basic, but if she has another weapon power it would apply to this as well).
For your second example, you've got it right. The psion would need at least one feat (multiclass Swordmage) or several (multiclass to any arcane class + Arcane Implement Proficiency) to be able to use it as an implement.
Powers and properties are allowed to be used as long as the wielder is proficient.
Longswords fall into the military category of weapons. If your character is proficient with military weapons he is proficient with the longsword. |
30,127 | I've pored over the PHBs, the Rules Compendium, and similar questions at this site and other forums and I'm still confused about how magical weapons enhancements/properties interact with character powers and proficiency. Specifically, I've got two circumstances I need advice on.
**First case**: An invoker in my group has a +1 Staff of Earthen Might. Since her class is proficient with staffs, I know that any implement power she uses this with will apply the +1 to her attack and damage rolls with such powers. I get that.
Am I correct, though, that the +2 proficiency bonus for this staff (as well as the +1d6 critical damage) only applies when she smacks something with the staff as a basic melee attack (which she would qualify for because she is proficient with simple melee weapons)? I want to make sure that these other weapon stats apply to the weapon when used as a weapon only and not when it's used as an implement.
In addition, does anyone that is holding this weapon qualify for the property bonus (+2 to Athletics/Str ability checks when on earth or stone) and the daily action (slowing enemy on hit)? Or do they have to be proficient in staffs as an implement?
**Second case**: We recently got Aecris, the +1 magic longsword from H1 Keep on the Shadowfell. The fighter doesn't want it nor does our halfling barbarian (the fighter has built around bonuses from wielding greataxes and the barbarian is a whirling slayer and benefits from having an off-hand weapon).
However, we have an Eladrin psion in the group that was eyeing it because although she can't use it as an implement, she *is* proficient with longswords (due to her race, not her class), and it would boost her attack modifier for her basic melee attack. In this case, she would get the +3 attack bonus when she stabs with the sword, but she wouldn't get the +1 enhancement bonus to attack and damage rolls, correct? From what I gather, the enhancement bonus is wasted on her since as a psion she's only proficient in staffs and orbs - is that right? Would she qualify for the daily action of gaining a healing surge when dropping an undead enemy to 0 hp without proficiency?
If this is the case, what good is the +1 enhancement bonus on this weapon, then? 'Longswords' aren't listed as an implement proficiency for any class I'm familiar with.
**Edited to summarize what I think my primary questions are:**
* What are the requirements to benefit from a magical weapon's enhancement bonus (i.e. like a weapon that *doesn't* generally double as an implement, like a +1 magic sickle)?
* What are the requirements to have access to the same magical weapon's properties or powers, if any?
* If a character can benefit from a magical weapon's enhancement bonus, what power keyword(s) will this bonus be applied to - 'weapon' or 'implement'?
Thanks in advance! | 2013/11/14 | [
"https://rpg.stackexchange.com/questions/30127",
"https://rpg.stackexchange.com",
"https://rpg.stackexchange.com/users/9816/"
] | There are three issues here, I think: Keywords, the two different kinds of proficiency, and permission by omission.
But before I go into those, a word: As always there are explicit features/feats/enchantments which break the rules, and that's why we call D&D an "exception-based" system: it deals in rules which apply universally unless (until) exceptions are made, so there is no need to enumerate the possible exceptions. We simply assume the rule unless told otherwise in a particular instance.
Keywords
--------
If a power has the `weapon` keyword, and *only* if the power has the `weapon` keyword, does a weapon enchantment (enhancement bonuses and other features) apply to that power. Ditto with the `implement` keyword and implement enchantments.
Proficiency and the Proficiency Bonus
-------------------------------------
"Proficiency" means that you've had training in the use of a weapon or implement, but mechanically it means totally different things whether you're talking about a weapon or an implement.
### Weapon Proficiency and the Proficiency Bonus
Proficiency with a weapon means that you can add that weapon's "proficiency bonus" to attack rolls. Only weapons have proficiency bonuses, they only apply to powers with the `weapon` keyword, and they have nothing to do with whether enhancement bonuses can be applied (see below for that bit).
### Implements, Enhancement Bonuses, and Permission by Omission
You need to be proficient with an implement in order to add its enhancement bonus to attacks and damage with implement powers. You do *not* need to be proficient with a weapon in order to add its enhancement bonus to attacks and damage with weapon powers, but you don't get its proficiency bonus to the attack roll. (In either case, you can only add the enhancement bonus of one item at a time to an attack unless you have a rules exception which says otherwise.)
I arrived at this conclusion because the magic implement rules say you need to be proficient for the enhancement bonus, but the magic weapon rules don't. Permission by omission is sloppy, but has solid precedent. | **First case**
*An invoker in my group has a +1 Staff of Earthen Might. Since her class is proficient with staffs, I know that any implement power she uses this with will apply the +1 to her attack and damage rolls with such powers. I get that.*
That is correct.
*Am I correct, though, that the +2 proficiency bonus for this staff (as well as the +1d6 critical damage) only applies when she smacks something with the staff as a basic melee attack (which she would qualify for because she is proficient with simple melee weapons)?*
You got the proficiency part right. The critical part, however, also applies on implement attacks.
p. 217 of the rules compendium
>
> Extra Damage: Magic weapons **and implements**, as well as high crit weapons (page 269), can increase the damage dealth on a critical hit by contributing extra damage.
>
>
>
RC p.275 for weapons as implements
>
> When an adventurer uses a magic version of the weapon as an implement,
> he or she can use the magic weapon’s enhancement bonus, **critical hit
> effects**, properties, and powers.
>
>
>
*In addition, does anyone that is holding this weapon qualify for the property bonus (+2 to Athletics/Str ability checks when on earth or stone) and the daily action (slowing enemy on hit)? Or do they have to be proficient in staffs as an implement?*
To be able to use the implements properties (even if used as a weapon), you have to be able to use the staff as an implement.
RC p.275
>
> When an adventurer uses a magic version of the implement as a weapon, he or she can use the magic implement's enhancement bonus and critical hit effects. To use the implement's **properties and powers**, the adventurer must have **proficiency with the implement**.
>
>
>
RC p.274 specifics for staff
>
> This implement also counts as a quaterstaff. Even a creature who **doesn't have proficiency with the staff as an implement** can use it as a weapon, but if the staff is magical, the creature **cannot use its properties or powers**, only its enhancement bonus and critical hit effect.
>
>
>
So only those proficient with the staff **as implement** will be able to use the property (+2 to Athletics/Str ability checks when on earth or stone) and the daily action (slowing enemy on hit).
**Second Case**
*[...] her basic melee attack. In this case, she would get the +3 attack bonus when she stabs with the sword, but she wouldn't get the +1 enhancement bonus to attack and damage rolls, correct?*
Not exactly. For her basic melee attacks, she would add the the proficiency to attack and the +1 enhancement bonus to attack and damage. She would not, however, receive any bonus on her powers that don't have the `[weapon]` keyword, neither proficiency nor enhancement.
>
> Would she qualify for the daily action of gaining a healing surge when
> dropping an undead enemy to 0 hp without proficiency?
>
>
>
She's proficient with the longsword, but not as an implement. Since there are no keywords nor explicit description, the power seems to be usable with any kind of attack, and is not limited to `[weapon]` powers. She can use it after killing an ennemy with one of her non-weapon powers. Still, they should sell it and buy something else, this isn't an interesting weapon for the Psion.
>
> If this is the case, what good is the +1 enhancement bonus on this weapon, then? 'Longswords' aren't listed as an implement proficiency for any class I'm familiar with.
>
>
>
You need implement proficiency with a weapon when you want to use it for an `[implement]` attack. For `[weapon]` attacks (including melee basic attack for instance), the enhancement bonus will work. The bonus is good for anyone using `[weapon]` attacks, but swordmage for instance can use heavy blades as implements aswell. |
39,973 | I know the differences between a **rangefinder** and a **SLR/DSLR** but what is the real reason to put a mirror in front of a lens to reflect light into the viewfinder?
It raises lens prooduction price when you put extra distance between lens and sensor. So why do that? Does it improve image quality somehow? Isn't it logical to use rangefinders only? | 2013/06/09 | [
"https://photo.stackexchange.com/questions/39973",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/17818/"
] | Simple, it allows you to see exactly what the camera will "see" when you expose the shot.
Nir has given you a part of the argument as well which is accuracy.
In the "middle ground" of anything around mabye 20-100mm, building a rangefinder is not too difficult and Leica had adapters for longer and wider lenses if I am not mistaken. It takes some effort to calibrate but is doable.
However with an SLR you can use even more extreme focal lengths - try a 7mm or 15mm Fisheye lens, how do you get that into an extra viewfinder (which incidentally needs a similar lens system). Or maybe a 400mm, 800mm lens?
Every system is a compromise somewhere - and using a mirror to reflect the light from the lens to the viewfinder (or focussing screen if one is finicky) allows the user to fully exploit the flexibility that is offered by the range of available lenses.
Coming back to rangefinders, you might have noticed that lenses typically span around 20-135mm and I think there are is at least one lens that offers 17mm on Leicas as well.
The extra distance between the sensor and the lens is itself also not disadvantageous given the way that sensors are designed. Leica's sensor uses a specially shifted micro-lens arrangement to improve the light gathering capability of the sensor. Now whether it works is another discussion, in theory it should.
Moving the lens closer to the sensor means that the light hits the sensor at an oblique angle rather than a near right angle. Given the nature of "light wells" on a sensor, this increases light loss (hence the shifted microlenses on a Leica).
(This is actually the basis for this issue: <http://www.luminous-landscape.com/essays/an_open_letter_to_the_major_camera_manufacturers.shtml> ) | Simple — you can't make an exchangeable lens rangefinder where the viewfinder is even remotely accurate. (Well, you can't without digital technology and live view — and then the mirrorless cameras makes more sense than rangefinders.) |
39,973 | I know the differences between a **rangefinder** and a **SLR/DSLR** but what is the real reason to put a mirror in front of a lens to reflect light into the viewfinder?
It raises lens prooduction price when you put extra distance between lens and sensor. So why do that? Does it improve image quality somehow? Isn't it logical to use rangefinders only? | 2013/06/09 | [
"https://photo.stackexchange.com/questions/39973",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/17818/"
] | Simple, it allows you to see exactly what the camera will "see" when you expose the shot.
Nir has given you a part of the argument as well which is accuracy.
In the "middle ground" of anything around mabye 20-100mm, building a rangefinder is not too difficult and Leica had adapters for longer and wider lenses if I am not mistaken. It takes some effort to calibrate but is doable.
However with an SLR you can use even more extreme focal lengths - try a 7mm or 15mm Fisheye lens, how do you get that into an extra viewfinder (which incidentally needs a similar lens system). Or maybe a 400mm, 800mm lens?
Every system is a compromise somewhere - and using a mirror to reflect the light from the lens to the viewfinder (or focussing screen if one is finicky) allows the user to fully exploit the flexibility that is offered by the range of available lenses.
Coming back to rangefinders, you might have noticed that lenses typically span around 20-135mm and I think there are is at least one lens that offers 17mm on Leicas as well.
The extra distance between the sensor and the lens is itself also not disadvantageous given the way that sensors are designed. Leica's sensor uses a specially shifted micro-lens arrangement to improve the light gathering capability of the sensor. Now whether it works is another discussion, in theory it should.
Moving the lens closer to the sensor means that the light hits the sensor at an oblique angle rather than a near right angle. Given the nature of "light wells" on a sensor, this increases light loss (hence the shifted microlenses on a Leica).
(This is actually the basis for this issue: <http://www.luminous-landscape.com/essays/an_open_letter_to_the_major_camera_manufacturers.shtml> ) | Its tradition. When we had film cameras, a mirror system was used to give the photographer an accurate image of what the lens was seeing irrespective of which lens was attached. Obviously one could have a system with a live viewer. Old time photographers are used to looking in a view finder and composing an image. |
2,862,698 | I'm still learning undergraduate probability. I was asked this probability puzzle in a recent quantitative developer interview. I solved the first part of the question, using brute-force. I think, brute-force very quickly becomes unwieldy for the sequence ending $THH$ - not sure if my answer is correct.
>
> A coin is flipped infinitely until you or I win. If at any point, the last three tosses in the sequence are $HHT$, I win. If at any point, the last three tosses in the sequence are $THH$, you win. Which sequence is more likely?
>
>
>
**Solution.**
$\begin{aligned}
P(xHHT)&=P(H^2T)+P(H^3T)+P(H^4T)+\ldots \\
&=\frac{1}{2^3}+\frac{1}{2^4} + \frac{1}{2^5} + \ldots \\
&=\frac{1/8}{1-1/2}\\
&=\frac{1}{4}
\end{aligned}$
For the second part, $P(xTHH)$, I have drawn a state-diagram, but there are just too many possible combinations for a sequence ending in $THH$. Is there an easier, or perhaps an intuitive way to look at this? Any hints in the right direction would be great! | 2018/07/25 | [
"https://math.stackexchange.com/questions/2862698",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/247892/"
] | Note: the only way you can possibly get $HHT$ before $THH$ is if the first two tosses are $HH$.
Pf: Suppose you get $HHT$ first. Then look at the first occurrence of $HHT$. Go back through the sequence. If you ever encounter a $T$, you must have $THH$ starting with the first $T$ you find. Thus, you can never find a $T$. In particular the first two tosses must both be $H$.
Conversely, if the first two tosses are $HH$ then $THH$ can not come first.
Thus the answer is clearly $\frac 14$. | >
> A coin is flipped infinitely until you or I win. If at any point, the last three tosses in the sequence are $HHT$, I win. If at any point, the last three tosses in the sequence are $THH$, you win. Which sequence is more likely?
>
>
>
Hint: if and only if the first two tosses are $HH$, player 1 wins. In all other cases player two wins. |
36,123,740 | Tensorflow tends to preallocate the entire available memory on it's GPUs. For debugging, is there a way of telling how much of that memory is actually in use? | 2016/03/21 | [
"https://Stackoverflow.com/questions/36123740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349760/"
] | Here's a practical solution that worked well for me:
Disable GPU memory pre-allocation using TF session configuration:
```
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)
```
run **nvidia-smi -l** (or some other utility) to monitor GPU memory consumption.
Step through your code with the debugger until you see the unexpected GPU memory consumption. | The TensorFlow profiler has improved memory timeline that is based on real gpu memory allocator information
<https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler#visualize-time-and-memory> |
36,123,740 | Tensorflow tends to preallocate the entire available memory on it's GPUs. For debugging, is there a way of telling how much of that memory is actually in use? | 2016/03/21 | [
"https://Stackoverflow.com/questions/36123740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349760/"
] | (1) There is some limited support with [Timeline](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/client/timeline.py) for logging memory allocations. Here is an example for its usage:
```
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
summary, _ = sess.run([merged, train_step],
feed_dict=feed_dict(True),
options=run_options,
run_metadata=run_metadata)
train_writer.add_run_metadata(run_metadata, 'step%03d' % i)
train_writer.add_summary(summary, i)
print('Adding run metadata for', i)
tl = timeline.Timeline(run_metadata.step_stats)
print(tl.generate_chrome_trace_format(show_memory=True))
trace_file = tf.gfile.Open(name='timeline', mode='w')
trace_file.write(tl.generate_chrome_trace_format(show_memory=True))
```
You can give this code a try with the MNIST example ([mnist with summaries](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py))
This will generate a tracing file named timeline, which you can open with chrome://tracing. Note that this only gives an approximated GPU memory usage statistics. It basically simulated a GPU execution, but doesn't have access to the full graph metadata. It also can't know how many variables have been assigned to the GPU.
(2) For a very coarse measure of GPU memory usage, nvidia-smi will show the total device memory usage at the time you run the command.
nvprof can show the on-chip shared memory usage and register usage at the CUDA kernel level, but doesn't show the global/device memory usage.
Here is an example command: nvprof --print-gpu-trace matrixMul
And more details here:
<http://docs.nvidia.com/cuda/profiler-users-guide/#abstract> | ```
tf.config.experimental.get_memory_info('GPU:0')
```
Currently returns the following keys:
```
'current': The current memory used by the device, in bytes.
'peak': The peak memory used by the device across the run of the program, in bytes.
``` |
36,123,740 | Tensorflow tends to preallocate the entire available memory on it's GPUs. For debugging, is there a way of telling how much of that memory is actually in use? | 2016/03/21 | [
"https://Stackoverflow.com/questions/36123740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349760/"
] | There's some code in `tensorflow.contrib.memory_stats` that will help with this:
```
from tensorflow.contrib.memory_stats.python.ops.memory_stats_ops import BytesInUse
with tf.device('/device:GPU:0'): # Replace with device you are interested in
bytes_in_use = BytesInUse()
with tf.Session() as sess:
print(sess.run(bytes_in_use))
``` | The TensorFlow profiler has improved memory timeline that is based on real gpu memory allocator information
<https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler#visualize-time-and-memory> |
36,123,740 | Tensorflow tends to preallocate the entire available memory on it's GPUs. For debugging, is there a way of telling how much of that memory is actually in use? | 2016/03/21 | [
"https://Stackoverflow.com/questions/36123740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349760/"
] | (1) There is some limited support with [Timeline](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/client/timeline.py) for logging memory allocations. Here is an example for its usage:
```
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
summary, _ = sess.run([merged, train_step],
feed_dict=feed_dict(True),
options=run_options,
run_metadata=run_metadata)
train_writer.add_run_metadata(run_metadata, 'step%03d' % i)
train_writer.add_summary(summary, i)
print('Adding run metadata for', i)
tl = timeline.Timeline(run_metadata.step_stats)
print(tl.generate_chrome_trace_format(show_memory=True))
trace_file = tf.gfile.Open(name='timeline', mode='w')
trace_file.write(tl.generate_chrome_trace_format(show_memory=True))
```
You can give this code a try with the MNIST example ([mnist with summaries](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py))
This will generate a tracing file named timeline, which you can open with chrome://tracing. Note that this only gives an approximated GPU memory usage statistics. It basically simulated a GPU execution, but doesn't have access to the full graph metadata. It also can't know how many variables have been assigned to the GPU.
(2) For a very coarse measure of GPU memory usage, nvidia-smi will show the total device memory usage at the time you run the command.
nvprof can show the on-chip shared memory usage and register usage at the CUDA kernel level, but doesn't show the global/device memory usage.
Here is an example command: nvprof --print-gpu-trace matrixMul
And more details here:
<http://docs.nvidia.com/cuda/profiler-users-guide/#abstract> | The TensorFlow profiler has improved memory timeline that is based on real gpu memory allocator information
<https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler#visualize-time-and-memory> |
36,123,740 | Tensorflow tends to preallocate the entire available memory on it's GPUs. For debugging, is there a way of telling how much of that memory is actually in use? | 2016/03/21 | [
"https://Stackoverflow.com/questions/36123740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349760/"
] | (1) There is some limited support with [Timeline](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/client/timeline.py) for logging memory allocations. Here is an example for its usage:
```
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
summary, _ = sess.run([merged, train_step],
feed_dict=feed_dict(True),
options=run_options,
run_metadata=run_metadata)
train_writer.add_run_metadata(run_metadata, 'step%03d' % i)
train_writer.add_summary(summary, i)
print('Adding run metadata for', i)
tl = timeline.Timeline(run_metadata.step_stats)
print(tl.generate_chrome_trace_format(show_memory=True))
trace_file = tf.gfile.Open(name='timeline', mode='w')
trace_file.write(tl.generate_chrome_trace_format(show_memory=True))
```
You can give this code a try with the MNIST example ([mnist with summaries](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py))
This will generate a tracing file named timeline, which you can open with chrome://tracing. Note that this only gives an approximated GPU memory usage statistics. It basically simulated a GPU execution, but doesn't have access to the full graph metadata. It also can't know how many variables have been assigned to the GPU.
(2) For a very coarse measure of GPU memory usage, nvidia-smi will show the total device memory usage at the time you run the command.
nvprof can show the on-chip shared memory usage and register usage at the CUDA kernel level, but doesn't show the global/device memory usage.
Here is an example command: nvprof --print-gpu-trace matrixMul
And more details here:
<http://docs.nvidia.com/cuda/profiler-users-guide/#abstract> | Here's a practical solution that worked well for me:
Disable GPU memory pre-allocation using TF session configuration:
```
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)
```
run **nvidia-smi -l** (or some other utility) to monitor GPU memory consumption.
Step through your code with the debugger until you see the unexpected GPU memory consumption. |
36,123,740 | Tensorflow tends to preallocate the entire available memory on it's GPUs. For debugging, is there a way of telling how much of that memory is actually in use? | 2016/03/21 | [
"https://Stackoverflow.com/questions/36123740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349760/"
] | The TensorFlow profiler has improved memory timeline that is based on real gpu memory allocator information
<https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler#visualize-time-and-memory> | as @V.M previously mentioned, a solution that works well is using: `tf.config.experimental.get_memory_info('DEVICE_NAME')`
This function returns a dictionary with two keys:
* **'current'**: The current memory used by the device, in bytes
* **'peak'**: The peak memory used by the device across the run of the program, in bytes.
The value of these keys is the ACTUAL memory used not the allocated one that is returned by nvidia-smi.
In reality, for GPUs, TensorFlow will allocate all the memory by default rendering using **nvidia-smi** to check for the used memory in your code useless. Even if, `tf.config.experimental.set_memory_growth` is set to true, Tensorflow will no more allocate the whole available memory but is going to remain in allocating **more memory than the one is used** and in a **discrete manner**, i.e. allocates 4589MiB then 8717MiB then 16943MiB then 30651 MiB, etc.
A small note concerning the `get_memory_info()` is that it **doesn't return correct values if used in a `tf.function()` decorated function**. Thus, the peak key shall be used after executing `tf.function()` decorated function to determine the peak memory used.
For **older versions** of Tensorflow, `tf.config.experimental.get_memory_usage('DEVICE_NAME')` was the only available function and only returned the used memory (no option for determining the peak memory).
Final note, you can also consider the **Tensorflow Profiler available with Tensorboard** as @Peter Mentioned.
Hope this helps :) |
36,123,740 | Tensorflow tends to preallocate the entire available memory on it's GPUs. For debugging, is there a way of telling how much of that memory is actually in use? | 2016/03/21 | [
"https://Stackoverflow.com/questions/36123740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349760/"
] | Here's a practical solution that worked well for me:
Disable GPU memory pre-allocation using TF session configuration:
```
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)
```
run **nvidia-smi -l** (or some other utility) to monitor GPU memory consumption.
Step through your code with the debugger until you see the unexpected GPU memory consumption. | as @V.M previously mentioned, a solution that works well is using: `tf.config.experimental.get_memory_info('DEVICE_NAME')`
This function returns a dictionary with two keys:
* **'current'**: The current memory used by the device, in bytes
* **'peak'**: The peak memory used by the device across the run of the program, in bytes.
The value of these keys is the ACTUAL memory used not the allocated one that is returned by nvidia-smi.
In reality, for GPUs, TensorFlow will allocate all the memory by default rendering using **nvidia-smi** to check for the used memory in your code useless. Even if, `tf.config.experimental.set_memory_growth` is set to true, Tensorflow will no more allocate the whole available memory but is going to remain in allocating **more memory than the one is used** and in a **discrete manner**, i.e. allocates 4589MiB then 8717MiB then 16943MiB then 30651 MiB, etc.
A small note concerning the `get_memory_info()` is that it **doesn't return correct values if used in a `tf.function()` decorated function**. Thus, the peak key shall be used after executing `tf.function()` decorated function to determine the peak memory used.
For **older versions** of Tensorflow, `tf.config.experimental.get_memory_usage('DEVICE_NAME')` was the only available function and only returned the used memory (no option for determining the peak memory).
Final note, you can also consider the **Tensorflow Profiler available with Tensorboard** as @Peter Mentioned.
Hope this helps :) |
36,123,740 | Tensorflow tends to preallocate the entire available memory on it's GPUs. For debugging, is there a way of telling how much of that memory is actually in use? | 2016/03/21 | [
"https://Stackoverflow.com/questions/36123740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349760/"
] | There's some code in `tensorflow.contrib.memory_stats` that will help with this:
```
from tensorflow.contrib.memory_stats.python.ops.memory_stats_ops import BytesInUse
with tf.device('/device:GPU:0'): # Replace with device you are interested in
bytes_in_use = BytesInUse()
with tf.Session() as sess:
print(sess.run(bytes_in_use))
``` | as @V.M previously mentioned, a solution that works well is using: `tf.config.experimental.get_memory_info('DEVICE_NAME')`
This function returns a dictionary with two keys:
* **'current'**: The current memory used by the device, in bytes
* **'peak'**: The peak memory used by the device across the run of the program, in bytes.
The value of these keys is the ACTUAL memory used not the allocated one that is returned by nvidia-smi.
In reality, for GPUs, TensorFlow will allocate all the memory by default rendering using **nvidia-smi** to check for the used memory in your code useless. Even if, `tf.config.experimental.set_memory_growth` is set to true, Tensorflow will no more allocate the whole available memory but is going to remain in allocating **more memory than the one is used** and in a **discrete manner**, i.e. allocates 4589MiB then 8717MiB then 16943MiB then 30651 MiB, etc.
A small note concerning the `get_memory_info()` is that it **doesn't return correct values if used in a `tf.function()` decorated function**. Thus, the peak key shall be used after executing `tf.function()` decorated function to determine the peak memory used.
For **older versions** of Tensorflow, `tf.config.experimental.get_memory_usage('DEVICE_NAME')` was the only available function and only returned the used memory (no option for determining the peak memory).
Final note, you can also consider the **Tensorflow Profiler available with Tensorboard** as @Peter Mentioned.
Hope this helps :) |
36,123,740 | Tensorflow tends to preallocate the entire available memory on it's GPUs. For debugging, is there a way of telling how much of that memory is actually in use? | 2016/03/21 | [
"https://Stackoverflow.com/questions/36123740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349760/"
] | (1) There is some limited support with [Timeline](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/client/timeline.py) for logging memory allocations. Here is an example for its usage:
```
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
summary, _ = sess.run([merged, train_step],
feed_dict=feed_dict(True),
options=run_options,
run_metadata=run_metadata)
train_writer.add_run_metadata(run_metadata, 'step%03d' % i)
train_writer.add_summary(summary, i)
print('Adding run metadata for', i)
tl = timeline.Timeline(run_metadata.step_stats)
print(tl.generate_chrome_trace_format(show_memory=True))
trace_file = tf.gfile.Open(name='timeline', mode='w')
trace_file.write(tl.generate_chrome_trace_format(show_memory=True))
```
You can give this code a try with the MNIST example ([mnist with summaries](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_with_summaries.py))
This will generate a tracing file named timeline, which you can open with chrome://tracing. Note that this only gives an approximated GPU memory usage statistics. It basically simulated a GPU execution, but doesn't have access to the full graph metadata. It also can't know how many variables have been assigned to the GPU.
(2) For a very coarse measure of GPU memory usage, nvidia-smi will show the total device memory usage at the time you run the command.
nvprof can show the on-chip shared memory usage and register usage at the CUDA kernel level, but doesn't show the global/device memory usage.
Here is an example command: nvprof --print-gpu-trace matrixMul
And more details here:
<http://docs.nvidia.com/cuda/profiler-users-guide/#abstract> | as @V.M previously mentioned, a solution that works well is using: `tf.config.experimental.get_memory_info('DEVICE_NAME')`
This function returns a dictionary with two keys:
* **'current'**: The current memory used by the device, in bytes
* **'peak'**: The peak memory used by the device across the run of the program, in bytes.
The value of these keys is the ACTUAL memory used not the allocated one that is returned by nvidia-smi.
In reality, for GPUs, TensorFlow will allocate all the memory by default rendering using **nvidia-smi** to check for the used memory in your code useless. Even if, `tf.config.experimental.set_memory_growth` is set to true, Tensorflow will no more allocate the whole available memory but is going to remain in allocating **more memory than the one is used** and in a **discrete manner**, i.e. allocates 4589MiB then 8717MiB then 16943MiB then 30651 MiB, etc.
A small note concerning the `get_memory_info()` is that it **doesn't return correct values if used in a `tf.function()` decorated function**. Thus, the peak key shall be used after executing `tf.function()` decorated function to determine the peak memory used.
For **older versions** of Tensorflow, `tf.config.experimental.get_memory_usage('DEVICE_NAME')` was the only available function and only returned the used memory (no option for determining the peak memory).
Final note, you can also consider the **Tensorflow Profiler available with Tensorboard** as @Peter Mentioned.
Hope this helps :) |
36,123,740 | Tensorflow tends to preallocate the entire available memory on it's GPUs. For debugging, is there a way of telling how much of that memory is actually in use? | 2016/03/21 | [
"https://Stackoverflow.com/questions/36123740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349760/"
] | Here's a practical solution that worked well for me:
Disable GPU memory pre-allocation using TF session configuration:
```
config = tf.ConfigProto()
config.gpu_options.allow_growth=True
sess = tf.Session(config=config)
```
run **nvidia-smi -l** (or some other utility) to monitor GPU memory consumption.
Step through your code with the debugger until you see the unexpected GPU memory consumption. | ```
tf.config.experimental.get_memory_info('GPU:0')
```
Currently returns the following keys:
```
'current': The current memory used by the device, in bytes.
'peak': The peak memory used by the device across the run of the program, in bytes.
``` |
36,501,768 | At our .NET front-end we are using ticks to handle time localization and at the database we are storing all values in UTC. Today we came across an odd rounding error when storing records to the database, we are using the following formula to convert Ticks to a datetime.
```
CAST((@ticks - 599266080000000000) / 10000000 / 24 / 60 / 60 AS datetime)
```
It seemed to work fine for most time values we tried until we discovered the following rounding error:
```
DECLARE @ticks bigint = 635953248000000000; -- 2016-04-04 00:00:00.000
SELECT CAST((@Ticks - 599266080000000000) / 10000000 / 24 / 60 / 60 AS datetime)
-- Results in 2016-04-03 23:59:59.997
```
The question is: What is causing this rounding error and what would be the best practice to fix it? | 2016/04/08 | [
"https://Stackoverflow.com/questions/36501768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3048845/"
] | If you capture your calculation in a sql\_variant you can determine what type it is. In your case the calculation uses a numeric type which is not an exact datatype and this is where the rounding is occurring:
```
DECLARE @myVar sql_variant = (@Ticks - 599266080000000000) / 10000000 / 24 / 60 / 60
SELECT SQL_VARIANT_PROPERTY(@myVar,'BaseType') BaseType,
SQL_VARIANT_PROPERTY(@myVar,'Precision') Precisions,
SQL_VARIANT_PROPERTY(@myVar,'Scale') Scale,
SQL_VARIANT_PROPERTY(@myVar,'TotalBytes') TotalBytes,
SQL_VARIANT_PROPERTY(@myVar,'Collation') Collation,
SQL_VARIANT_PROPERTY(@myVar,'MaxLength') MaxLengths
```
which produces the following output:
```
BaseType Precisions Scale TotalBytes Collation MaxLengths
numeric 38 18 17 NULL 13
```
I have found this code which works from [Extended.Net link](http://extendeddotnet.blogspot.co.uk/2011/10/convert-net-datetimeticks-to-t-sql.html)
```
DECLARE @ticks bigint = 635953248000000000
-- First, we will convert the ticks into a datetime value with UTC time
DECLARE @BaseDate datetime;
SET @BaseDate = '01/01/1900';
DECLARE @NetFxTicksFromBaseDate bigint;
SET @NetFxTicksFromBaseDate = @Ticks - 599266080000000000;
-- The numeric constant is the number of .Net Ticks between the System.DateTime.MinValue (01/01/0001) and the SQL Server datetime base date (01/01/1900)
DECLARE @DaysFromBaseDate int;
SET @DaysFromBaseDate = @NetFxTicksFromBaseDate / 864000000000;
-- The numeric constant is the number of .Net Ticks in a single day.
DECLARE @TimeOfDayInTicks bigint;
SET @TimeOfDayInTicks = @NetFxTicksFromBaseDate - @DaysFromBaseDate * 864000000000;
DECLARE @TimeOfDayInMilliseconds int;
SET @TimeOfDayInMilliseconds = @TimeOfDayInTicks / 10000;
-- A Tick equals to 100 nanoseconds which is 0.0001 milliseconds
DECLARE @UtcDate datetime;
SET @UtcDate = DATEADD(ms, @TimeOfDayInMilliseconds, DATEADD(d, @DaysFromBaseDate, @BaseDate));
-- The @UtcDate is already useful. If you need the time in UTC, just return this value.
SELECT @UtcDate;
``` | I found the following works:
```
DECLARE @ticks bigint = 635953248000000000; -- 2016-04-04 00:00:00.000
SELECT DATEADD(s,(@ticks %CONVERT(BIGINT,864000000000))/CONVERT(BIGINT,10000000),DATEADD(d,@ticks /CONVERT(BIGINT,864000000000)-CONVERT(BIGINT,639905),CONVERT(DATETIME,'1/1/1753')))
-- Results in 2016-04-04 00:00:00.000
```
[Source](https://social.msdn.microsoft.com/Forums/en-US/4f119d62-68fd-443e-aa20-3414e42d5f78/converting-bigint-to-datetime2-where-the-value-begin-with-digits-apart-from-1?forum=transactsql)
I couldn't tell you where the rounding error originates though. |
36,501,768 | At our .NET front-end we are using ticks to handle time localization and at the database we are storing all values in UTC. Today we came across an odd rounding error when storing records to the database, we are using the following formula to convert Ticks to a datetime.
```
CAST((@ticks - 599266080000000000) / 10000000 / 24 / 60 / 60 AS datetime)
```
It seemed to work fine for most time values we tried until we discovered the following rounding error:
```
DECLARE @ticks bigint = 635953248000000000; -- 2016-04-04 00:00:00.000
SELECT CAST((@Ticks - 599266080000000000) / 10000000 / 24 / 60 / 60 AS datetime)
-- Results in 2016-04-03 23:59:59.997
```
The question is: What is causing this rounding error and what would be the best practice to fix it? | 2016/04/08 | [
"https://Stackoverflow.com/questions/36501768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3048845/"
] | If you capture your calculation in a sql\_variant you can determine what type it is. In your case the calculation uses a numeric type which is not an exact datatype and this is where the rounding is occurring:
```
DECLARE @myVar sql_variant = (@Ticks - 599266080000000000) / 10000000 / 24 / 60 / 60
SELECT SQL_VARIANT_PROPERTY(@myVar,'BaseType') BaseType,
SQL_VARIANT_PROPERTY(@myVar,'Precision') Precisions,
SQL_VARIANT_PROPERTY(@myVar,'Scale') Scale,
SQL_VARIANT_PROPERTY(@myVar,'TotalBytes') TotalBytes,
SQL_VARIANT_PROPERTY(@myVar,'Collation') Collation,
SQL_VARIANT_PROPERTY(@myVar,'MaxLength') MaxLengths
```
which produces the following output:
```
BaseType Precisions Scale TotalBytes Collation MaxLengths
numeric 38 18 17 NULL 13
```
I have found this code which works from [Extended.Net link](http://extendeddotnet.blogspot.co.uk/2011/10/convert-net-datetimeticks-to-t-sql.html)
```
DECLARE @ticks bigint = 635953248000000000
-- First, we will convert the ticks into a datetime value with UTC time
DECLARE @BaseDate datetime;
SET @BaseDate = '01/01/1900';
DECLARE @NetFxTicksFromBaseDate bigint;
SET @NetFxTicksFromBaseDate = @Ticks - 599266080000000000;
-- The numeric constant is the number of .Net Ticks between the System.DateTime.MinValue (01/01/0001) and the SQL Server datetime base date (01/01/1900)
DECLARE @DaysFromBaseDate int;
SET @DaysFromBaseDate = @NetFxTicksFromBaseDate / 864000000000;
-- The numeric constant is the number of .Net Ticks in a single day.
DECLARE @TimeOfDayInTicks bigint;
SET @TimeOfDayInTicks = @NetFxTicksFromBaseDate - @DaysFromBaseDate * 864000000000;
DECLARE @TimeOfDayInMilliseconds int;
SET @TimeOfDayInMilliseconds = @TimeOfDayInTicks / 10000;
-- A Tick equals to 100 nanoseconds which is 0.0001 milliseconds
DECLARE @UtcDate datetime;
SET @UtcDate = DATEADD(ms, @TimeOfDayInMilliseconds, DATEADD(d, @DaysFromBaseDate, @BaseDate));
-- The @UtcDate is already useful. If you need the time in UTC, just return this value.
SELECT @UtcDate;
``` | The problem comes about because `datetime` does not have the precision to store values down to the millisecond:
>
> datetime values are rounded to increments of .000, .003, or .007 seconds
>
>
>
[Source](https://msdn.microsoft.com/en-gb/library/ms187819.aspx)
Your value comes out as `42462.000000000000000000` which if I convert to a DateTime in C# comes out as 2016-04-03 23:59:59.995 which will get rounded to .997 by SQL. |
66,389 | Let $G$ be an ample $\mathbb{Q}$-divisor on a smooth variety $X$. Let $D$ be a $\mathbb{Q}$-divisor linearly equivalent to $G$. Let $f: Y\to X$ be a common log resolution of $G$ and $D$. We define the multiplier ideal of a divisor $G$ as $I(G)=f\_\*O\_Y(K\_{Y/X}-[f^\*G])$. Are the multiplier ideals $I(G)$ and $I((1-t)G+tD)$ the same for sufficiently small $t>0$? | 2011/05/29 | [
"https://mathoverflow.net/questions/66389",
"https://mathoverflow.net",
"https://mathoverflow.net/users/2348/"
] | I don't think so. Take for example $X=\mathbb{P}^2$, and $G$ and $D$ to be distinct lines.
then $I(G)=\mathcal{O}\_X(-G)$ while $I((1-t)g+tD)=\mathcal{O}\_X$ for every small $t>0$.
Maybe you might want to look at the multiplier ideal associated to the linear series $|G|$. | Think about it this way: The co-support of the multiplier ideal of $G$ is the locus where the pair $(X,G)$ has worse than klt singularities. If $(X,G)$ has non-klt singularities, say because some of its coefficients are at least $1$, and $(X,D)$ is dlt, then some of the small perturbations will likely be still klt, so you get a jump in the multiplier ideal. A simple concrete example for this is given by Gianni Bello in his answer. |
66,389 | Let $G$ be an ample $\mathbb{Q}$-divisor on a smooth variety $X$. Let $D$ be a $\mathbb{Q}$-divisor linearly equivalent to $G$. Let $f: Y\to X$ be a common log resolution of $G$ and $D$. We define the multiplier ideal of a divisor $G$ as $I(G)=f\_\*O\_Y(K\_{Y/X}-[f^\*G])$. Are the multiplier ideals $I(G)$ and $I((1-t)G+tD)$ the same for sufficiently small $t>0$? | 2011/05/29 | [
"https://mathoverflow.net/questions/66389",
"https://mathoverflow.net",
"https://mathoverflow.net/users/2348/"
] | I don't think so. Take for example $X=\mathbb{P}^2$, and $G$ and $D$ to be distinct lines.
then $I(G)=\mathcal{O}\_X(-G)$ while $I((1-t)g+tD)=\mathcal{O}\_X$ for every small $t>0$.
Maybe you might want to look at the multiplier ideal associated to the linear series $|G|$. | However, I should point out that one always has the multiplier ideal containment
$$I((1−t)G+tD) \supseteq I(G)$$ for $t > 0$ sufficiently small.
In particular, the singularities of $(X, (1-t)G + tD)$ can only be epsilon more severe than the singularities of the pair $(X, G)$, thus the multiplier ideal won't get smaller, at least for sufficiently small $t$. Furthermore, they might even be better (in other words, less severe) as Gianni's example shows. |
44,200,737 | I need to remove all occurring patterns except 1, but I haven't been able to get this working in a Bash script.
I tried
```
sed -e 's/ /\\ /g' -e 's/\\ / /1'
```
and
```
sed ':a;s/\([^ ]* .*[^\\]\) \(.*\)/\1\\ \2/;ta'
```
but neither do have the desired effect unfortunately.
Is someone able to help me out?
Thank you in advance! | 2017/05/26 | [
"https://Stackoverflow.com/questions/44200737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7487227/"
] | **Plain Mockito library**
```
import org.mockito.Mock;
...
@Mock
MyService myservice;
```
and
```
import org.mockito.Mockito;
...
MyService myservice = Mockito.mock(MyService.class);
```
come from the Mockito library and are functionally equivalent.
They allow to mock a class or an interface and to record and verify behaviors on it.
The way using annotation is shorter, so preferable and often preferred.
---
Note that to enable Mockito annotations during test executions, the
`MockitoAnnotations.initMocks(this)` static method has to be called.
To avoid side effect between tests, it is advised to do it before each test execution :
```
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
```
Another way to enable Mockito annotations is annotating the test class with `@RunWith` by specifying the `MockitoJUnitRunner` that does this task and also other useful things :
```
@RunWith(org.mockito.runners.MockitoJUnitRunner.class)
public MyClassTest{...}
```
---
**Spring Boot library wrapping Mockito library**
This is indeed a [Spring Boot class](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html):
```
import org.springframework.boot.test.mock.mockito.MockBean;
...
@MockBean
MyService myservice;
```
The class is included in the `spring-boot-test` library.
It allows to add Mockito mocks in a Spring `ApplicationContext`.
If a bean, compatible with the declared class exists in the context, it **replaces** it by the mock.
If it is not the case, it **adds** the mock in the context as a bean.
Javadoc reference :
>
> Annotation that can be used to add mocks to a Spring
> ApplicationContext.
>
>
> ...
>
>
> If any existing single bean of the same type defined in the context
> will be replaced by the mock, if no existing bean is defined a new one
> will be added.
>
>
>
---
**When use classic/plain Mockito and when use `@MockBean` from Spring Boot ?**
Unit tests are designed to test a component in isolation from other components and unit tests have also a requirement : being as fast as possible in terms of execution time as these tests may be executed each day dozen times on the developer machines.
Consequently, here is a simple guideline :
As you write a test that doesn't need any dependencies from the Spring Boot container, the classic/plain Mockito is the way to follow : it is fast and favors the isolation of the tested component.
If your test needs to rely on the Spring Boot container **and** you want also to add or mock one of the container beans : `@MockBean` from Spring Boot is the way.
---
**Typical usage of Spring Boot `@MockBean`**
As we write a test class annotated with `@WebMvcTest` (web test slice).
[The Spring Boot documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests) summarizes that very well :
>
> Often `@WebMvcTest` will be limited to a single controller and used in
> combination with `@MockBean` to provide mock implementations for
> required collaborators.
>
>
>
Here is an example :
```
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@WebMvcTest(FooController.class)
public class FooControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private FooService fooServiceMock;
@Test
public void testExample() throws Exception {
Foo mockedFoo = new Foo("one", "two");
Mockito.when(fooServiceMock.get(1))
.thenReturn(mockedFoo);
mvc.perform(get("foos/1")
.accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk())
.andExpect(content().string("one two"));
}
}
``` | At the end its easy to explain. If you just look into the javadocs of the annotations you will see the differences:
@Mock: (`org.mockito.Mock`)
>
> Mark a field as a mock.
>
>
>
>
> * Allows shorthand mock creation.
> * Minimizes repetitive mock creation code.
> * Makes the test class more readable.
> * Makes the verification error easier to read because the field name is used to identify the mock.
>
>
>
@MockBean: (`org.springframework.boot.test.mock.mockito.MockBean`)
>
> Annotation that can be used to add mocks to a Spring ApplicationContext. Can be used as a class level annotation or on fields in either `@Configuration` classes, or test classes that are `@RunWith` the SpringRunner.
>
>
>
>
> Mocks can be registered by type or by bean name. Any existing single bean of the same type defined in the context will be replaced by the mock, if no existing bean is defined a new one will be added.
>
>
>
>
> When `@MockBean` is used on a field, as well as being registered in the application context, the mock will also be injected into the field.
>
>
>
Mockito.mock()
>
> Its just the representation of a `@Mock`.
>
>
> |
44,200,737 | I need to remove all occurring patterns except 1, but I haven't been able to get this working in a Bash script.
I tried
```
sed -e 's/ /\\ /g' -e 's/\\ / /1'
```
and
```
sed ':a;s/\([^ ]* .*[^\\]\) \(.*\)/\1\\ \2/;ta'
```
but neither do have the desired effect unfortunately.
Is someone able to help me out?
Thank you in advance! | 2017/05/26 | [
"https://Stackoverflow.com/questions/44200737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7487227/"
] | At the end its easy to explain. If you just look into the javadocs of the annotations you will see the differences:
@Mock: (`org.mockito.Mock`)
>
> Mark a field as a mock.
>
>
>
>
> * Allows shorthand mock creation.
> * Minimizes repetitive mock creation code.
> * Makes the test class more readable.
> * Makes the verification error easier to read because the field name is used to identify the mock.
>
>
>
@MockBean: (`org.springframework.boot.test.mock.mockito.MockBean`)
>
> Annotation that can be used to add mocks to a Spring ApplicationContext. Can be used as a class level annotation or on fields in either `@Configuration` classes, or test classes that are `@RunWith` the SpringRunner.
>
>
>
>
> Mocks can be registered by type or by bean name. Any existing single bean of the same type defined in the context will be replaced by the mock, if no existing bean is defined a new one will be added.
>
>
>
>
> When `@MockBean` is used on a field, as well as being registered in the application context, the mock will also be injected into the field.
>
>
>
Mockito.mock()
>
> Its just the representation of a `@Mock`.
>
>
> | Mocktio.mock() :-
1. Will create a mock object of either class or interface. We can use
this mock to stub the return values and verify if they are called.
2. We must use the `when(..)` and `thenReturn(..)` methods for mock objects
whose class methods will be invoked during test case execution.
`@Mock` :-
1. This is shorthand for `mock()` method so it is preferable and often
used.
2. Both `mock()` and `@Mock` are functionally equivalent.
3. Easier to identify the problem in mock failure as name of the field appears in the error message.
To enable the Mockito annotation during test execution we need to call the `MockitoAnnotations.initMocks(this)` method but this method is deprecated instead we can call - `MockitoAnnotations.openMocks(this)`. In order to avoid the side effects it is advised to call this method before test case executions.
Another way to enable the Mockito annotations is by annotating the test class with `@RunWith` by specifying the MockitoJUnitRunner that does this task and also other useful things.
`@MockBean` :-
It is used to add the mock objects into spring application context.
This mock will replace the existing bean of same type in application
context. If no bean is available, then new bean will be added. This
is useful in integration test case.
When we write a test case that doesn't need any dependencies from the Spring Boot container, the classic/plain Mockito is used and it is fast and favors the isolation of the tested component.
If our test case needs to rely on the Spring Boot container and want to add or mock one of the container beans then `@MockBean` is used. |
44,200,737 | I need to remove all occurring patterns except 1, but I haven't been able to get this working in a Bash script.
I tried
```
sed -e 's/ /\\ /g' -e 's/\\ / /1'
```
and
```
sed ':a;s/\([^ ]* .*[^\\]\) \(.*\)/\1\\ \2/;ta'
```
but neither do have the desired effect unfortunately.
Is someone able to help me out?
Thank you in advance! | 2017/05/26 | [
"https://Stackoverflow.com/questions/44200737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7487227/"
] | **Plain Mockito library**
```
import org.mockito.Mock;
...
@Mock
MyService myservice;
```
and
```
import org.mockito.Mockito;
...
MyService myservice = Mockito.mock(MyService.class);
```
come from the Mockito library and are functionally equivalent.
They allow to mock a class or an interface and to record and verify behaviors on it.
The way using annotation is shorter, so preferable and often preferred.
---
Note that to enable Mockito annotations during test executions, the
`MockitoAnnotations.initMocks(this)` static method has to be called.
To avoid side effect between tests, it is advised to do it before each test execution :
```
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
```
Another way to enable Mockito annotations is annotating the test class with `@RunWith` by specifying the `MockitoJUnitRunner` that does this task and also other useful things :
```
@RunWith(org.mockito.runners.MockitoJUnitRunner.class)
public MyClassTest{...}
```
---
**Spring Boot library wrapping Mockito library**
This is indeed a [Spring Boot class](https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html):
```
import org.springframework.boot.test.mock.mockito.MockBean;
...
@MockBean
MyService myservice;
```
The class is included in the `spring-boot-test` library.
It allows to add Mockito mocks in a Spring `ApplicationContext`.
If a bean, compatible with the declared class exists in the context, it **replaces** it by the mock.
If it is not the case, it **adds** the mock in the context as a bean.
Javadoc reference :
>
> Annotation that can be used to add mocks to a Spring
> ApplicationContext.
>
>
> ...
>
>
> If any existing single bean of the same type defined in the context
> will be replaced by the mock, if no existing bean is defined a new one
> will be added.
>
>
>
---
**When use classic/plain Mockito and when use `@MockBean` from Spring Boot ?**
Unit tests are designed to test a component in isolation from other components and unit tests have also a requirement : being as fast as possible in terms of execution time as these tests may be executed each day dozen times on the developer machines.
Consequently, here is a simple guideline :
As you write a test that doesn't need any dependencies from the Spring Boot container, the classic/plain Mockito is the way to follow : it is fast and favors the isolation of the tested component.
If your test needs to rely on the Spring Boot container **and** you want also to add or mock one of the container beans : `@MockBean` from Spring Boot is the way.
---
**Typical usage of Spring Boot `@MockBean`**
As we write a test class annotated with `@WebMvcTest` (web test slice).
[The Spring Boot documentation](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests) summarizes that very well :
>
> Often `@WebMvcTest` will be limited to a single controller and used in
> combination with `@MockBean` to provide mock implementations for
> required collaborators.
>
>
>
Here is an example :
```
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@WebMvcTest(FooController.class)
public class FooControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private FooService fooServiceMock;
@Test
public void testExample() throws Exception {
Foo mockedFoo = new Foo("one", "two");
Mockito.when(fooServiceMock.get(1))
.thenReturn(mockedFoo);
mvc.perform(get("foos/1")
.accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk())
.andExpect(content().string("one two"));
}
}
``` | Mocktio.mock() :-
1. Will create a mock object of either class or interface. We can use
this mock to stub the return values and verify if they are called.
2. We must use the `when(..)` and `thenReturn(..)` methods for mock objects
whose class methods will be invoked during test case execution.
`@Mock` :-
1. This is shorthand for `mock()` method so it is preferable and often
used.
2. Both `mock()` and `@Mock` are functionally equivalent.
3. Easier to identify the problem in mock failure as name of the field appears in the error message.
To enable the Mockito annotation during test execution we need to call the `MockitoAnnotations.initMocks(this)` method but this method is deprecated instead we can call - `MockitoAnnotations.openMocks(this)`. In order to avoid the side effects it is advised to call this method before test case executions.
Another way to enable the Mockito annotations is by annotating the test class with `@RunWith` by specifying the MockitoJUnitRunner that does this task and also other useful things.
`@MockBean` :-
It is used to add the mock objects into spring application context.
This mock will replace the existing bean of same type in application
context. If no bean is available, then new bean will be added. This
is useful in integration test case.
When we write a test case that doesn't need any dependencies from the Spring Boot container, the classic/plain Mockito is used and it is fast and favors the isolation of the tested component.
If our test case needs to rely on the Spring Boot container and want to add or mock one of the container beans then `@MockBean` is used. |
28,022,091 | I never wrote any complex regular expression before, and what I need seems to be (at least) a bit complicated.
I need a Regex to find matches for the following:
```
"On Fri, Jan 16, 2015 at 4:39 PM"
```
Where `On` will always be there;
then 3 characters for week day;
`,` is always there;
space is always there;
then 3 characters for month name;
space is always there;
day of month (one or two numbers);
`,` is always there;
space is always there;
4 numbers for year;
space `at` space always there;
time (have to match `4:39` as well as `10:39`);
space and 2 caps letters for `AM` or `PM`. | 2015/01/19 | [
"https://Stackoverflow.com/questions/28022091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772830/"
] | You could try the below regex and it won't check for the month name or day name or date.
```
^On\s[A-Z][a-z]{2},\s[A-Z][a-z]{2}\s\d{1,2},\s\d{4}\sat\s(?:10|4):39\s[AP]M$
```
[DEMO](http://www.rubular.com/r/yQcktbdo8t) | You can use [Rubular](http://rubular.com) to construct and test Ruby Regular Expressions.
I have put together an Example: <http://rubular.com/r/45RIiwheqs>
Since it looks you try to parse dates, you should use [Date.strptime](http://ruby-doc.org/stdlib-2.2.0/libdoc/date/rdoc/Date.html#method-c-strptime). |
28,022,091 | I never wrote any complex regular expression before, and what I need seems to be (at least) a bit complicated.
I need a Regex to find matches for the following:
```
"On Fri, Jan 16, 2015 at 4:39 PM"
```
Where `On` will always be there;
then 3 characters for week day;
`,` is always there;
space is always there;
then 3 characters for month name;
space is always there;
day of month (one or two numbers);
`,` is always there;
space is always there;
4 numbers for year;
space `at` space always there;
time (have to match `4:39` as well as `10:39`);
space and 2 caps letters for `AM` or `PM`. | 2015/01/19 | [
"https://Stackoverflow.com/questions/28022091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772830/"
] | Try this:
```
On\s+(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (?:Jan|Feb|Mar|Apr|May|June|July|Aug|Sept|Oct|Nov|Dec) \d{1,2}, \d{4} at \d{1,2}:\d{2} (?:AM|PM)
```
 | /On [A-Za-z]{3}, [A-Za-z]{3} \d{1,2}, \d{4} at \d{1,2}:\d{1,2}/g |
28,022,091 | I never wrote any complex regular expression before, and what I need seems to be (at least) a bit complicated.
I need a Regex to find matches for the following:
```
"On Fri, Jan 16, 2015 at 4:39 PM"
```
Where `On` will always be there;
then 3 characters for week day;
`,` is always there;
space is always there;
then 3 characters for month name;
space is always there;
day of month (one or two numbers);
`,` is always there;
space is always there;
4 numbers for year;
space `at` space always there;
time (have to match `4:39` as well as `10:39`);
space and 2 caps letters for `AM` or `PM`. | 2015/01/19 | [
"https://Stackoverflow.com/questions/28022091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772830/"
] | Try this:
```
On\s+(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (?:Jan|Feb|Mar|Apr|May|June|July|Aug|Sept|Oct|Nov|Dec) \d{1,2}, \d{4} at \d{1,2}:\d{2} (?:AM|PM)
```
 | ```
/On \w{3}, \w{3} \d{1,2}, \d{4} at \d{1,2}:\d{1,2} [A-Z]{2}/
# \w{3} for 3 charecters
# \d{1,2} for a or 2 digits
# \d{4} for 4 digits
# [A-Z]{2} for 2 capital leters
``` |
28,022,091 | I never wrote any complex regular expression before, and what I need seems to be (at least) a bit complicated.
I need a Regex to find matches for the following:
```
"On Fri, Jan 16, 2015 at 4:39 PM"
```
Where `On` will always be there;
then 3 characters for week day;
`,` is always there;
space is always there;
then 3 characters for month name;
space is always there;
day of month (one or two numbers);
`,` is always there;
space is always there;
4 numbers for year;
space `at` space always there;
time (have to match `4:39` as well as `10:39`);
space and 2 caps letters for `AM` or `PM`. | 2015/01/19 | [
"https://Stackoverflow.com/questions/28022091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772830/"
] | ```
/On \w{3}, \w{3} \d{1,2}, \d{4} at \d{1,2}:\d{1,2} [A-Z]{2}/
# \w{3} for 3 charecters
# \d{1,2} for a or 2 digits
# \d{4} for 4 digits
# [A-Z]{2} for 2 capital leters
``` | You can use [Rubular](http://rubular.com) to construct and test Ruby Regular Expressions.
I have put together an Example: <http://rubular.com/r/45RIiwheqs>
Since it looks you try to parse dates, you should use [Date.strptime](http://ruby-doc.org/stdlib-2.2.0/libdoc/date/rdoc/Date.html#method-c-strptime). |
28,022,091 | I never wrote any complex regular expression before, and what I need seems to be (at least) a bit complicated.
I need a Regex to find matches for the following:
```
"On Fri, Jan 16, 2015 at 4:39 PM"
```
Where `On` will always be there;
then 3 characters for week day;
`,` is always there;
space is always there;
then 3 characters for month name;
space is always there;
day of month (one or two numbers);
`,` is always there;
space is always there;
4 numbers for year;
space `at` space always there;
time (have to match `4:39` as well as `10:39`);
space and 2 caps letters for `AM` or `PM`. | 2015/01/19 | [
"https://Stackoverflow.com/questions/28022091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772830/"
] | You could try the below regex and it won't check for the month name or day name or date.
```
^On\s[A-Z][a-z]{2},\s[A-Z][a-z]{2}\s\d{1,2},\s\d{4}\sat\s(?:10|4):39\s[AP]M$
```
[DEMO](http://www.rubular.com/r/yQcktbdo8t) | The way you are describing the problem makes me thing that the format will always be preserved.
I would then in your case use the `Time.parse` function, passing the format string
```
format = "On %a, %b"On Fri, Jan 16, 2015 at 4:39 PM", format)
```
which is more readable than a regexp (in my opinion) and has the added value that it returns a `Time` object, which is easier to use than a regexp match, in case you need to perform other time-based calculations.
Another good thing is that if the string contains an invalid date (like "On Mon, Jan 59, 2015 at 37:99 GX" ) the `parse` function will raise an exception, so that validation is done for free for you. |
28,022,091 | I never wrote any complex regular expression before, and what I need seems to be (at least) a bit complicated.
I need a Regex to find matches for the following:
```
"On Fri, Jan 16, 2015 at 4:39 PM"
```
Where `On` will always be there;
then 3 characters for week day;
`,` is always there;
space is always there;
then 3 characters for month name;
space is always there;
day of month (one or two numbers);
`,` is always there;
space is always there;
4 numbers for year;
space `at` space always there;
time (have to match `4:39` as well as `10:39`);
space and 2 caps letters for `AM` or `PM`. | 2015/01/19 | [
"https://Stackoverflow.com/questions/28022091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772830/"
] | ```
/On \w{3}, \w{3} \d{1,2}, \d{4} at \d{1,2}:\d{1,2} [A-Z]{2}/
# \w{3} for 3 charecters
# \d{1,2} for a or 2 digits
# \d{4} for 4 digits
# [A-Z]{2} for 2 capital leters
``` | The way you are describing the problem makes me thing that the format will always be preserved.
I would then in your case use the `Time.parse` function, passing the format string
```
format = "On %a, %b"On Fri, Jan 16, 2015 at 4:39 PM", format)
```
which is more readable than a regexp (in my opinion) and has the added value that it returns a `Time` object, which is easier to use than a regexp match, in case you need to perform other time-based calculations.
Another good thing is that if the string contains an invalid date (like "On Mon, Jan 59, 2015 at 37:99 GX" ) the `parse` function will raise an exception, so that validation is done for free for you. |
28,022,091 | I never wrote any complex regular expression before, and what I need seems to be (at least) a bit complicated.
I need a Regex to find matches for the following:
```
"On Fri, Jan 16, 2015 at 4:39 PM"
```
Where `On` will always be there;
then 3 characters for week day;
`,` is always there;
space is always there;
then 3 characters for month name;
space is always there;
day of month (one or two numbers);
`,` is always there;
space is always there;
4 numbers for year;
space `at` space always there;
time (have to match `4:39` as well as `10:39`);
space and 2 caps letters for `AM` or `PM`. | 2015/01/19 | [
"https://Stackoverflow.com/questions/28022091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772830/"
] | Here's a very simple and readable one:
```
/On \w{3}, \w{3} \d{1,2}, \d{4} at \d{1,2}:\d{2} [AP]M/
```
[See it on rubular](http://rubular.com/r/CxkKy6h4Y9) | The way you are describing the problem makes me thing that the format will always be preserved.
I would then in your case use the `Time.parse` function, passing the format string
```
format = "On %a, %b"On Fri, Jan 16, 2015 at 4:39 PM", format)
```
which is more readable than a regexp (in my opinion) and has the added value that it returns a `Time` object, which is easier to use than a regexp match, in case you need to perform other time-based calculations.
Another good thing is that if the string contains an invalid date (like "On Mon, Jan 59, 2015 at 37:99 GX" ) the `parse` function will raise an exception, so that validation is done for free for you. |
28,022,091 | I never wrote any complex regular expression before, and what I need seems to be (at least) a bit complicated.
I need a Regex to find matches for the following:
```
"On Fri, Jan 16, 2015 at 4:39 PM"
```
Where `On` will always be there;
then 3 characters for week day;
`,` is always there;
space is always there;
then 3 characters for month name;
space is always there;
day of month (one or two numbers);
`,` is always there;
space is always there;
4 numbers for year;
space `at` space always there;
time (have to match `4:39` as well as `10:39`);
space and 2 caps letters for `AM` or `PM`. | 2015/01/19 | [
"https://Stackoverflow.com/questions/28022091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772830/"
] | ```
/On \w{3}, \w{3} \d{1,2}, \d{4} at \d{1,2}:\d{1,2} [A-Z]{2}/
# \w{3} for 3 charecters
# \d{1,2} for a or 2 digits
# \d{4} for 4 digits
# [A-Z]{2} for 2 capital leters
``` | /On [A-Za-z]{3}, [A-Za-z]{3} \d{1,2}, \d{4} at \d{1,2}:\d{1,2}/g |
28,022,091 | I never wrote any complex regular expression before, and what I need seems to be (at least) a bit complicated.
I need a Regex to find matches for the following:
```
"On Fri, Jan 16, 2015 at 4:39 PM"
```
Where `On` will always be there;
then 3 characters for week day;
`,` is always there;
space is always there;
then 3 characters for month name;
space is always there;
day of month (one or two numbers);
`,` is always there;
space is always there;
4 numbers for year;
space `at` space always there;
time (have to match `4:39` as well as `10:39`);
space and 2 caps letters for `AM` or `PM`. | 2015/01/19 | [
"https://Stackoverflow.com/questions/28022091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772830/"
] | You could try the below regex and it won't check for the month name or day name or date.
```
^On\s[A-Z][a-z]{2},\s[A-Z][a-z]{2}\s\d{1,2},\s\d{4}\sat\s(?:10|4):39\s[AP]M$
```
[DEMO](http://www.rubular.com/r/yQcktbdo8t) | /On [A-Za-z]{3}, [A-Za-z]{3} \d{1,2}, \d{4} at \d{1,2}:\d{1,2}/g |
28,022,091 | I never wrote any complex regular expression before, and what I need seems to be (at least) a bit complicated.
I need a Regex to find matches for the following:
```
"On Fri, Jan 16, 2015 at 4:39 PM"
```
Where `On` will always be there;
then 3 characters for week day;
`,` is always there;
space is always there;
then 3 characters for month name;
space is always there;
day of month (one or two numbers);
`,` is always there;
space is always there;
4 numbers for year;
space `at` space always there;
time (have to match `4:39` as well as `10:39`);
space and 2 caps letters for `AM` or `PM`. | 2015/01/19 | [
"https://Stackoverflow.com/questions/28022091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1772830/"
] | Try this:
```
On\s+(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (?:Jan|Feb|Mar|Apr|May|June|July|Aug|Sept|Oct|Nov|Dec) \d{1,2}, \d{4} at \d{1,2}:\d{2} (?:AM|PM)
```
 | You can use [Rubular](http://rubular.com) to construct and test Ruby Regular Expressions.
I have put together an Example: <http://rubular.com/r/45RIiwheqs>
Since it looks you try to parse dates, you should use [Date.strptime](http://ruby-doc.org/stdlib-2.2.0/libdoc/date/rdoc/Date.html#method-c-strptime). |
24,283 | Reading Matthew 12:26
If Satan drives out Satan, he is divided against himself. How then can his kingdom stand?
I cant seem to pin point where is his kingdom? Evil men dont seem to be united? | 2013/12/31 | [
"https://christianity.stackexchange.com/questions/24283",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/6506/"
] | Let's take a long look at the Scriptures around your referenced Scripture:
Matthew 12:25 through 28 KJV
>
> 25 And Jesus knew their thoughts, and said unto them, Every kingdom divided against itself is brought to desolation; and every city or house divided against itself shall not stand:
>
>
> 26 And if Satan cast out Satan, he is divided against himself; how shall then his kingdom stand?
>
>
> 27 And if I by Beelzebub cast out devils, by whom do your children cast them out? therefore they shall be your judges.
>
>
> 28 But if I cast out devils by the Spirit of God, then the kingdom of God is come unto you.
>
>
>
and see if Jesus was actually saying that Satan had a Kingdom to begin with. What Jesus was retorting to was the verse preceding this retort (Matthew 12:24):
But when the Pharisees heard it, they said, This fellow doth not cast out devils, but by Beelzebub the prince of the devils.
Jesus was incensed by their claim that he was getting his power to do these miracles from Satan, and his angry retort was meant to marginalize them.
In verses 26 and 27 He is belittling them by:
1. saying that If Satan is ruining his own plans, If He had a Kingdom by fighting against himself he would be destroying his own Kingdom.
2. Jesus is saying and if as you say I am getting my power from Satan, where are your people getting their power from?
The last stone he casts is in verse 28 where he tells them knowing what I have just told you my power must come from another source. and if my source is God then you have just seen the Kingdom of God.
Here are some other Scriptures concerning Satan's supposed power which you may find will help you in understanding Satan. Please remember that Jesus himself said that Satan was a liar and the father of lies.
Matthew 4:1-11 KJV
>
> Again, the devil taketh him up into an exceeding high mountain, and sheweth him all the kingdoms of the world, and the glory of them; And saith unto him, All these things will I give thee, if thou wilt fall down and worship me.
>
>
>
Mark 3:22-26 KJV
>
> And the scribes which came down from Jerusalem said, He hath Beelzebub, and by the prince of the devils casteth he out devils. And he called them [unto him], and said unto them in parables, How can Satan cast out Satan? And if a kingdom be divided against itself, that kingdom cannot stand. And if a house be divided against itself, that house cannot stand. And if Satan rise up against himself, and be divided, he cannot stand, but hath an end.
>
>
>
In This Scripture what Jesus is pointing to is that if what they were claiming were true then Satan does not have the power of God since he could not do what they claimed and be eternal.
Revelation 2:13 KJV
>
> I know thy works, and where thou dwellest, [even] where Satan's seat [is]: and thou holdest fast my name, and hast not denied my faith, even in those days wherein Antipas [was] my faithful martyr, who was slain among you, where Satan dwelleth.
>
>
>
Revelation 12:9-12 KJV
>
> Therefore rejoice, [ye] heavens, and ye that dwell in them. Woe to the inhabiters of the earth and of the sea! for the devil is come down unto you, having great wrath, because he knoweth that he hath but a short time.
>
>
>
Revelation 3:9 KJV
>
> Behold, I will make them of the synagogue of Satan, which say they are Jews, and are not, but do lie; behold, I will make them to come and worship before thy feet, and to know that I have loved thee.
>
>
>
Revelation 12:9-12 KJV
>
> Therefore rejoice, [ye] heavens, and ye that dwell in them. Woe to the inhabiters of the earth and of the sea! for the devil is come down unto you, having great wrath, because he knoweth that he hath but a short time.
>
>
> | I see three questions plus the question in the quote.
**Is Satan's kingdom here on earth?** Yes, the adversary is here on earth. He was cast out when Jesus was "snatched up to God and to his throne" (Rev 12:5). Most likely his "Ascension into Heaven" (Acts 1:9-11) but possibly at his death on the Cross.
**I cant seem to pin point where is his kingdom?** Opposing the spirit is the Flesh (Gal 5:17) Therefore when serving the Flesh we also serve Satan. "..you are slaves of the one you obey.." (Romans 6:14-19).
These two questions work together.
**Evil men dont seem to be united?**
"**If Satan drives out Satan, he is divided against himself. How then can his kingdom stand?**" -Matthew 12:26
Singular: If a man hates himself and actively pursues damage to himself. How can he stay alive?
Married Couple: If the couple actively pursue damage to the relationship. How can the relationship survive? |
24,283 | Reading Matthew 12:26
If Satan drives out Satan, he is divided against himself. How then can his kingdom stand?
I cant seem to pin point where is his kingdom? Evil men dont seem to be united? | 2013/12/31 | [
"https://christianity.stackexchange.com/questions/24283",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/6506/"
] | Let's take a long look at the Scriptures around your referenced Scripture:
Matthew 12:25 through 28 KJV
>
> 25 And Jesus knew their thoughts, and said unto them, Every kingdom divided against itself is brought to desolation; and every city or house divided against itself shall not stand:
>
>
> 26 And if Satan cast out Satan, he is divided against himself; how shall then his kingdom stand?
>
>
> 27 And if I by Beelzebub cast out devils, by whom do your children cast them out? therefore they shall be your judges.
>
>
> 28 But if I cast out devils by the Spirit of God, then the kingdom of God is come unto you.
>
>
>
and see if Jesus was actually saying that Satan had a Kingdom to begin with. What Jesus was retorting to was the verse preceding this retort (Matthew 12:24):
But when the Pharisees heard it, they said, This fellow doth not cast out devils, but by Beelzebub the prince of the devils.
Jesus was incensed by their claim that he was getting his power to do these miracles from Satan, and his angry retort was meant to marginalize them.
In verses 26 and 27 He is belittling them by:
1. saying that If Satan is ruining his own plans, If He had a Kingdom by fighting against himself he would be destroying his own Kingdom.
2. Jesus is saying and if as you say I am getting my power from Satan, where are your people getting their power from?
The last stone he casts is in verse 28 where he tells them knowing what I have just told you my power must come from another source. and if my source is God then you have just seen the Kingdom of God.
Here are some other Scriptures concerning Satan's supposed power which you may find will help you in understanding Satan. Please remember that Jesus himself said that Satan was a liar and the father of lies.
Matthew 4:1-11 KJV
>
> Again, the devil taketh him up into an exceeding high mountain, and sheweth him all the kingdoms of the world, and the glory of them; And saith unto him, All these things will I give thee, if thou wilt fall down and worship me.
>
>
>
Mark 3:22-26 KJV
>
> And the scribes which came down from Jerusalem said, He hath Beelzebub, and by the prince of the devils casteth he out devils. And he called them [unto him], and said unto them in parables, How can Satan cast out Satan? And if a kingdom be divided against itself, that kingdom cannot stand. And if a house be divided against itself, that house cannot stand. And if Satan rise up against himself, and be divided, he cannot stand, but hath an end.
>
>
>
In This Scripture what Jesus is pointing to is that if what they were claiming were true then Satan does not have the power of God since he could not do what they claimed and be eternal.
Revelation 2:13 KJV
>
> I know thy works, and where thou dwellest, [even] where Satan's seat [is]: and thou holdest fast my name, and hast not denied my faith, even in those days wherein Antipas [was] my faithful martyr, who was slain among you, where Satan dwelleth.
>
>
>
Revelation 12:9-12 KJV
>
> Therefore rejoice, [ye] heavens, and ye that dwell in them. Woe to the inhabiters of the earth and of the sea! for the devil is come down unto you, having great wrath, because he knoweth that he hath but a short time.
>
>
>
Revelation 3:9 KJV
>
> Behold, I will make them of the synagogue of Satan, which say they are Jews, and are not, but do lie; behold, I will make them to come and worship before thy feet, and to know that I have loved thee.
>
>
>
Revelation 12:9-12 KJV
>
> Therefore rejoice, [ye] heavens, and ye that dwell in them. Woe to the inhabiters of the earth and of the sea! for the devil is come down unto you, having great wrath, because he knoweth that he hath but a short time.
>
>
> | This question is about spiritual world. How it is reflected within humanity? How it manifests? How a spiritual world stands?
To understand how a man can become evil man, or a good man, I will quote from Holy Tradition of Orthodoxy, where many mysteries about humanity and God where revealed to us through Holy Spirit and His servants. (<http://tzarlazar.tripod.com>)
>
> [CHAPTER FOUR](http://tzarlazar.tripod.com/lazar04.htm) ...Man is wondrously composed of body, soul, and
> spirit. The spirit is the mover and the lord of the whole of man's
> being. As the spirit is, so will the movements of the soul and body
> be. As the spirit is, so also is the man. The spirit moves the soul,
> and the soul the body. 'It is the spirit that gives life, the flesh is
> of no avail.' (John 6). Even the circles of the angelic host in the
> heavenly kingdom live and are moved only by the Spirit of God. From
> that Spirit there springs forth for us angels those four streams of
> sweetness: truth, love, life, and joy. In this same manner the
> progenitor of your race also lived and was moved by the Spirit of God,
> similar to us angels.
>
>
> "When, however, he insanely departed from righteousness and heavenly
> Love, a fundamental transformation took place in him. In appearance he
> remained the same; nevertheless an essential change occurred within
> him. To this day little is known in the world about this
> transformation. It is one of the strangest, quietest, most consecrated
> mysteries. The fundamental transformation lay in this: the insulted
> Creator pulled His Holy Spirit out of man, and left man alone with his
> created soul and natural spirit. With this natural spirit, which is
> created and not inspired by God, fallen man was condemned "to eat
> bread in the sweat of his face" (Gen. 3), like the ants and the
> bees and the beasts. Thus man degenerated into an animal, the lord
> became the peer of his servants, the king became equal to his
> subjects. Man the god became man the animal. But this is not the worst
> part. For the animals are in their own state wondrous and beautiful.
> What is the worst part is that man the animal quickly tumbled down
> into man the demon, of his own free will. Of his own free will, after
> having exchanged the Holy Spirit for an unclean vessel, he also threw
> away his natural, created spirit and accepted into himself a third
> spirit — the unclean spirit, the spirit of falling away from God and
> struggling against God, the spirit of the angels of hell. For when man
> lost the Holy Spirit, he was placed at a crossroads, where his natural
> created spirit is in control, and where two opposite spirits meet: the
> spirit of light and the spirit of darkness, the Spirit of God and the
> spirit of hell.
> "At this crossroads, where the natural spirit is in control and where the two opposing spirits are blowing, many people turn their
> face to the spirit of darkness and death, while there are only a few
> who turn their face toward God. To these latter our gracious God has
> again given His Holy Spirit. These are those amazing righteous people,
> to whom the promise and the prophesied salvation have been given. As
> it has been given to them so also will it be given through them to
> every future generation of mankind, so long as it remains on the
> crossroads facing towards the God of life.
> "For thousands of years they have been the only man-gods in the midst of the man-animals and, what is worse, man-demons. They have
> been called gods and sons of God, not because of their mortal flesh or
> their natural soul and spirit, but because of the Holy Spirit of God,
> which has been given to them again, and because at the crossroads of
> the spirits their face has been turned, with faith and reverence,
> towards the Holy Spirit of God. Because of this God has breathed His
> Spirit from Himself into them, and thus they have been made worthy to
> be called gods and sons of God. ...
>
>
>
With this understanding we can pin point how the kingdom of Satan stands.
As an example think about 2 men driven by the same evil spirit. They maybe want to hurt themselves or to kill each other, in appearance they are not united but in spirit they are the similar, exercising the same activity. They are bearers of the same evil spirit, and they potentially contaminate with the same spirit people around them which they contact to .. the hate, the greedy, the deprivation, the anger, the proud etc are manifestations of the same evil spirit.
When you observe this around you and inside you, over and over, you can realize in which Kingdom you or people around you are living and how this Kingdom stands. |
23,032,889 | i need help, i am trying to replicate this kind of progress indicator, but i can't figure it out.
What i want:
[](https://i.stack.imgur.com/d0Ypc.png)
What i have: <http://jsfiddle.net/AQWdM/>
```css
body {
font-family: 'Segoe UI';
font-size: 13px;
}
ul.progress li.active {
background-color: #dc9305;
}
ul.progress li {
background-color: #7e7e7e;
}
ul.progress {
list-style: none;
margin: 0;
padding: 0;
}
ul.progress li {
float: left;
line-height: 20px;
height: 20px;
min-width: 130px;
position: relative;
}
ul.progress li:after {
content: '';
position: absolute;
width: 0;
height: 0;
right: 4px;
border-style: solid;
border-width: 10px 0 10px 10px;
border-color: transparent transparent transparent #7e7e7e;
}
ul.progress li:before {
content: '';
position: absolute;
width: 0;
height: 0;
right: 0px;
border-style: solid;
border-width: 10px 0 10px 10px;
border-color: transparent transparent transparent #fff;
}
ul.progress li.beforeactive:before {
background-color: #dc9305;
}
ul.progress li.active:before {
background-color: #7e7e7e;
}
ul.progress li.active:after {
border-color: transparent transparent transparent #dc9305;
}
ul.progress li:last-child:after,
ul.progress li:last-child:before {
border: 0;
}
ul.progress li a {
padding: 0px 0px 0px 6px;
color: #FFF;
text-decoration: none;
}
```
```html
<ul class="progress">
<li><a href="">Qualify</a></li>
<li class="beforeactive"><a href="">Develop</a></li>
<li class="active"><a href="">Propose</a></li>
<li><a href="">Close</a></li>
</ul>
```
First, my example has "beforeactive" class - i would like to avoid this, so i can just mark item as active. Also, arrows on my example are not best set up - on image where is what i want, it has better set up arrows (the are more thick at starting).
I need your help to:
1.) Create better css, clearly i am not good at css, so not to require beforeactive class, also to properly color backgrounds, and to be optimized - there can be hundrets of this lists per page
2.) Create arrow to match the one on the design i want to have
3.) It needs to be dynamic, since sometimes it will be small, somtimes it will be large, it needs to be able to cope with different font sizes (maybe use em or percentage - i used px just to test stuff)
4.) IF - AND ONLY IF IS POSSIBLE SIMPLE WAY - to make it for example whole long 600px; and current active one is longest, others have fixed size, and the active one always fills up the rest of it. So if first is active, it takes 400px, and rest fill in 200px, when we activate second, to animate making others size down, and second one size up. I use jquery, so it's ok to use his anymations, but i prefer css animations (there will be thousands of lines of javascript code - so i try to use javascript as little as possible for ui)
Thank you | 2014/04/12 | [
"https://Stackoverflow.com/questions/23032889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3527152/"
] | You should use one pseudo rotated element and draw it on the far left side. *the first will be out of sight, so no need to worry about last `li`, set `overflow` on `ul` to hide `overflow`ing parts :).*
**[DEMO](http://codepen.io/gc-nomade/pen/FnKim/)** and CSS
```css
body {
font-family: 'Segoe UI';
font-size: 13px;
}
ul.progress li.active {
background-color: #dc9305;
}
ul.progress li {
background-color: #7e7e7e;
position: relative;
text-indent: 0.5em;
}
ul.progress li:after {
content: '';
position: absolute;
right: 100%;
margin-right: 0.4em;
width: 1.2em;
padding-top: 1.2em;
;
border: solid white;
z-index: 1;
transform: rotate(45deg);
border-bottom: 0;
border-left: 0;
box-shadow: 5px -5px 0 3px #7e7e7e
}
ul.progress li.active:after {
box-shadow: 6px -6px 0 3px #dc9305;
}
ul.progress {
list-style: none;
margin:2px 0;
padding: 0;
overflow: hidden;
min-width:max-content;
}
ul.progress li {
float: left;
line-height: 20px;
height: 20px;
min-width: 130px;
position: relative;
transition: min-width 0.5s;
}
ul.progress li a {
padding: 0px 0px 0px 6px;
color: #FFF;
text-decoration: none;
}
ul.progress li:hover {
min-width: 300px;
}
ul.progress li:before {
content: '\2714'
}
ul.progress li.active:before,
ul.progress li.active~li:before {
content: ''
}
```
```html
<ul class="progress">
<li class="active"><a href="">Qualify</a></li>
<li><a href="">Develop</a></li>
<li><a href="">Propose</a></li>
<li><a href="">Close</a></li>
</ul>
<ul class="progress">
<li><a href="">Qualify</a></li>
<li class="active"><a href="">Develop</a></li>
<li><a href="">Propose</a></li>
<li><a href="">Close</a></li>
</ul>
<ul class="progress">
<li><a href="">Qualify</a></li>
<li><a href="">Develop</a></li>
<li class="active"><a href="">Propose</a></li>
<li><a href="">Close</a></li>
</ul>
<ul class="progress">
<li><a href="">Qualify</a></li>
<li><a href="">Develop</a></li>
<li><a href="">Propose</a></li>
<li class="active"><a href="">Close</a></li>
</ul>
```
---
Do not forget to add vendor-prefix or use a script to care of it.
---
over `li` to see them grow with `transition`, check marks added too via CSS to `li` ahead `.active` class | [Check this out](http://jsfiddle.net/8D2Ss/1/)
Please check this and see is this what you were looking for
```
<ul class="progress">
<li><a href="">✔ Qualify</a></li>
<li class="beforeactive"><a href=""> ✔ Develop</a></li>
<li class="active"><a href="">Propose</a></li>
<li><a href="">Close</a></li>
</ul>
```
Css
```
body {
font-family: 'Segoe UI';
font-size: 13px;
}
ul.progress li.active {
background-color: #dc9305;
}
ul.progress li {
background-color: #7e7e7e;
}
ul.progress {
list-style: none;
margin: 0;
padding: 0;
}
ul.progress li {
float: left;
line-height: 20px;
height: 20px;
min-width: 130px;
position: relative;
}
ul.progress li:after {
content: '';
position: absolute;
width: 0;
height: 0;
right: 4px;
border-style: solid;
border-width: 10px 0 10px 10px;
border-color: transparent transparent transparent #7e7e7e;
}
ul.progress li:before {
content: '';
position: absolute;
width: 0;
height: 0;
right: 0px;
border-style: solid;
border-width: 10px 0 10px 10px;
border-color: transparent transparent transparent #fff;
}
ul.progress li.beforeactive:before {
background-color: #dc9305;
}
ul.progress li.active:before {
background-color: #7e7e7e;
}
ul.progress li.active:after {
border-color: transparent transparent transparent #dc9305;
}
ul.progress li:last-child:after,
ul.progress li:last-child:before {
border: 0;
}
ul.progress li a {
padding: 0px 0px 0px 6px;
color: #FFF;
text-decoration: none;
}
ul.progress li:hover {
min-width:300px;
}
```
Output
------
 |
16,214,205 | Lets say, I have Product and Score tables.
```
Product
-------
id
name
Score
-----
id
ProductId
ScoreValue
```
I want to get the top 10 Products with the highest AVERAGE scores, how do I get the average and select the top 10 products in one select statement?
here is mine which selects unexpected rows
```
SELECT TOP 10 Product.ProductName Score.Score
FROM Product, Score
WHERE Product.ID IN (select top 100 productid
from score
group by productid
order by sum(score) desc)
order by Score.Score desc
``` | 2013/04/25 | [
"https://Stackoverflow.com/questions/16214205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2091346/"
] | Give this a try,
```
WITH records
AS
(
SELECT a.ID, a.Name, AVG(b.ScoreValue) avg_score,
DENSE_RANK() OVER (ORDER BY AVG(b.ScoreValue) DESC) rn
FROM Product a
INNER JOIN Score b
ON a.ID = b.ProductID
GROUP BY a.ID, a.Name
)
SELECT ID, Name, Avg_Score
FROM records
WHERE rn <= 10
ORDER BY avg_score DESC
```
The reason why I am not using `TOP` is because it will not handle duplicate record having the highest average. But you can use `TOP WITH TIES` instead. | Please try:
```
declare @Product as table (id int, name nvarchar(20))
declare @Score as table (id int, ProductID int, ScoreValue decimal(23, 5))
insert into @Product values (1, 'a'), (2, 'b'), (3, 'c')
insert into @Score values (1, 1, 25), (2, 1, 30), (3, 2, 40), (4, 2, 45), (5, 3, 3)
select
distinct top 2 name,
ProductID,
AVG(ScoreValue) over (partition by name)
from @Product a inner join @Score b on a.id=b.ProductID
order by 3 desc
```
Change with your table name and number of rows accordingly. |
16,214,205 | Lets say, I have Product and Score tables.
```
Product
-------
id
name
Score
-----
id
ProductId
ScoreValue
```
I want to get the top 10 Products with the highest AVERAGE scores, how do I get the average and select the top 10 products in one select statement?
here is mine which selects unexpected rows
```
SELECT TOP 10 Product.ProductName Score.Score
FROM Product, Score
WHERE Product.ID IN (select top 100 productid
from score
group by productid
order by sum(score) desc)
order by Score.Score desc
``` | 2013/04/25 | [
"https://Stackoverflow.com/questions/16214205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2091346/"
] | Give this a try,
```
WITH records
AS
(
SELECT a.ID, a.Name, AVG(b.ScoreValue) avg_score,
DENSE_RANK() OVER (ORDER BY AVG(b.ScoreValue) DESC) rn
FROM Product a
INNER JOIN Score b
ON a.ID = b.ProductID
GROUP BY a.ID, a.Name
)
SELECT ID, Name, Avg_Score
FROM records
WHERE rn <= 10
ORDER BY avg_score DESC
```
The reason why I am not using `TOP` is because it will not handle duplicate record having the highest average. But you can use `TOP WITH TIES` instead. | This might do it
```
SELECT TOP 10 p.ProductName, avg( s.Score ) as avg_score
FROM Product p
inner join Score s on s.product_id = p.product_id
group by p.ProductName, p.product_id
order by avg_score desc
``` |
27,470,505 | I'm using webapi2 and Castle Windsor. I'm trying to intercept calls to the ApiController to make some logging, but I can't find in the parameter the method called, url, parameters, etc. The method name returned is ExecuteAsync.
This is my interceptor call (which is hit)
```
public class LoggingInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var methodName = invocation.Method.Name;
invocation.Proceed();
}
}
``` | 2014/12/14 | [
"https://Stackoverflow.com/questions/27470505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/723059/"
] | ```
if (invocation.Method.Name == "ExecuteAsync")
{
var ctx = (HttpControllerContext) invocation.Arguments[0];
Console.WriteLine("Controller name: {0}", ctx.ControllerDescriptor.ControllerName);
Console.WriteLine("Request Uri: {0}", ctx.Request.RequestUri);
}
invocation.Proceed();
```
Intercepting the ExecuteAsync call, you can get access to the HttpControllerContext but not the HttpActionContext, which contains details about the actual controller action method being invoked. (As far as I can tell this is only available to an ActionFilter).
Therefore the detail about the request is limited: for instance, deserialized parameters are not available using this technique.
If you wish, you can make your controller action methods `virtual` and these will then also be intercepted, and you can then access the actual action parameters via `invocation.arguments`. However, in your interceptor you will need to somehow differentiate the action methods that you wish to log, from the other methods that get called on the controller (i.e. `Intialize()`, `Dispose()`, `ExecuteAsync()`, `Ok()`, etc.) | While using ASP.NET MVC framework is possible to get the action caller from LoginInterceptor (check [this link](https://cangencer.wordpress.com/2011/06/02/asp-net-mvc-3-aspect-oriented-programming-with-castle-interceptors/)), in ASP.NET Web Api I haven't found a proper way to achieve it using interceptors with Castle Windsor.
By the other hand, I have found a way to achive what you are trying to do, taking advantage of `Caller Info Attributes` and Castle Windsor `LoggingFacility` component.
**Caller Info Attributes**
These attributes are
* [CallerMemberName] - Sets the information about caller member name.
* [CallerFilePath] - Sets the information about caller's source code
file.
* [CallerLineNumber] - Sets the information about caller's line number.
And you can use them this way (as optional parameters):
```
public static void ShowCallerInfo([CallerMemberName]
string callerName = null, [CallerFilePath] string
callerFilePath = null, [CallerLineNumber] int callerLine=-1)
{
Console.WriteLine("Caller Name: {0}", callerName);
Console.WriteLine("Caller FilePath: {0}", callerFilePath);
Console.WriteLine("Caller Line number: {0}", callerLine);
}
```
Calling `ShowCallerInfo();` method (without parameters) displays:
```
Caller Name: Main
Caller FilePath: h:\ConsoleApplication1\ConsoleApplication1\ConsoleApplication1\Class1.cs
Caller Line number: 7
```
**LoggingFacility**
Castle Windsor provides the `LoggingFacility` component as an alternative for Logging (using injection instead of interception), that allows logging inside your methods, not only after and before (allowed with interceptors).
Just registering your Logger this way:
```
container.AddFacility<LoggingFacility>(f => f.UseNLog().WithConfig("NLog.config"));
```
Automatically injects an ILogger object that can use in your code.
```
public class MyController : ApiController
{
public ILogger Logger { get; set; }
[HttpGet]
public IHttpActionResult Get()
{
Logger.Info("Log Test");
…
}
...
}
```
Check this [link](http://docs.castleproject.org/Windsor.Logging-Facility.ashx) and this [link](http://docs.castleproject.org/Windsor.Windsor-Tutorial-Part-Five-Adding-logging-support.ashx) for more info.
**Example**
So, as an example, you can mix both features to achieve Logging in controller actions this way:
```
public class MyController : ApiController
{
// Make Logger optional
private ILogger logger = NullLogger.Instance;
public ILogger Logger
{
get { return logger; }
set { logger = value; }
}
[HttpGet]
public IHttpActionResult Get()
{
loggerError("Error");
...
return Ok();
}
....
public void loggerError(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Logger.Error(message +
" - Caller Name: " + memberName
+ " - Caller FilePath: " + sourceFilePath
+ " - Line number: " + sourceLineNumber
);
}
...
}
``` |
207,341 | Assume this city is relatively large by late medieval standards, around 200,000 people. The city is mainly a site for trade due to its geographically central position and being on a river. Also, because it is geographically central, it also means the city is important for the government to project power.
**What might be the benefits for this same government to sanction certain crime within this important trade city?**
Crime that would be considered legal within city limits ranges from murder, burglary, trade of illicit substances, and racketeering. This is all under the condition that the crime does not directly affect the government's activities. | 2021/07/17 | [
"https://worldbuilding.stackexchange.com/questions/207341",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/43517/"
] | ### To punish them.
Looking at your situation from a modern lens - Politicians love spending money on those who voted for them, and also those who could be plausibly convinced to vote for them. They don't like spending money on those who voted strongly against them. Dishing out favour in this way is known as [pork barreling](https://en.wikipedia.org/wiki/Pork_barrel).
So there's a town where people didn't vote for you / send enough tax money to you / support you in a recent coup / send enough virgins to your harem / whatever spited you. You can show your disaproval by screwing them over at the next chance you get. Maybe their tax rate is raised, or maybe they get less resources allocated.
You can also send them a message by withdrawing or reducing the police. The safety of that community is less of a concern for you if you want to teach them a lesson - they're not going to vote for you / support you / etc, why should you waste resources on them?
Perhaps after a few months of crime running out of control they'll learn their place and they'll be better subjects next time. | Instead of government-sanctioned crime, what about a small area with a different government or no government? It could be an independent city where three or more large countries meet, and none of the countries can take it over because the others wouldn't let them. This also gives a good explanation for why there would be lots of devious machinations going on by various government agents in the city, and it would be a prosperous trade hub if it is the best route between those nations. |
207,341 | Assume this city is relatively large by late medieval standards, around 200,000 people. The city is mainly a site for trade due to its geographically central position and being on a river. Also, because it is geographically central, it also means the city is important for the government to project power.
**What might be the benefits for this same government to sanction certain crime within this important trade city?**
Crime that would be considered legal within city limits ranges from murder, burglary, trade of illicit substances, and racketeering. This is all under the condition that the crime does not directly affect the government's activities. | 2021/07/17 | [
"https://worldbuilding.stackexchange.com/questions/207341",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/43517/"
] | I wonder if you have a too modern view of the state -- by the people, for the people. Over much of history it was by *some* people, for *some* people.
* **Illicit substances**
Very much in the eye of the beholder. In much of the West, alcohol is legal (and taxed) and cannabis is not. Say you have strong merchant guilds interested in the trade in those substances, and they might have gained permission to do so. Also consider the [Opium Wars](https://en.wikipedia.org/wiki/Opium_Wars).
* **Racketeering**
Just who is exploited, and how? Look at the rise of firefighters in [ancient Rome](https://en.wikipedia.org/wiki/Marcus_Licinius_Crassus#Rise_to_power_and_wealth). Early on they were for-profit companies who charged whatever the market would bear when a house was on fire. Or take a medieval craft guild, regulating prices, quality and competition and making sure that guild masters had a decent living.
* Special case: **Tax farming**
The government sold the right to [collect taxes](https://en.wikipedia.org/wiki/Farm_(revenue_leasing)). The interests who paid a hefty sum now try to squeeze money out of the city to cover their costs and make a profit on top. Not everybody is allowed to racketeer, but from the perspective of the victims some rackets are legal.
* **Burglary**
This one is difficult. When it is made legal, powerful factions like the merchants and guilds mentioned above must guard their properties without the help of a city watch. But do you know the proverb *only the rich can afford a weak government?* Say burglary is not legal, the rules against it are simply not enforced by the government. That is left to merchants and shop-keepers, who form associations (see *racketeering*) to employ guards and [thief-takers](https://en.wikipedia.org/wiki/Thief-taker).
* **Murder**
As above, making it a kind of *civil* offense requiring [weregild](https://en.wikipedia.org/wiki/Weregild) if the relatives of the victim are strong enough to insist. | Instead of government-sanctioned crime, what about a small area with a different government or no government? It could be an independent city where three or more large countries meet, and none of the countries can take it over because the others wouldn't let them. This also gives a good explanation for why there would be lots of devious machinations going on by various government agents in the city, and it would be a prosperous trade hub if it is the best route between those nations. |
207,341 | Assume this city is relatively large by late medieval standards, around 200,000 people. The city is mainly a site for trade due to its geographically central position and being on a river. Also, because it is geographically central, it also means the city is important for the government to project power.
**What might be the benefits for this same government to sanction certain crime within this important trade city?**
Crime that would be considered legal within city limits ranges from murder, burglary, trade of illicit substances, and racketeering. This is all under the condition that the crime does not directly affect the government's activities. | 2021/07/17 | [
"https://worldbuilding.stackexchange.com/questions/207341",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/43517/"
] | Nonsense. If something is allowed by the law, then it is not a crime. The very definition of a crime is breaking the law.
The proper question would be why the law in this city is more lenient than elsewhere. Consider for example the US, which is probably the country with the most legally heterogeneous country in the world. In some places you can walk around with an assault rifle or drive a tank. Do it in other places and it's jail for you. Why? Because different places have different populations with different world views, and the government at federal level does not want or cannot interfere. | Hollywood will show you many - prolly dozens - of stories in which "governments" sanction crime for their own devious ends… most often to justify increasing the security budget or beefing up security powers.
That and any other Answer uses "government" in a rather loose sense. Even in today's Communist China and the historical USSR, it's almost unthinkable that an entire government would collectively go your way.
May we assume the Question is really about agencies, branches or departments, or rogue agents within them? |
207,341 | Assume this city is relatively large by late medieval standards, around 200,000 people. The city is mainly a site for trade due to its geographically central position and being on a river. Also, because it is geographically central, it also means the city is important for the government to project power.
**What might be the benefits for this same government to sanction certain crime within this important trade city?**
Crime that would be considered legal within city limits ranges from murder, burglary, trade of illicit substances, and racketeering. This is all under the condition that the crime does not directly affect the government's activities. | 2021/07/17 | [
"https://worldbuilding.stackexchange.com/questions/207341",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/43517/"
] | I wonder if you have a too modern view of the state -- by the people, for the people. Over much of history it was by *some* people, for *some* people.
* **Illicit substances**
Very much in the eye of the beholder. In much of the West, alcohol is legal (and taxed) and cannabis is not. Say you have strong merchant guilds interested in the trade in those substances, and they might have gained permission to do so. Also consider the [Opium Wars](https://en.wikipedia.org/wiki/Opium_Wars).
* **Racketeering**
Just who is exploited, and how? Look at the rise of firefighters in [ancient Rome](https://en.wikipedia.org/wiki/Marcus_Licinius_Crassus#Rise_to_power_and_wealth). Early on they were for-profit companies who charged whatever the market would bear when a house was on fire. Or take a medieval craft guild, regulating prices, quality and competition and making sure that guild masters had a decent living.
* Special case: **Tax farming**
The government sold the right to [collect taxes](https://en.wikipedia.org/wiki/Farm_(revenue_leasing)). The interests who paid a hefty sum now try to squeeze money out of the city to cover their costs and make a profit on top. Not everybody is allowed to racketeer, but from the perspective of the victims some rackets are legal.
* **Burglary**
This one is difficult. When it is made legal, powerful factions like the merchants and guilds mentioned above must guard their properties without the help of a city watch. But do you know the proverb *only the rich can afford a weak government?* Say burglary is not legal, the rules against it are simply not enforced by the government. That is left to merchants and shop-keepers, who form associations (see *racketeering*) to employ guards and [thief-takers](https://en.wikipedia.org/wiki/Thief-taker).
* **Murder**
As above, making it a kind of *civil* offense requiring [weregild](https://en.wikipedia.org/wiki/Weregild) if the relatives of the victim are strong enough to insist. | >
> What might be the benefits for [a] government to sanction certain crime within [an] important trade city?
>
>
>
There are already excellent answers to this question, but to add some more real world details that have been overlooked:
### Strengthening Colonial Rule
The most famous real-world example is [**Hong Kong**](http://en.wikipedia.org/wiki/Hong_Kong). In order **(a)** to **facilitate illicit trade** in opium and other products, **(b)** to **enjoy an additional local spy network** in a large and hostile neighbor, and most importantly **(c)** to **maintain a semblance of order** over a large population whose language few of the colonial administration spoke, the Brits maintained deals with the [Triads](http://en.wikipedia.org/wiki/Triad_(organized_crime)) to essentially outsource most public order over the Chinese slums to powerful criminals. [The "tea money" *hongbao*](https://www.cinemaescapist.com/2018/04/chasing-dragon-critique-british-corruption-colonial-hong-kong/) provided by the gangs were also prime sources of income for the colonial police. Things were periodically shut down or renegotiated, as after the [1956 Double Ten Riots](http://en.wikipedia.org/wiki/1956_Hong_Kong_riots), but the Triads were so entrenched that [even the PRC were forced into deals with them during the handover](https://academic.oup.com/bjc/article-abstract/50/5/851/463592) and has only been slowly chipping away at them since, usually [when they start messing around on the mainland](https://www.chinasmack.com/large-hong-kong-triad-gathering-in-shenzhen-raided-by-police). There are tons of books, TV shows, and movies about this era but lots of them are in Cantonese. To bring the same idea closer to home, [*The Shield*](http://en.wikipedia.org/wiki/The_Shield) dramatizes the [LAPD](http://en.wikipedia.org/wiki/Los_Angeles_Police_Department)'s similar accommodation of crime as a way of handling the endemic mess in the poorer neighborhoods of [**Los Angeles**](http://en.wikipedia.org/wiki/Los_Angeles). Essentially, apart from enriching themselves, the Farmington police are shown choosing their battles, angling for local black and hispanic criminal leaders who keep the violence and crime away from better (and whiter) neighborhoods and away from directly harming the local children or the police themselves.
### Handling Temporary Emergencies
In [**New York City**](http://en.wikipedia.org/wiki/New_York_City) during World War II, [the US gov't made common cause with the mafia](https://historycollection.com/10-undeniable-ties-united-states-government-organized-crime/7/) in part to get a better spy network in the leadup to the invasion of Sicily but also to maintain control over longshoreman and other important labor unions involved in **maintaining the armed force's logistical network**. It wasn't until the 1960s that the Feds got around to cleaning any of that up, in part because they were grateful for the assistance in tamping down any possibility of strikes during the war years.
### Illicit Profits Exceeding Gov't Revenues
Another important real-world example is the accommodation of the *narcotraficantes* by governments in Central and South America, especially [**Mexico**](http://en.wikipedia.org/wiki/Mexico). Although [coordinated government action limited local problems for years](https://scholar.harvard.edu/files/vrios/files/jcr587052.pdf), over time the amount of money involved in funneling drugs and people through to the US erupted into massive turf wars within Latin America itself. Disunity between local and federal parties didn't help, but mostly the flow of cash reached the point where nearly the entire law enforcement apparatus could be bought, the rest [could be hunted](https://www.nzherald.co.nz/world/in-mexico-cartels-are-hunting-down-police-at-their-homes/OJG54TOADTJW3OBRXWZUHWK2AM/), and (push come to shove) local gangs have sometimes [been better armed than the national military](https://time.com/5705358/sinaloa-cartel-mexico-culiacan/). |
207,341 | Assume this city is relatively large by late medieval standards, around 200,000 people. The city is mainly a site for trade due to its geographically central position and being on a river. Also, because it is geographically central, it also means the city is important for the government to project power.
**What might be the benefits for this same government to sanction certain crime within this important trade city?**
Crime that would be considered legal within city limits ranges from murder, burglary, trade of illicit substances, and racketeering. This is all under the condition that the crime does not directly affect the government's activities. | 2021/07/17 | [
"https://worldbuilding.stackexchange.com/questions/207341",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/43517/"
] | **Crime keeps people scared. Scared people want governments that are tough on crime. To demonstrate you are tough, you need criminals to punish.**
<https://www.foxnews.com/us/san-diego-homeless-attacks-help>
>
> San Diegans beg city to curb violence by homeless: 'like you’re in the
> 'Walking Dead''
>
>
>
What a packed headline - scared people begging the government for help, violence, and dehumanizing criminals by comparing them to zombies.
Your city government sells itself as tough on crime. Law and order. But if it is too good at its job, people forget about crime like people have forgotten about polio and measles because vaccines are too good at preventing disease. Your governments puts on a show of force, public discipline of criminals, etc. Maybe more like what we would consider a protection racket.
And they need grist for the mill - so crime is allowed in neighborhoods where people who are disloyal or dissatisfied with the government might live, to keep these malcontents scared. You can still satisfy your followers / customers with the punishment of criminals taken from places where criminals live. Maybe satisfy them better when they see the criminals as the dangerous "other". | >
> What might be the benefits for [a] government to sanction certain crime within [an] important trade city?
>
>
>
There are already excellent answers to this question, but to add some more real world details that have been overlooked:
### Strengthening Colonial Rule
The most famous real-world example is [**Hong Kong**](http://en.wikipedia.org/wiki/Hong_Kong). In order **(a)** to **facilitate illicit trade** in opium and other products, **(b)** to **enjoy an additional local spy network** in a large and hostile neighbor, and most importantly **(c)** to **maintain a semblance of order** over a large population whose language few of the colonial administration spoke, the Brits maintained deals with the [Triads](http://en.wikipedia.org/wiki/Triad_(organized_crime)) to essentially outsource most public order over the Chinese slums to powerful criminals. [The "tea money" *hongbao*](https://www.cinemaescapist.com/2018/04/chasing-dragon-critique-british-corruption-colonial-hong-kong/) provided by the gangs were also prime sources of income for the colonial police. Things were periodically shut down or renegotiated, as after the [1956 Double Ten Riots](http://en.wikipedia.org/wiki/1956_Hong_Kong_riots), but the Triads were so entrenched that [even the PRC were forced into deals with them during the handover](https://academic.oup.com/bjc/article-abstract/50/5/851/463592) and has only been slowly chipping away at them since, usually [when they start messing around on the mainland](https://www.chinasmack.com/large-hong-kong-triad-gathering-in-shenzhen-raided-by-police). There are tons of books, TV shows, and movies about this era but lots of them are in Cantonese. To bring the same idea closer to home, [*The Shield*](http://en.wikipedia.org/wiki/The_Shield) dramatizes the [LAPD](http://en.wikipedia.org/wiki/Los_Angeles_Police_Department)'s similar accommodation of crime as a way of handling the endemic mess in the poorer neighborhoods of [**Los Angeles**](http://en.wikipedia.org/wiki/Los_Angeles). Essentially, apart from enriching themselves, the Farmington police are shown choosing their battles, angling for local black and hispanic criminal leaders who keep the violence and crime away from better (and whiter) neighborhoods and away from directly harming the local children or the police themselves.
### Handling Temporary Emergencies
In [**New York City**](http://en.wikipedia.org/wiki/New_York_City) during World War II, [the US gov't made common cause with the mafia](https://historycollection.com/10-undeniable-ties-united-states-government-organized-crime/7/) in part to get a better spy network in the leadup to the invasion of Sicily but also to maintain control over longshoreman and other important labor unions involved in **maintaining the armed force's logistical network**. It wasn't until the 1960s that the Feds got around to cleaning any of that up, in part because they were grateful for the assistance in tamping down any possibility of strikes during the war years.
### Illicit Profits Exceeding Gov't Revenues
Another important real-world example is the accommodation of the *narcotraficantes* by governments in Central and South America, especially [**Mexico**](http://en.wikipedia.org/wiki/Mexico). Although [coordinated government action limited local problems for years](https://scholar.harvard.edu/files/vrios/files/jcr587052.pdf), over time the amount of money involved in funneling drugs and people through to the US erupted into massive turf wars within Latin America itself. Disunity between local and federal parties didn't help, but mostly the flow of cash reached the point where nearly the entire law enforcement apparatus could be bought, the rest [could be hunted](https://www.nzherald.co.nz/world/in-mexico-cartels-are-hunting-down-police-at-their-homes/OJG54TOADTJW3OBRXWZUHWK2AM/), and (push come to shove) local gangs have sometimes [been better armed than the national military](https://time.com/5705358/sinaloa-cartel-mexico-culiacan/). |
207,341 | Assume this city is relatively large by late medieval standards, around 200,000 people. The city is mainly a site for trade due to its geographically central position and being on a river. Also, because it is geographically central, it also means the city is important for the government to project power.
**What might be the benefits for this same government to sanction certain crime within this important trade city?**
Crime that would be considered legal within city limits ranges from murder, burglary, trade of illicit substances, and racketeering. This is all under the condition that the crime does not directly affect the government's activities. | 2021/07/17 | [
"https://worldbuilding.stackexchange.com/questions/207341",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/43517/"
] | Crime is allowed in the central city because it symbolically reinforces the government's claim to power.
* The current rulers are not nobles whose authority to lead flows down from their heritage.
* They are not great businessmen whose authority comes from their wealth and the employment opportunities they bring to the nation.
* They are not chosen by God, representatives of the divine authority of the Church.
* They were not chosen by the people.
They are conquerors, who recently attained their power by defeating the previous owners of the throne. Their power comes from their ability to overwhelm the previous symbol of law. It comes from the standing army which they brought with them, warriors who are now free to commit whatever crimes they wish in payment for their services. Justice has fallen to their might.
But they are also not fools. They know that if lawlessness is allowed throughout the kingdom, then the kingdom will very quickly fall. So outside of this city, the law is enforced even more brutally than it was under the previous king.
But here in their new home, strength is the only law. | **All of that is already legal to some extent in some places**
Legal in lots of jurisdictions, some of them even real democracies:
* Killing humans, for example in self defense, in war, as capital punishment, to save the mother of an unborn, abortion or euthanasia.
* Substance trading and consumption: Drinking alcohol, smoking tobacco or cannabis
* Taking other people’s property: Taxes, fines, fees, interest, foreclosures
The most important part is that the above activities are tightly controlled in order to provide stability and reliability. A successful city or country generally needs stability. You certainly don’t want random murder on the streets to be legal or you’d have anarchy and mayhem. But as long as it’s controlled and restricted in some way it’s perfectly feasible for murder to be legal. Even if it’s just some amount of money (“tax” or fine) you have to pay to the government for committing certain things. |
207,341 | Assume this city is relatively large by late medieval standards, around 200,000 people. The city is mainly a site for trade due to its geographically central position and being on a river. Also, because it is geographically central, it also means the city is important for the government to project power.
**What might be the benefits for this same government to sanction certain crime within this important trade city?**
Crime that would be considered legal within city limits ranges from murder, burglary, trade of illicit substances, and racketeering. This is all under the condition that the crime does not directly affect the government's activities. | 2021/07/17 | [
"https://worldbuilding.stackexchange.com/questions/207341",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/43517/"
] | **Crime keeps people scared. Scared people want governments that are tough on crime. To demonstrate you are tough, you need criminals to punish.**
<https://www.foxnews.com/us/san-diego-homeless-attacks-help>
>
> San Diegans beg city to curb violence by homeless: 'like you’re in the
> 'Walking Dead''
>
>
>
What a packed headline - scared people begging the government for help, violence, and dehumanizing criminals by comparing them to zombies.
Your city government sells itself as tough on crime. Law and order. But if it is too good at its job, people forget about crime like people have forgotten about polio and measles because vaccines are too good at preventing disease. Your governments puts on a show of force, public discipline of criminals, etc. Maybe more like what we would consider a protection racket.
And they need grist for the mill - so crime is allowed in neighborhoods where people who are disloyal or dissatisfied with the government might live, to keep these malcontents scared. You can still satisfy your followers / customers with the punishment of criminals taken from places where criminals live. Maybe satisfy them better when they see the criminals as the dangerous "other". | We have good historical examples where this occurred because of jurisdictional confusion.
For example, the tangled relationship of royal and Church prerogatives in Europe in the medieval and early Modern period often allowed Church leaders to exempt people from royal laws while on their lands. For example, in an area that later became part of London that was known as the [Liberty of the Clink](https://en.wikipedia.org/wiki/Liberty_of_the_Clink), the bishop was able to license prostitutes, brothels, and theatres.
[Kowloon Walled City](https://en.wikipedia.org/wiki/Kowloon_Walled_City) came to be because of a complicated history of claims over a small area of land by the British colonial government of Hong Kong and the Nationalist and Communist governments of China. Britain did not want to govern the area, but also did not want to return it to Chinese jurisdiction. So you ended up with a sort of *Passport to Pimlico* self-organizing quasi-anarchy without official law enforcement. |
207,341 | Assume this city is relatively large by late medieval standards, around 200,000 people. The city is mainly a site for trade due to its geographically central position and being on a river. Also, because it is geographically central, it also means the city is important for the government to project power.
**What might be the benefits for this same government to sanction certain crime within this important trade city?**
Crime that would be considered legal within city limits ranges from murder, burglary, trade of illicit substances, and racketeering. This is all under the condition that the crime does not directly affect the government's activities. | 2021/07/17 | [
"https://worldbuilding.stackexchange.com/questions/207341",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/43517/"
] | Nonsense. If something is allowed by the law, then it is not a crime. The very definition of a crime is breaking the law.
The proper question would be why the law in this city is more lenient than elsewhere. Consider for example the US, which is probably the country with the most legally heterogeneous country in the world. In some places you can walk around with an assault rifle or drive a tank. Do it in other places and it's jail for you. Why? Because different places have different populations with different world views, and the government at federal level does not want or cannot interfere. | Some governments [pork barrel](https://en.wikipedia.org/wiki/Pork_barrel): they favor the electorates that voted for them with money for projects that will benefit those communities - better roads, park lands, new hospital or extension to an existing one, etc.
There is also an element of divide and conquer. If the communities are competing with each other there will be less focus on the government.
A government that encouraged crime in one area would not do so openly. By encouraging such a situation, the government would openly give the perception of tackling the crime. By doing so, the people will have less of a focus on what the government is doing in other areas, such a corruption and kleptocracy. It also gives the government a better chance of staying in power.
One way to unite a people to align with the government is for the government to create common enemy. The criminals in the crime zone would be one such "enemy". |
207,341 | Assume this city is relatively large by late medieval standards, around 200,000 people. The city is mainly a site for trade due to its geographically central position and being on a river. Also, because it is geographically central, it also means the city is important for the government to project power.
**What might be the benefits for this same government to sanction certain crime within this important trade city?**
Crime that would be considered legal within city limits ranges from murder, burglary, trade of illicit substances, and racketeering. This is all under the condition that the crime does not directly affect the government's activities. | 2021/07/17 | [
"https://worldbuilding.stackexchange.com/questions/207341",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/43517/"
] | **In the real world, we sanction crime already**
Many countries allowed crime. Prostitution is illegal in many areas and has been at many times. It was and is often *tolerated*. Reasonings like, "if we don't tolerate it, the sailors will grab our woman of high social standing" were used to justify this. It was certainly still illigal, but as long as it wasn't in the way of society, it was ok.
This has happened in many other cases. Drug use for example. But there's also more difficult ideas like violence. Citizens, military and police all have varying amount of violence that is tolerated. Killing someone in self defence, or beating political rivals, or simoly killing an enemy all have different amount of tolerances. Violence in itself however is normally illigal.
Your government can use the same. Murder? Don't care. Murder of a policeman or factory worker? Illegal. As soon as the value to the city ramps up, the amount of tolerance will go down. | Hollywood will show you many - prolly dozens - of stories in which "governments" sanction crime for their own devious ends… most often to justify increasing the security budget or beefing up security powers.
That and any other Answer uses "government" in a rather loose sense. Even in today's Communist China and the historical USSR, it's almost unthinkable that an entire government would collectively go your way.
May we assume the Question is really about agencies, branches or departments, or rogue agents within them? |
207,341 | Assume this city is relatively large by late medieval standards, around 200,000 people. The city is mainly a site for trade due to its geographically central position and being on a river. Also, because it is geographically central, it also means the city is important for the government to project power.
**What might be the benefits for this same government to sanction certain crime within this important trade city?**
Crime that would be considered legal within city limits ranges from murder, burglary, trade of illicit substances, and racketeering. This is all under the condition that the crime does not directly affect the government's activities. | 2021/07/17 | [
"https://worldbuilding.stackexchange.com/questions/207341",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/43517/"
] | **In the real world, we sanction crime already**
Many countries allowed crime. Prostitution is illegal in many areas and has been at many times. It was and is often *tolerated*. Reasonings like, "if we don't tolerate it, the sailors will grab our woman of high social standing" were used to justify this. It was certainly still illigal, but as long as it wasn't in the way of society, it was ok.
This has happened in many other cases. Drug use for example. But there's also more difficult ideas like violence. Citizens, military and police all have varying amount of violence that is tolerated. Killing someone in self defence, or beating political rivals, or simoly killing an enemy all have different amount of tolerances. Violence in itself however is normally illigal.
Your government can use the same. Murder? Don't care. Murder of a policeman or factory worker? Illegal. As soon as the value to the city ramps up, the amount of tolerance will go down. | We have good historical examples where this occurred because of jurisdictional confusion.
For example, the tangled relationship of royal and Church prerogatives in Europe in the medieval and early Modern period often allowed Church leaders to exempt people from royal laws while on their lands. For example, in an area that later became part of London that was known as the [Liberty of the Clink](https://en.wikipedia.org/wiki/Liberty_of_the_Clink), the bishop was able to license prostitutes, brothels, and theatres.
[Kowloon Walled City](https://en.wikipedia.org/wiki/Kowloon_Walled_City) came to be because of a complicated history of claims over a small area of land by the British colonial government of Hong Kong and the Nationalist and Communist governments of China. Britain did not want to govern the area, but also did not want to return it to Chinese jurisdiction. So you ended up with a sort of *Passport to Pimlico* self-organizing quasi-anarchy without official law enforcement. |
28,731 | Sometimes, package updates from MELPA can break some part of emacs and when that happens I'd like to be able to revert back to using an older version of the package.
Right now, I can do it in two ways:
* I've set emacs to delete files by moving to trash and when I update a package, the older version is trashed. I can retrieve the older version and replace the one in `~/.emacs.d/elpa`.
* Go to the github repo of the package that broke functionality, fetch an older version of the package, replace the one in `~/.emacs.d/elpa` with the one from gitub, byte-recompile the file(s).
Both these ways involve a lot of manual work moving things around. Is there an easier(preferably automatic) way to downgrade packages installed from MELPA? | 2016/11/18 | [
"https://emacs.stackexchange.com/questions/28731",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/12247/"
] | When you update your packages through the `M-x list-packages` interface, after the successful installation of the package, you'll get asked if you want to remove the old package. Don't delete them so they stay in place and you could then later remove the newer package through this interface.
My current package list shows 4 versions of magit installed in my ~/.emacs.d/elpa/ directory tree.
```
magit 20160827.1549 obsolete A Git porcelain inside Emacs
magit 20160907.945 obsolete A Git porcelain inside Emacs
magit 20161001.1454 obsolete A Git porcelain inside Emacs
magit 20161123.617 installed A Git porcelain inside Emacs
```
You can clean-up old versions later with the key `~` (package-menu-mark-obsolete-for-deletion) to mark all obsolete packages. To delete a certain old version move to its line and press `d` to mark them for deletion. After you marked the packages you'd use `x` to execute the actions as usual.
In **Emacs 25** the mark all packages for `U`pgrade functionality automatically sets all old packages for deletion, and doesn't prompt for confirmation after installing. You have to look for lines that start with a capital "D", which you can just unmark (best with the following macro)
Type the key or chord on the left of the dash from the following lines.
```
<F3> - start macro recording
C-s - isearch-forward
C-q - quoted-insert
C-j - linefeed character
D - the mark at the start of the line
<Ret> - stops the isearch on the line with the "D"
u - unmark the package for deletion
<F4> - stops macro recording - the first package is now unmarked
<F4> - executes the macro for the next upgraded package
```
If there are no further matches for the search the macro will ring the bell and stop, so you could `C-u 0 <F4>` to unmark all packages marked for deletion. After this you can e`x`ecute the installations.
The function I declared to be changed in my comment has to be changed in a way I cannot grasp yet, as it's important that the last (cond) block has to be successful in order to not loop endlessly. | Lots of people elect not to commit ELPA packages to version control, but this is an example of why I believe you should do so.
Reverting *anything* is trivial if it's all committed.
Depending on the state of the upstream ELPA packages is a risk. |
28,731 | Sometimes, package updates from MELPA can break some part of emacs and when that happens I'd like to be able to revert back to using an older version of the package.
Right now, I can do it in two ways:
* I've set emacs to delete files by moving to trash and when I update a package, the older version is trashed. I can retrieve the older version and replace the one in `~/.emacs.d/elpa`.
* Go to the github repo of the package that broke functionality, fetch an older version of the package, replace the one in `~/.emacs.d/elpa` with the one from gitub, byte-recompile the file(s).
Both these ways involve a lot of manual work moving things around. Is there an easier(preferably automatic) way to downgrade packages installed from MELPA? | 2016/11/18 | [
"https://emacs.stackexchange.com/questions/28731",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/12247/"
] | The "nuclear option", as it were, would be to ditch `package.el` entirely and instead use the package manager that I wrote, [`straight.el`](https://github.com/raxod502/straight.el). The advantage would be that `straight.el` installs packages by cloning their Git repositories, thereby making it trivial to use whichever version you would like. Also, `straight.el` provides functionality for dealing with revision lockfiles, which allow you to record the exact state of your package management configuration down to the smallest detail. Then, in the case of an emergency, you can simply revert all packages to their known-good versions.
These kinds of operations are, in general, impossible with `package.el`, and they will always be impossible, due to the overall design.
In response to your desire to avoid making a commit every time you update your packages, this is not necessary with `straight.el`. I would *recommend* writing a version lockfile and committing that every time you update your packages, since that makes it impossible to ever get into a state where your Emacs configuration is broken after an upgrade and you don't know how to revert. But you don't have to do this, if you like living life on the edge. | Lots of people elect not to commit ELPA packages to version control, but this is an example of why I believe you should do so.
Reverting *anything* is trivial if it's all committed.
Depending on the state of the upstream ELPA packages is a risk. |
28,731 | Sometimes, package updates from MELPA can break some part of emacs and when that happens I'd like to be able to revert back to using an older version of the package.
Right now, I can do it in two ways:
* I've set emacs to delete files by moving to trash and when I update a package, the older version is trashed. I can retrieve the older version and replace the one in `~/.emacs.d/elpa`.
* Go to the github repo of the package that broke functionality, fetch an older version of the package, replace the one in `~/.emacs.d/elpa` with the one from gitub, byte-recompile the file(s).
Both these ways involve a lot of manual work moving things around. Is there an easier(preferably automatic) way to downgrade packages installed from MELPA? | 2016/11/18 | [
"https://emacs.stackexchange.com/questions/28731",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/12247/"
] | I find an easy way to downgrade: managing your own melpa archive.
1. Clone [melpa](https://github.com/melpa/melpa) repo.
2. Follow [melpa's custom melpa archive wiki page](https://github.com/melpa/melpa/wiki/Custom-Melpa-Archive) to remove all recipes.
3. Find the commit of the package you want to down grade to, and create a new recipe with that commit for the package. (see [melpa's readme](https://github.com/melpa/melpa#recipe-format) about how to specify the commit)
4. Run `make` to build the downgraded package
5. Add your own melpa archive, which can be a local directory, to the `package-archives` list.
6. Install the downgraded package using the package menu. Or you can use `package-pinned-packages` to restrict the archive where the package should be downloaded from. | Lots of people elect not to commit ELPA packages to version control, but this is an example of why I believe you should do so.
Reverting *anything* is trivial if it's all committed.
Depending on the state of the upstream ELPA packages is a risk. |
28,731 | Sometimes, package updates from MELPA can break some part of emacs and when that happens I'd like to be able to revert back to using an older version of the package.
Right now, I can do it in two ways:
* I've set emacs to delete files by moving to trash and when I update a package, the older version is trashed. I can retrieve the older version and replace the one in `~/.emacs.d/elpa`.
* Go to the github repo of the package that broke functionality, fetch an older version of the package, replace the one in `~/.emacs.d/elpa` with the one from gitub, byte-recompile the file(s).
Both these ways involve a lot of manual work moving things around. Is there an easier(preferably automatic) way to downgrade packages installed from MELPA? | 2016/11/18 | [
"https://emacs.stackexchange.com/questions/28731",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/12247/"
] | When you update your packages through the `M-x list-packages` interface, after the successful installation of the package, you'll get asked if you want to remove the old package. Don't delete them so they stay in place and you could then later remove the newer package through this interface.
My current package list shows 4 versions of magit installed in my ~/.emacs.d/elpa/ directory tree.
```
magit 20160827.1549 obsolete A Git porcelain inside Emacs
magit 20160907.945 obsolete A Git porcelain inside Emacs
magit 20161001.1454 obsolete A Git porcelain inside Emacs
magit 20161123.617 installed A Git porcelain inside Emacs
```
You can clean-up old versions later with the key `~` (package-menu-mark-obsolete-for-deletion) to mark all obsolete packages. To delete a certain old version move to its line and press `d` to mark them for deletion. After you marked the packages you'd use `x` to execute the actions as usual.
In **Emacs 25** the mark all packages for `U`pgrade functionality automatically sets all old packages for deletion, and doesn't prompt for confirmation after installing. You have to look for lines that start with a capital "D", which you can just unmark (best with the following macro)
Type the key or chord on the left of the dash from the following lines.
```
<F3> - start macro recording
C-s - isearch-forward
C-q - quoted-insert
C-j - linefeed character
D - the mark at the start of the line
<Ret> - stops the isearch on the line with the "D"
u - unmark the package for deletion
<F4> - stops macro recording - the first package is now unmarked
<F4> - executes the macro for the next upgraded package
```
If there are no further matches for the search the macro will ring the bell and stop, so you could `C-u 0 <F4>` to unmark all packages marked for deletion. After this you can e`x`ecute the installations.
The function I declared to be changed in my comment has to be changed in a way I cannot grasp yet, as it's important that the last (cond) block has to be successful in order to not loop endlessly. | The "nuclear option", as it were, would be to ditch `package.el` entirely and instead use the package manager that I wrote, [`straight.el`](https://github.com/raxod502/straight.el). The advantage would be that `straight.el` installs packages by cloning their Git repositories, thereby making it trivial to use whichever version you would like. Also, `straight.el` provides functionality for dealing with revision lockfiles, which allow you to record the exact state of your package management configuration down to the smallest detail. Then, in the case of an emergency, you can simply revert all packages to their known-good versions.
These kinds of operations are, in general, impossible with `package.el`, and they will always be impossible, due to the overall design.
In response to your desire to avoid making a commit every time you update your packages, this is not necessary with `straight.el`. I would *recommend* writing a version lockfile and committing that every time you update your packages, since that makes it impossible to ever get into a state where your Emacs configuration is broken after an upgrade and you don't know how to revert. But you don't have to do this, if you like living life on the edge. |
28,731 | Sometimes, package updates from MELPA can break some part of emacs and when that happens I'd like to be able to revert back to using an older version of the package.
Right now, I can do it in two ways:
* I've set emacs to delete files by moving to trash and when I update a package, the older version is trashed. I can retrieve the older version and replace the one in `~/.emacs.d/elpa`.
* Go to the github repo of the package that broke functionality, fetch an older version of the package, replace the one in `~/.emacs.d/elpa` with the one from gitub, byte-recompile the file(s).
Both these ways involve a lot of manual work moving things around. Is there an easier(preferably automatic) way to downgrade packages installed from MELPA? | 2016/11/18 | [
"https://emacs.stackexchange.com/questions/28731",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/12247/"
] | When you update your packages through the `M-x list-packages` interface, after the successful installation of the package, you'll get asked if you want to remove the old package. Don't delete them so they stay in place and you could then later remove the newer package through this interface.
My current package list shows 4 versions of magit installed in my ~/.emacs.d/elpa/ directory tree.
```
magit 20160827.1549 obsolete A Git porcelain inside Emacs
magit 20160907.945 obsolete A Git porcelain inside Emacs
magit 20161001.1454 obsolete A Git porcelain inside Emacs
magit 20161123.617 installed A Git porcelain inside Emacs
```
You can clean-up old versions later with the key `~` (package-menu-mark-obsolete-for-deletion) to mark all obsolete packages. To delete a certain old version move to its line and press `d` to mark them for deletion. After you marked the packages you'd use `x` to execute the actions as usual.
In **Emacs 25** the mark all packages for `U`pgrade functionality automatically sets all old packages for deletion, and doesn't prompt for confirmation after installing. You have to look for lines that start with a capital "D", which you can just unmark (best with the following macro)
Type the key or chord on the left of the dash from the following lines.
```
<F3> - start macro recording
C-s - isearch-forward
C-q - quoted-insert
C-j - linefeed character
D - the mark at the start of the line
<Ret> - stops the isearch on the line with the "D"
u - unmark the package for deletion
<F4> - stops macro recording - the first package is now unmarked
<F4> - executes the macro for the next upgraded package
```
If there are no further matches for the search the macro will ring the bell and stop, so you could `C-u 0 <F4>` to unmark all packages marked for deletion. After this you can e`x`ecute the installations.
The function I declared to be changed in my comment has to be changed in a way I cannot grasp yet, as it's important that the last (cond) block has to be successful in order to not loop endlessly. | I find an easy way to downgrade: managing your own melpa archive.
1. Clone [melpa](https://github.com/melpa/melpa) repo.
2. Follow [melpa's custom melpa archive wiki page](https://github.com/melpa/melpa/wiki/Custom-Melpa-Archive) to remove all recipes.
3. Find the commit of the package you want to down grade to, and create a new recipe with that commit for the package. (see [melpa's readme](https://github.com/melpa/melpa#recipe-format) about how to specify the commit)
4. Run `make` to build the downgraded package
5. Add your own melpa archive, which can be a local directory, to the `package-archives` list.
6. Install the downgraded package using the package menu. Or you can use `package-pinned-packages` to restrict the archive where the package should be downloaded from. |
28,731 | Sometimes, package updates from MELPA can break some part of emacs and when that happens I'd like to be able to revert back to using an older version of the package.
Right now, I can do it in two ways:
* I've set emacs to delete files by moving to trash and when I update a package, the older version is trashed. I can retrieve the older version and replace the one in `~/.emacs.d/elpa`.
* Go to the github repo of the package that broke functionality, fetch an older version of the package, replace the one in `~/.emacs.d/elpa` with the one from gitub, byte-recompile the file(s).
Both these ways involve a lot of manual work moving things around. Is there an easier(preferably automatic) way to downgrade packages installed from MELPA? | 2016/11/18 | [
"https://emacs.stackexchange.com/questions/28731",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/12247/"
] | When you update your packages through the `M-x list-packages` interface, after the successful installation of the package, you'll get asked if you want to remove the old package. Don't delete them so they stay in place and you could then later remove the newer package through this interface.
My current package list shows 4 versions of magit installed in my ~/.emacs.d/elpa/ directory tree.
```
magit 20160827.1549 obsolete A Git porcelain inside Emacs
magit 20160907.945 obsolete A Git porcelain inside Emacs
magit 20161001.1454 obsolete A Git porcelain inside Emacs
magit 20161123.617 installed A Git porcelain inside Emacs
```
You can clean-up old versions later with the key `~` (package-menu-mark-obsolete-for-deletion) to mark all obsolete packages. To delete a certain old version move to its line and press `d` to mark them for deletion. After you marked the packages you'd use `x` to execute the actions as usual.
In **Emacs 25** the mark all packages for `U`pgrade functionality automatically sets all old packages for deletion, and doesn't prompt for confirmation after installing. You have to look for lines that start with a capital "D", which you can just unmark (best with the following macro)
Type the key or chord on the left of the dash from the following lines.
```
<F3> - start macro recording
C-s - isearch-forward
C-q - quoted-insert
C-j - linefeed character
D - the mark at the start of the line
<Ret> - stops the isearch on the line with the "D"
u - unmark the package for deletion
<F4> - stops macro recording - the first package is now unmarked
<F4> - executes the macro for the next upgraded package
```
If there are no further matches for the search the macro will ring the bell and stop, so you could `C-u 0 <F4>` to unmark all packages marked for deletion. After this you can e`x`ecute the installations.
The function I declared to be changed in my comment has to be changed in a way I cannot grasp yet, as it's important that the last (cond) block has to be successful in order to not loop endlessly. | I download the package from github(the package home page) and build it, and recover files to `.emacs.d/elpa`.
for example:
If I want to downgrade package - [hl-todo](https://github.com/tarsius/hl-todo/tree/3bba4591c54951d2abab113ec5e58a6319808ca9) to version `3bba4591`, I can download the specific version package, then build it (with the command `make`), and it will generate `.elc` files and others. Copy and Cover them to `~/.emacs.d/elpa/hl-todo-20200807.1546` (replace the timestamp with yours) |
28,731 | Sometimes, package updates from MELPA can break some part of emacs and when that happens I'd like to be able to revert back to using an older version of the package.
Right now, I can do it in two ways:
* I've set emacs to delete files by moving to trash and when I update a package, the older version is trashed. I can retrieve the older version and replace the one in `~/.emacs.d/elpa`.
* Go to the github repo of the package that broke functionality, fetch an older version of the package, replace the one in `~/.emacs.d/elpa` with the one from gitub, byte-recompile the file(s).
Both these ways involve a lot of manual work moving things around. Is there an easier(preferably automatic) way to downgrade packages installed from MELPA? | 2016/11/18 | [
"https://emacs.stackexchange.com/questions/28731",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/12247/"
] | The "nuclear option", as it were, would be to ditch `package.el` entirely and instead use the package manager that I wrote, [`straight.el`](https://github.com/raxod502/straight.el). The advantage would be that `straight.el` installs packages by cloning their Git repositories, thereby making it trivial to use whichever version you would like. Also, `straight.el` provides functionality for dealing with revision lockfiles, which allow you to record the exact state of your package management configuration down to the smallest detail. Then, in the case of an emergency, you can simply revert all packages to their known-good versions.
These kinds of operations are, in general, impossible with `package.el`, and they will always be impossible, due to the overall design.
In response to your desire to avoid making a commit every time you update your packages, this is not necessary with `straight.el`. I would *recommend* writing a version lockfile and committing that every time you update your packages, since that makes it impossible to ever get into a state where your Emacs configuration is broken after an upgrade and you don't know how to revert. But you don't have to do this, if you like living life on the edge. | I find an easy way to downgrade: managing your own melpa archive.
1. Clone [melpa](https://github.com/melpa/melpa) repo.
2. Follow [melpa's custom melpa archive wiki page](https://github.com/melpa/melpa/wiki/Custom-Melpa-Archive) to remove all recipes.
3. Find the commit of the package you want to down grade to, and create a new recipe with that commit for the package. (see [melpa's readme](https://github.com/melpa/melpa#recipe-format) about how to specify the commit)
4. Run `make` to build the downgraded package
5. Add your own melpa archive, which can be a local directory, to the `package-archives` list.
6. Install the downgraded package using the package menu. Or you can use `package-pinned-packages` to restrict the archive where the package should be downloaded from. |
28,731 | Sometimes, package updates from MELPA can break some part of emacs and when that happens I'd like to be able to revert back to using an older version of the package.
Right now, I can do it in two ways:
* I've set emacs to delete files by moving to trash and when I update a package, the older version is trashed. I can retrieve the older version and replace the one in `~/.emacs.d/elpa`.
* Go to the github repo of the package that broke functionality, fetch an older version of the package, replace the one in `~/.emacs.d/elpa` with the one from gitub, byte-recompile the file(s).
Both these ways involve a lot of manual work moving things around. Is there an easier(preferably automatic) way to downgrade packages installed from MELPA? | 2016/11/18 | [
"https://emacs.stackexchange.com/questions/28731",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/12247/"
] | The "nuclear option", as it were, would be to ditch `package.el` entirely and instead use the package manager that I wrote, [`straight.el`](https://github.com/raxod502/straight.el). The advantage would be that `straight.el` installs packages by cloning their Git repositories, thereby making it trivial to use whichever version you would like. Also, `straight.el` provides functionality for dealing with revision lockfiles, which allow you to record the exact state of your package management configuration down to the smallest detail. Then, in the case of an emergency, you can simply revert all packages to their known-good versions.
These kinds of operations are, in general, impossible with `package.el`, and they will always be impossible, due to the overall design.
In response to your desire to avoid making a commit every time you update your packages, this is not necessary with `straight.el`. I would *recommend* writing a version lockfile and committing that every time you update your packages, since that makes it impossible to ever get into a state where your Emacs configuration is broken after an upgrade and you don't know how to revert. But you don't have to do this, if you like living life on the edge. | I download the package from github(the package home page) and build it, and recover files to `.emacs.d/elpa`.
for example:
If I want to downgrade package - [hl-todo](https://github.com/tarsius/hl-todo/tree/3bba4591c54951d2abab113ec5e58a6319808ca9) to version `3bba4591`, I can download the specific version package, then build it (with the command `make`), and it will generate `.elc` files and others. Copy and Cover them to `~/.emacs.d/elpa/hl-todo-20200807.1546` (replace the timestamp with yours) |
28,731 | Sometimes, package updates from MELPA can break some part of emacs and when that happens I'd like to be able to revert back to using an older version of the package.
Right now, I can do it in two ways:
* I've set emacs to delete files by moving to trash and when I update a package, the older version is trashed. I can retrieve the older version and replace the one in `~/.emacs.d/elpa`.
* Go to the github repo of the package that broke functionality, fetch an older version of the package, replace the one in `~/.emacs.d/elpa` with the one from gitub, byte-recompile the file(s).
Both these ways involve a lot of manual work moving things around. Is there an easier(preferably automatic) way to downgrade packages installed from MELPA? | 2016/11/18 | [
"https://emacs.stackexchange.com/questions/28731",
"https://emacs.stackexchange.com",
"https://emacs.stackexchange.com/users/12247/"
] | I find an easy way to downgrade: managing your own melpa archive.
1. Clone [melpa](https://github.com/melpa/melpa) repo.
2. Follow [melpa's custom melpa archive wiki page](https://github.com/melpa/melpa/wiki/Custom-Melpa-Archive) to remove all recipes.
3. Find the commit of the package you want to down grade to, and create a new recipe with that commit for the package. (see [melpa's readme](https://github.com/melpa/melpa#recipe-format) about how to specify the commit)
4. Run `make` to build the downgraded package
5. Add your own melpa archive, which can be a local directory, to the `package-archives` list.
6. Install the downgraded package using the package menu. Or you can use `package-pinned-packages` to restrict the archive where the package should be downloaded from. | I download the package from github(the package home page) and build it, and recover files to `.emacs.d/elpa`.
for example:
If I want to downgrade package - [hl-todo](https://github.com/tarsius/hl-todo/tree/3bba4591c54951d2abab113ec5e58a6319808ca9) to version `3bba4591`, I can download the specific version package, then build it (with the command `make`), and it will generate `.elc` files and others. Copy and Cover them to `~/.emacs.d/elpa/hl-todo-20200807.1546` (replace the timestamp with yours) |
7,338,824 | I have a log line that I am pulling from bash like:
```
There are 5 apples and 7 oranges
```
And I want to get the 5 and 7 into bash variables and am having problems doing so.
awk '{ print $3, $6 }' won't work due to the fact that their position might change, if there are bananas. Bonus points if the digits can be associated with their fruits.
Thanks in advance | 2011/09/07 | [
"https://Stackoverflow.com/questions/7338824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884881/"
] | and to get the fruits:
```
echo 'There are 5 apples and 7 oranges' | grep -o -E '[[:digit:]]+ [[:alpha:]]+'
``` | Grep will do this:
```
echo 'There are 5 apples and 7 oranges' | grep -o -E '[[:digit:]]+'
``` |
7,338,824 | I have a log line that I am pulling from bash like:
```
There are 5 apples and 7 oranges
```
And I want to get the 5 and 7 into bash variables and am having problems doing so.
awk '{ print $3, $6 }' won't work due to the fact that their position might change, if there are bananas. Bonus points if the digits can be associated with their fruits.
Thanks in advance | 2011/09/07 | [
"https://Stackoverflow.com/questions/7338824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884881/"
] | A bash-only method, tested with bash v4:
```
str=" There are 5 apples, 12 bananas and 7 oranges"
i=0
while [[ "$str" =~ ([0-9]+)" "([a-z]+)(.*) ]] ; do
num[$i]=${BASH_REMATCH[1]}
type[$i]=${BASH_REMATCH[2]}
str=${BASH_REMATCH[3]}
(( i++ ))
done
for (( i=0; i<${#num[@]}; i++ )); do
printf "%4d\t%s\t%s\n" $i ${num[$i]} ${type[$i]}
done
```
outputs
```
0 5 apples
1 12 bananas
2 7 oranges
``` | Grep will do this:
```
echo 'There are 5 apples and 7 oranges' | grep -o -E '[[:digit:]]+'
``` |
7,338,824 | I have a log line that I am pulling from bash like:
```
There are 5 apples and 7 oranges
```
And I want to get the 5 and 7 into bash variables and am having problems doing so.
awk '{ print $3, $6 }' won't work due to the fact that their position might change, if there are bananas. Bonus points if the digits can be associated with their fruits.
Thanks in advance | 2011/09/07 | [
"https://Stackoverflow.com/questions/7338824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884881/"
] | and to get the fruits:
```
echo 'There are 5 apples and 7 oranges' | grep -o -E '[[:digit:]]+ [[:alpha:]]+'
``` | Slightly more compact version:
`echo 'There are 5 apples and 7 oranges' | egrep -o '[0-9]+ \w+'`
Note however that `\w` is synonymous with `[:alnum:]`, and will thus match "appl3s" as well, for example. |
7,338,824 | I have a log line that I am pulling from bash like:
```
There are 5 apples and 7 oranges
```
And I want to get the 5 and 7 into bash variables and am having problems doing so.
awk '{ print $3, $6 }' won't work due to the fact that their position might change, if there are bananas. Bonus points if the digits can be associated with their fruits.
Thanks in advance | 2011/09/07 | [
"https://Stackoverflow.com/questions/7338824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884881/"
] | and to get the fruits:
```
echo 'There are 5 apples and 7 oranges' | grep -o -E '[[:digit:]]+ [[:alpha:]]+'
``` | Well, shell is a strange language, and you can do nice things. For example:
```
a="there are 7 apples"
for i in $a; do
case $i in
[0-9]*)
value=$i
expectname=1
;;
*)
test -n "$expectname" && name=$i
expectname=
;;
esac
done
echo $value
echo $name
```
If you have more than one occurrence, you can fill an array, or a bash map. |
7,338,824 | I have a log line that I am pulling from bash like:
```
There are 5 apples and 7 oranges
```
And I want to get the 5 and 7 into bash variables and am having problems doing so.
awk '{ print $3, $6 }' won't work due to the fact that their position might change, if there are bananas. Bonus points if the digits can be associated with their fruits.
Thanks in advance | 2011/09/07 | [
"https://Stackoverflow.com/questions/7338824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884881/"
] | and to get the fruits:
```
echo 'There are 5 apples and 7 oranges' | grep -o -E '[[:digit:]]+ [[:alpha:]]+'
``` | A bash-only method, tested with bash v4:
```
str=" There are 5 apples, 12 bananas and 7 oranges"
i=0
while [[ "$str" =~ ([0-9]+)" "([a-z]+)(.*) ]] ; do
num[$i]=${BASH_REMATCH[1]}
type[$i]=${BASH_REMATCH[2]}
str=${BASH_REMATCH[3]}
(( i++ ))
done
for (( i=0; i<${#num[@]}; i++ )); do
printf "%4d\t%s\t%s\n" $i ${num[$i]} ${type[$i]}
done
```
outputs
```
0 5 apples
1 12 bananas
2 7 oranges
``` |
7,338,824 | I have a log line that I am pulling from bash like:
```
There are 5 apples and 7 oranges
```
And I want to get the 5 and 7 into bash variables and am having problems doing so.
awk '{ print $3, $6 }' won't work due to the fact that their position might change, if there are bananas. Bonus points if the digits can be associated with their fruits.
Thanks in advance | 2011/09/07 | [
"https://Stackoverflow.com/questions/7338824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884881/"
] | A bash-only method, tested with bash v4:
```
str=" There are 5 apples, 12 bananas and 7 oranges"
i=0
while [[ "$str" =~ ([0-9]+)" "([a-z]+)(.*) ]] ; do
num[$i]=${BASH_REMATCH[1]}
type[$i]=${BASH_REMATCH[2]}
str=${BASH_REMATCH[3]}
(( i++ ))
done
for (( i=0; i<${#num[@]}; i++ )); do
printf "%4d\t%s\t%s\n" $i ${num[$i]} ${type[$i]}
done
```
outputs
```
0 5 apples
1 12 bananas
2 7 oranges
``` | Slightly more compact version:
`echo 'There are 5 apples and 7 oranges' | egrep -o '[0-9]+ \w+'`
Note however that `\w` is synonymous with `[:alnum:]`, and will thus match "appl3s" as well, for example. |
7,338,824 | I have a log line that I am pulling from bash like:
```
There are 5 apples and 7 oranges
```
And I want to get the 5 and 7 into bash variables and am having problems doing so.
awk '{ print $3, $6 }' won't work due to the fact that their position might change, if there are bananas. Bonus points if the digits can be associated with their fruits.
Thanks in advance | 2011/09/07 | [
"https://Stackoverflow.com/questions/7338824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884881/"
] | A bash-only method, tested with bash v4:
```
str=" There are 5 apples, 12 bananas and 7 oranges"
i=0
while [[ "$str" =~ ([0-9]+)" "([a-z]+)(.*) ]] ; do
num[$i]=${BASH_REMATCH[1]}
type[$i]=${BASH_REMATCH[2]}
str=${BASH_REMATCH[3]}
(( i++ ))
done
for (( i=0; i<${#num[@]}; i++ )); do
printf "%4d\t%s\t%s\n" $i ${num[$i]} ${type[$i]}
done
```
outputs
```
0 5 apples
1 12 bananas
2 7 oranges
``` | Well, shell is a strange language, and you can do nice things. For example:
```
a="there are 7 apples"
for i in $a; do
case $i in
[0-9]*)
value=$i
expectname=1
;;
*)
test -n "$expectname" && name=$i
expectname=
;;
esac
done
echo $value
echo $name
```
If you have more than one occurrence, you can fill an array, or a bash map. |
65,263,049 | I am using this logic in my button i.e if login the buynow class is working else login modal is open.
& code here.
```
<button class="ps-btn ps-btn--sm @if(session()->has('name')){{'buy_now'}}"@else {{data-toggle="modal" data-target="#loginModal"}}@endif>Buy Now<i class="ps-icon-next"></i></button>
``` | 2020/12/12 | [
"https://Stackoverflow.com/questions/65263049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14724522/"
] | You can use below code
```
<button class="ps-btn ps-btn--sm
@if(session()->has('name')) buy_now"
@else " data-toggle='modal' data-target='#loginModal'
@endif>Buy Now<i class="ps-icon-next"></i>
</button>
```
**Notice:** We use `{{ $variable }}` for echoing a php variable. It is equivalent to `<?php echo $variable ?>`. For more info refer to [laravel displaying data](https://laravel.com/docs/8.x/blade#displaying-data) | **Try this:**
```
<button session()->has('name') ? class="ps-btn ps-btn--sm buy_now' : "data-
toggle="modal" data-target="#loginModal">Buy Now<i class="ps-icon-next"></i>
</button>
``` |
40,193,491 | I am working on a project, where I have a domain `xyz.com`, I have been requested that a subdomain example `abc.xyz.com` should point to website which has ipaddress
example `http://199.152.57.120/client/` and when a visitor browse `abc.xyz.com` it should open the website hosted on `http://199.152.57.120/client/` but by hidding this ip address the visitor should always see `abc.xyz.com`.
I also need to host another website to `xyz.com`
domain which is registered with *x* company and webhosting is taken for *z* company both different.
It is something similar to Reseller business where Reseller company assign a website to their client on their custom domain. | 2016/10/22 | [
"https://Stackoverflow.com/questions/40193491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7057429/"
] | Here's the solution for [image2](http://genxcoders.in/demo/TDirectory/2.png)
`echo '<select>';`
`structureTree(0,0);`
`echo '</select>';`
`function structureTree($deptParentId, $level){`
```
$result = getDataFromDb($deptParentId); // change this into SQL
foreach($result as $result){
echo '<option value="'.$deptParentId.'">'.str_repeat('-',$level).$result['deptName'].'</option>';
structureTree($result['deptId'], $level+2);
}
```
`}`
`// mocking database record
function getDataFromDb($deptParentId)
{`
```
$data = array(
array(
'deptId' => 1,
'deptName' => 'IT',
'deptParentId' => 0,
),
array(
'deptId' => 2,
'deptName' => 'Human Resources',
'deptParentId' => 1,
),
array(
'deptId' => 3,
'deptName' => 'Opreational',
'deptParentId' => 1,
),
array(
'deptId' => 4,
'deptName' => 'Networking Department',
'deptParentId' => 1,
),
array(
'deptId' => 5,
'deptName' => 'Software Development',
'deptParentId' => 1,
),
array(
'deptId' => 6,
'deptName' => 'Mobile Software Development',
'deptParentId' => 5,
),
array(
'deptId' => 7,
'deptName' => 'ERP',
'deptParentId' => 5,
),
array(
'deptId' => 8,
'deptName' => 'Product Development',
'deptParentId' => 5,
),
);
$result = array();
foreach ($data as $record) {
if ($record['deptParentId'] === $deptParentId) {
$result[] = $record;
}
}
return $result;
```
`}`
regarding [1.png](http://genxcoders.in/demo/TDirectory/1.png) Here's the `SQL` based on your sample db table
`SELEC dep.deptId As DepId`
`,dep.deptName As DepartmenName`
`,parent.deptId As ParentId`
`,parent.deptName As ParentDepartmentName`
`FROM tddept As dep`
`JOIN tddept As parent ON parent.deptParentId = dep.deptId;` | recursion is the solution for this problem. While the parent still has a child then it keeps querying until there's no child left.
e.g
One
.One1
.One2
.One3
Here's the php application
`function structureTree($depParentId = 0){`
```
$result = queryFunction("SELECT *FROM
tddept WHERE deptParentId = '$depParentId'");
foreach($results as $result){
echo $result['deptName'].'<br/>';
structureTree($resultp['deptParentId']);
}
```
`}`
`structureTree();` |
2,318 | We would like to get rid of the Tridion Broker as part of a project and publish content directly to a repository as part of a Storage Extension.
My question is, is there any deep dependency that Tridion has on the Broker that might mean things work in a sub-optimal way, or gotchas that I should be aware of?
Update - We are going to be using Tridion purely as a content store which will push out JSON. There will be no functionality or any form of business logic/UI. | 2013/07/25 | [
"https://tridion.stackexchange.com/questions/2318",
"https://tridion.stackexchange.com",
"https://tridion.stackexchange.com/users/315/"
] | I will assume that what you mean with the Broker is the Tridion Broker database.
It is possible to publish everything to the file system, it includes, content, linking info, metadata and references, however this functionality is deprecated and will be removed in future releases, having said that, in future releases, linking, metadata and references will always be stored in the Tridion broker database.
If what you want is to override the storage layer and create a custom one, it will for sure affect key features like the Tridion CD API, Dynamic Linking and of course it won't be supported by either Customer Support or R&D.
Other key feature that depends on the Tridion Broker database is the Session Preview functionality. | 1. Dynamic Linking is the big one as Rob mentions.
2. any DCPs embedded on Pages will render
UCs/Tags.
3. Any code that queries CPs using Criteria/Query API will need to be gutted/replaced.
4. If you use P&P, then any personalized content will be rendered and filtered via User Controls/Tags, and this will need replacing
5. If you use UGC, same as #4.
When starting a fresh implementation Broker/no-Broker is a decision to be made, but once it's done and the site is live, you have a lot of work on your hands to get rid of the Broker. |
2,318 | We would like to get rid of the Tridion Broker as part of a project and publish content directly to a repository as part of a Storage Extension.
My question is, is there any deep dependency that Tridion has on the Broker that might mean things work in a sub-optimal way, or gotchas that I should be aware of?
Update - We are going to be using Tridion purely as a content store which will push out JSON. There will be no functionality or any form of business logic/UI. | 2013/07/25 | [
"https://tridion.stackexchange.com/questions/2318",
"https://tridion.stackexchange.com",
"https://tridion.stackexchange.com/users/315/"
] | 1. Dynamic Linking is the big one as Rob mentions.
2. any DCPs embedded on Pages will render
UCs/Tags.
3. Any code that queries CPs using Criteria/Query API will need to be gutted/replaced.
4. If you use P&P, then any personalized content will be rendered and filtered via User Controls/Tags, and this will need replacing
5. If you use UGC, same as #4.
When starting a fresh implementation Broker/no-Broker is a decision to be made, but once it's done and the site is live, you have a lot of work on your hands to get rid of the Broker. | This sounds like an unusual implementation.
It might be worth blueprinting your website to allow you to localize the templates to render the json. The new child publication could be used with a new deployer for you to test if this gives you the output you need without any missing functionality. |
2,318 | We would like to get rid of the Tridion Broker as part of a project and publish content directly to a repository as part of a Storage Extension.
My question is, is there any deep dependency that Tridion has on the Broker that might mean things work in a sub-optimal way, or gotchas that I should be aware of?
Update - We are going to be using Tridion purely as a content store which will push out JSON. There will be no functionality or any form of business logic/UI. | 2013/07/25 | [
"https://tridion.stackexchange.com/questions/2318",
"https://tridion.stackexchange.com",
"https://tridion.stackexchange.com/users/315/"
] | I will assume that what you mean with the Broker is the Tridion Broker database.
It is possible to publish everything to the file system, it includes, content, linking info, metadata and references, however this functionality is deprecated and will be removed in future releases, having said that, in future releases, linking, metadata and references will always be stored in the Tridion broker database.
If what you want is to override the storage layer and create a custom one, it will for sure affect key features like the Tridion CD API, Dynamic Linking and of course it won't be supported by either Customer Support or R&D.
Other key feature that depends on the Tridion Broker database is the Session Preview functionality. | This sounds like an unusual implementation.
It might be worth blueprinting your website to allow you to localize the templates to render the json. The new child publication could be used with a new deployer for you to test if this gives you the output you need without any missing functionality. |
2,318 | We would like to get rid of the Tridion Broker as part of a project and publish content directly to a repository as part of a Storage Extension.
My question is, is there any deep dependency that Tridion has on the Broker that might mean things work in a sub-optimal way, or gotchas that I should be aware of?
Update - We are going to be using Tridion purely as a content store which will push out JSON. There will be no functionality or any form of business logic/UI. | 2013/07/25 | [
"https://tridion.stackexchange.com/questions/2318",
"https://tridion.stackexchange.com",
"https://tridion.stackexchange.com/users/315/"
] | I will assume that what you mean with the Broker is the Tridion Broker database.
It is possible to publish everything to the file system, it includes, content, linking info, metadata and references, however this functionality is deprecated and will be removed in future releases, having said that, in future releases, linking, metadata and references will always be stored in the Tridion broker database.
If what you want is to override the storage layer and create a custom one, it will for sure affect key features like the Tridion CD API, Dynamic Linking and of course it won't be supported by either Customer Support or R&D.
Other key feature that depends on the Tridion Broker database is the Session Preview functionality. | I would be vary wary of any approach that removes all Content Delivery functionality, or the ability to hook into it. Customers I have seen that take this approach due to whatever requirements, tend to become very dissatisfied in the long term. Usually they bought Tridion for the whole package of functionality, CM + CD.
Some typical issues are:
1. Upgrading - if you build your own Content Delivery framework, this needs to be tested and updated before the client can upgrade their Tridion version. Maybe the people/organization that created the framework have moved on, and no-one knows how the heck it works any more anyway. I have even had customers who didnt even have the source code for their framework!
2. New product features - Tridion releases a new version or module with feature X that is amazing. The sales guy does the hard sell, the customer MUST have it... but wait - it requires Content Delivery elements, which are not part of your framework
So think carefully before following this route. You can still publish JSON to Elastic Store with Tridion, but I would try to keep standard Tridion CD for as much as possible... |
2,318 | We would like to get rid of the Tridion Broker as part of a project and publish content directly to a repository as part of a Storage Extension.
My question is, is there any deep dependency that Tridion has on the Broker that might mean things work in a sub-optimal way, or gotchas that I should be aware of?
Update - We are going to be using Tridion purely as a content store which will push out JSON. There will be no functionality or any form of business logic/UI. | 2013/07/25 | [
"https://tridion.stackexchange.com/questions/2318",
"https://tridion.stackexchange.com",
"https://tridion.stackexchange.com/users/315/"
] | I would be vary wary of any approach that removes all Content Delivery functionality, or the ability to hook into it. Customers I have seen that take this approach due to whatever requirements, tend to become very dissatisfied in the long term. Usually they bought Tridion for the whole package of functionality, CM + CD.
Some typical issues are:
1. Upgrading - if you build your own Content Delivery framework, this needs to be tested and updated before the client can upgrade their Tridion version. Maybe the people/organization that created the framework have moved on, and no-one knows how the heck it works any more anyway. I have even had customers who didnt even have the source code for their framework!
2. New product features - Tridion releases a new version or module with feature X that is amazing. The sales guy does the hard sell, the customer MUST have it... but wait - it requires Content Delivery elements, which are not part of your framework
So think carefully before following this route. You can still publish JSON to Elastic Store with Tridion, but I would try to keep standard Tridion CD for as much as possible... | This sounds like an unusual implementation.
It might be worth blueprinting your website to allow you to localize the templates to render the json. The new child publication could be used with a new deployer for you to test if this gives you the output you need without any missing functionality. |
32,869,080 | I've a class A like that:
```
public class A
{
private String id; // Generated on server
private DateTime timestamp;
private int trash;
private Humanity.FeedTypeEnum feedType
private List<Property> properties;
// ...
```
where `Property` is:
```
public class Property
{
private Humanity.PropertyTypeEnum type;
private string key;
private object value;
//...
```
I'd like to build a dynamic object that flat `List<Property> properties` A's field to raw properties. For example:
```
A a = new A();
a.Id = "Id";
a.Timestamp = DateTime.Now;
a.Trash = 2;
a.FeedType = Humanity.FeedTypeEnum.Mail;
a.Properties = new List<Property>()
{
new Property()
{
Type = Humanity.PropertyTypeEnum.String,
Key = "name"
Value = "file1.pdf"
},
new Property()
{
Type = Humanity.PropertyTypeEnum.Timestamp,
Key = "creationDate",
Value = Datetime.Now
}
}
```
As I've commented I'd like to flat this `a` object in order to access to the properties as:
```
String name = a.Name;
DateTime creationDate = a.CreationDate;
a.Name = "otherName";
a.CreationDate = creationDate.AddDays(1);
```
I've achieved that using Reflection. However, I'm figuring out that it's a best option using `ExpandoObject`.
The question is, how can I do that using `ExpandoObject` class? | 2015/09/30 | [
"https://Stackoverflow.com/questions/32869080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3227319/"
] | You can do what you want extending `DynamicObject` class:
```
class A : System.Dynamic.DynamicObject
{
// Other members
public List<Property> properties;
private readonly Dictionary<string, object> _membersDict = new Dictionary<string, object>();
public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
{
result = null;
if (!_membersDict.ContainsKey(binder.Name))
return false;
result = _membersDict[binder.Name];
return true;
}
public override bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value)
{
if (!_membersDict.ContainsKey(binder.Name))
return false;
_membersDict[binder.Name] = value;
return true;
}
public void CreateProperties()
{
foreach (Property prop in properties)
{
if (!_membersDict.ContainsKey(prop.key))
{
_membersDict.Add(prop.key, prop.value);
}
}
}
}
```
Then use it like that:
```
A a = new A();
/////////
a.Properties = new List<Property>()
{
new Property()
{
Type = Humanity.PropertyTypeEnum.String, // Now this property is useless, the value field has already a type, if you want you can add some logic around with this property to ensure that value will always be the same type
Key = "name"
Value = "file1.pdf"
},
new Property()
{
Type = Humanity.PropertyTypeEnum.Timestamp,
Key = "creationDate",
Value = Datetime.Now
}
}
a.CreateProperties();
dynamic dynA = a;
dynA.name = "value1";
``` | This method just overrides the square bracket operator. Not as slick as what you wanted but simpler and workable.
You definitely can't have design time (when you write code) features like you described.
You could make it work with reflection at run-time but surely not the way you showed right?
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
A a = new A();
a.properties = new List<Property>()
{
new Property(Humanity.PropertyTypeEnum.String, "name", "file1.pdf"),
new Property(Humanity.PropertyTypeEnum.Timestamp, "creationDate", DateTime.Now)
};
//String name = a.Name;
//DateTime creationDate = a.CreationDate;
//a.Name = "otherName";
//a.CreationDate = creationDate.AddDays(1);
String name = (String)a["name"];
DateTime creationDate = (DateTime)a["creationDate"];
a["name"] = "otherName";
a["creationDate"] = creationDate.AddDays(1);
}
public class A
{
private Dictionary<Property, object> myvalues = new Dictionary<Property, object>();
public List<Property> properties;
public object this[string name]
{
get
{
var prop = properties.Find(p => p.key == name);
if (prop == null)
throw new Exception("property " + name + " not found.");
return prop.value;
}
set
{
var prop = properties.Find(p => p.key == name);
if (prop == null)
throw new Exception("property " + name + " not found.");
prop.value = value;
}
}
}
public class Property
{
public Property(Humanity.PropertyTypeEnum type, string key, object value) { this.type = type; this.key = key; this.value = value; }
private Humanity.PropertyTypeEnum type;
public string key;
public object value;
}
}
}
namespace Humanity
{
public enum PropertyTypeEnum { String, Timestamp };
public enum FeedTypeEnum { };
}
``` |
64,018,695 | My program always outpout test which should not happen. Its like the program is skipping the case to go to default right away. I don't understand why it does that. I've spent 30 mins to find a solution but I can't understand why it does that.
Thanks for helping me !
```
var ani;
let ans;
let prix;
var total;
var arm1;
var arm2;
let nombrearmure;
nombrearmure = 0;
ani = prompt("Entrez votre type d'animal : ");
switch (ani.toLowerCase) {
case 'c' :
ans = prompt('Voulez vous acheter une épée pour 100$ ? : ');
if (ans.toLowerCase() === 'o'){
prix = 100;
nombrearmure = 1;
} else {
if (ans.toLowerCase() === 'n') {
console.log('Épée refusé');
} else {
console.log('Réponse non valide');
}
}
ans = prompt('Voulez vous acheter une corne de licorne pour 500 $ ? : ');
if(ans.toLowerCase() === 'o'){
prix = prix+500;
nombrearmure = nombrearmure + 2;
} else {
if (ans.toLowerCase() === 'n'){
console.log('Corne de licorne refusé');
} else {
console.log('Réponse invalide');
}
}
break;
case 'l' :
ans = prompt('Voulez vous acheter un casque(100-200$) : ');
if (ans.toLowerCase() === 'o'){
ans = parseInt(prompt('Appuyez sur 1 pour un casque noir (100$) ou 2 pour un casque multicolore (200$) : '));
switch(ans){
case 1 :
prix = 100;
nombrearmure = 1;
break;
case 2 :
prix = 200
nombrearmure = 2;
break;
default :
console.log('Réponse invalide')
return 1;
}
} else {
if(ans.toLowerCase === 'n'){
console.log('Casque refusé');
} else {
}
}
default:
console.log('test');
}
``` | 2020/09/22 | [
"https://Stackoverflow.com/questions/64018695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14323955/"
] | You are doing `ani.toLowerCase`. It should be `ani.toLowerCase()`. Also remove the return 1. | You didn't call the lowerCase function, invoke it.
Also, remove the return statement,
Now if you try to enter 'l' or 'c' letter it will work
```js
var ani;
let ans;
let prix;
var total;
var arm1;
var arm2;
let nombrearmure;
nombrearmure = 0;
ani = prompt("Entrez votre type d'animal : ");
switch (ani.toLowerCase()) {
case 'c':
ans = prompt('Voulez vous acheter une épée pour 100$ ? : ');
if (ans.toLowerCase() === 'o') {
prix = 100;
nombrearmure = 1;
} else {
if (ans.toLowerCase() === 'n') {
console.log('Épée refusé');
} else {
console.log('Réponse non valide');
}
}
ans = prompt('Voulez vous acheter une corne de licorne pour 500 $ ? : ');
if (ans.toLowerCase() === 'o') {
prix = prix + 500;
nombrearmure = nombrearmure + 2;
} else {
if (ans.toLowerCase() === 'n') {
console.log('Corne de licorne refusé');
} else {
console.log('Réponse invalide');
}
}
break;
case 'l':
ans = prompt('Voulez vous acheter un casque(100-200$) : ');
if (ans.toLowerCase() === 'o') {
ans = parseInt(prompt('Appuyez sur 1 pour un casque noir (100$) ou 2 pour un casque multicolore (200$) : '));
switch (ans) {
case 1:
prix = 100;
nombrearmure = 1;
break;
case 2:
prix = 200
nombrearmure = 2;
break;
default:
console.log('Réponse invalide')
}
} else {
if (ans.toLowerCase === 'n') {
console.log('Casque refusé');
} else {
}
}
default:
console.log('test');
}
``` |
59,973 | I want to register a sidebar but I am a little confused about the uses of the `id` argument in [`register_sidebar`](http://codex.wordpress.org/Function_Reference/register_sidebar) function.
>
> Codex says: id - Sidebar id - Must be all in lowercase, with no spaces
> (default is a numeric auto-incremented ID).
>
>
>
Of what use is the `id` argument and must it always be in numeric form?. | 2012/07/28 | [
"https://wordpress.stackexchange.com/questions/59973",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11125/"
] | John Landells’ answer is good and correct.
I want to add a **List of forbidden or reserved IDs** – these IDs may appear on the widget config page `/wp-admin/widgets.php`. If you use one of these … strange things will happen due to duplicated IDs. Drag and drop will probably not work anymore. See [Ticket #14466](http://core.trac.wordpress.org/ticket/14466) for the most obvious case: `#footer`.
**Update, Sept. 17.:** `#footer` will be [allowed in WP 3.5](http://core.trac.wordpress.org/changeset/21878).
**Update, Nov., 06.:** Per [ticket 14466](http://core.trac.wordpress.org/ticket/14466) all widget IDs in `widgets.php` are prefixed with `sidebar-` now. The following list will be obsolete with WordPress 3.5. Probably.
Also, an ID should not start with a number, that’s invalid HTML.
Installed plugins affecting this list: [Debug Bar](http://wordpress.org/extend/plugins/debug-bar/), [Debug Bar Cron](http://wordpress.org/extend/plugins/debug-bar-cron/), [Monster Widget](http://wordpress.org/extend/plugins/monster-widget/).
```none
#_wpnonce_widgets
#ab-awaiting-mod
#access-off
#access-on
#adminmenu
#adminmenuback
#adminmenushadow
#adminmenuwrap
#adv-settings
#available-widgets
#collapse-button
#collapse-menu
#colors-css
#contextual-help-back
#contextual-help-columns
#contextual-help-link
#contextual-help-link-wrap
#contextual-help-wrap
#debug-bar-actions
#debug-bar-cron
#debug-bar-css
#debug-bar-info
#debug-bar-menu
#debug-bar-wp-query
#debug-menu-link-Debug_Bar_Object_Cache
#debug-menu-link-Debug_Bar_Queries
#debug-menu-link-Debug_Bar_WP_Query
#debug-menu-link-ZT_Debug_Bar_Cron
#debug-menu-links
#debug-menu-target-Debug_Bar_Object_Cache
#debug-menu-target-Debug_Bar_Queries
#debug-menu-target-Debug_Bar_WP_Query
#debug-menu-target-ZT_Debug_Bar_Cron
#debug-menu-targets
#debug-status
#debug-status-db
#debug-status-memory
#debug-status-php
#debug-status-site
#footer
#footer-left
#footer-thankyou
#footer-upgrade
#icon-themes
#menu-appearance
#menu-comments
#menu-dashboard
#menu-links
#menu-media
#menu-pages
#menu-plugins
#menu-posts
#menu-posts-domicile
#menu-settings
#menu-tools
#menu-users
#object-cache-stats
#querylist
#removing-widget
#rss-items-2
#rss-items-__i__
#rss-show-author-2
#rss-show-author-__i__
#rss-show-date-2
#rss-show-date-__i__
#rss-show-summary-2
#rss-show-summary-__i__
#rss-title-2
#rss-title-__i__
#rss-url-2
#rss-url-__i__
#screen-meta
#screen-meta-links
#screen-options-link-wrap
#screen-options-wrap
#screenoptionnonce
#show-settings-link
#tab-link-missing-widgets
#tab-link-overview
#tab-link-removing-reusing
#tab-panel-missing-widgets
#tab-panel-overview
#tab-panel-removing-reusing
#widget-10_recent-posts-__i__
#widget-11_rss-__i__
#widget-12_search-__i__
#widget-13_tag_cloud-__i__
#widget-14_text-__i__
#widget-15_widget_twentyeleven_ephemera-__i__
#widget-16_rss-2
#widget-1_archives-__i__
#widget-2_calendar-__i__
#widget-3_categories-__i__
#widget-4_nav_menu-__i__
#widget-5_links-__i__
#widget-6_meta-__i__
#widget-7_monster-__i__
#widget-8_pages-__i__
#widget-9_recent-comments-__i__
#widget-archives-__i__-count
#widget-archives-__i__-dropdown
#widget-archives-__i__-savewidget
#widget-archives-__i__-title
#widget-calendar-__i__-savewidget
#widget-calendar-__i__-title
#widget-categories-__i__-count
#widget-categories-__i__-dropdown
#widget-categories-__i__-hierarchical
#widget-categories-__i__-savewidget
#widget-categories-__i__-title
#widget-links-__i__-category
#widget-links-__i__-description
#widget-links-__i__-images
#widget-links-__i__-limit
#widget-links-__i__-name
#widget-links-__i__-orderby
#widget-links-__i__-rating
#widget-links-__i__-savewidget
#widget-list
#widget-meta-__i__-savewidget
#widget-meta-__i__-title
#widget-monster-__i__-savewidget
#widget-nav_menu-__i__-nav_menu
#widget-nav_menu-__i__-savewidget
#widget-nav_menu-__i__-title
#widget-pages-__i__-exclude
#widget-pages-__i__-savewidget
#widget-pages-__i__-sortby
#widget-pages-__i__-title
#widget-recent-comments-__i__-number
#widget-recent-comments-__i__-savewidget
#widget-recent-comments-__i__-title
#widget-recent-posts-__i__-number
#widget-recent-posts-__i__-savewidget
#widget-recent-posts-__i__-title
#widget-rss-2-savewidget
#widget-rss-__i__-savewidget
#widget-search-__i__-savewidget
#widget-search-__i__-title
#widget-tag_cloud-__i__-savewidget
#widget-tag_cloud-__i__-taxonomy
#widget-tag_cloud-__i__-title
#widget-text-__i__-filter
#widget-text-__i__-savewidget
#widget-text-__i__-text
#widget-text-__i__-title
#widget-widget_twentyeleven_ephemera-__i__-number
#widget-widget_twentyeleven_ephemera-__i__-savewidget
#widget-widget_twentyeleven_ephemera-__i__-title
#widgets-left
#widgets-right
#wp-admin-bar-a8c_developer
#wp-admin-bar-comments
#wp-admin-bar-debug-bar
#wp-admin-bar-edit-profile
#wp-admin-bar-logout
#wp-admin-bar-my-account
#wp-admin-bar-new-content
#wp-admin-bar-new-content-default
#wp-admin-bar-new-domicile
#wp-admin-bar-new-link
#wp-admin-bar-new-media
#wp-admin-bar-new-page
#wp-admin-bar-new-post
#wp-admin-bar-new-user
#wp-admin-bar-root-default
#wp-admin-bar-site-name
#wp-admin-bar-site-name-default
#wp-admin-bar-top-secondary
#wp-admin-bar-updates
#wp-admin-bar-user-actions
#wp-admin-bar-user-info
#wp-admin-bar-view-site
#wp_inactive_widgets
#wpadminbar
#wpbody
#wpbody-content
#wpcontent
#wpwrap
#zt-debug-bar-cron-css
```
I collected the IDs with a small plugin that can be used on any page:
```php
<?php # -*- coding: utf-8 -*-
/* Plugin Name: T5 List IDs */
add_action( 'shutdown', function()
{ ?>
<script>
jQuery( function( $ )
{
var els = []
$( '[id]' ).each( function() { els.push( this.id ) } )
els.sort()
var pre = $( '<pre/>' ).css( 'margin','10px' ).html( '#'+els.join( '<br>#' ) )
$( document.documentElement ).append( pre )
})
</script><?php
}
);
``` | The sidebar ID is used to uniquely identify this specific sidebar. If you don't set it and something creates another, you could find that your sidebar moves somewhere unexpected!
It doesn't need to be numeric - you can use strings, too. |
59,973 | I want to register a sidebar but I am a little confused about the uses of the `id` argument in [`register_sidebar`](http://codex.wordpress.org/Function_Reference/register_sidebar) function.
>
> Codex says: id - Sidebar id - Must be all in lowercase, with no spaces
> (default is a numeric auto-incremented ID).
>
>
>
Of what use is the `id` argument and must it always be in numeric form?. | 2012/07/28 | [
"https://wordpress.stackexchange.com/questions/59973",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11125/"
] | The sidebar ID is used to uniquely identify this specific sidebar. If you don't set it and something creates another, you could find that your sidebar moves somewhere unexpected!
It doesn't need to be numeric - you can use strings, too. | You have to avoid multiple `-` characters, like `test1---test2` |
59,973 | I want to register a sidebar but I am a little confused about the uses of the `id` argument in [`register_sidebar`](http://codex.wordpress.org/Function_Reference/register_sidebar) function.
>
> Codex says: id - Sidebar id - Must be all in lowercase, with no spaces
> (default is a numeric auto-incremented ID).
>
>
>
Of what use is the `id` argument and must it always be in numeric form?. | 2012/07/28 | [
"https://wordpress.stackexchange.com/questions/59973",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11125/"
] | The sidebar ID is used to uniquely identify this specific sidebar. If you don't set it and something creates another, you could find that your sidebar moves somewhere unexpected!
It doesn't need to be numeric - you can use strings, too. | Apparently, you have to avoid IDs that include prefixes from the above list as well:
e.g.:
```
#footer-xxx
#footer-yyy
```
The following setup initially worked, but resulted in errors (using the monsoon theme):
```
register_sidebar( array(
'name' => esc_html__( 'Footer Area', 'monsoon' ),
'id' => 'footer-area',
'description' => esc_html__( 'Appears above the footer.', 'monsoon' ),
'before_widget' => '<div class="col-sm-3 footer-area widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
) );
```
By renaming the sidebar, the errors disappeared. I haven't tested on other themes, though. So this might only be applicable to my setup.
However, thus thread really helped me in my search for a solution :) |
59,973 | I want to register a sidebar but I am a little confused about the uses of the `id` argument in [`register_sidebar`](http://codex.wordpress.org/Function_Reference/register_sidebar) function.
>
> Codex says: id - Sidebar id - Must be all in lowercase, with no spaces
> (default is a numeric auto-incremented ID).
>
>
>
Of what use is the `id` argument and must it always be in numeric form?. | 2012/07/28 | [
"https://wordpress.stackexchange.com/questions/59973",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11125/"
] | John Landells’ answer is good and correct.
I want to add a **List of forbidden or reserved IDs** – these IDs may appear on the widget config page `/wp-admin/widgets.php`. If you use one of these … strange things will happen due to duplicated IDs. Drag and drop will probably not work anymore. See [Ticket #14466](http://core.trac.wordpress.org/ticket/14466) for the most obvious case: `#footer`.
**Update, Sept. 17.:** `#footer` will be [allowed in WP 3.5](http://core.trac.wordpress.org/changeset/21878).
**Update, Nov., 06.:** Per [ticket 14466](http://core.trac.wordpress.org/ticket/14466) all widget IDs in `widgets.php` are prefixed with `sidebar-` now. The following list will be obsolete with WordPress 3.5. Probably.
Also, an ID should not start with a number, that’s invalid HTML.
Installed plugins affecting this list: [Debug Bar](http://wordpress.org/extend/plugins/debug-bar/), [Debug Bar Cron](http://wordpress.org/extend/plugins/debug-bar-cron/), [Monster Widget](http://wordpress.org/extend/plugins/monster-widget/).
```none
#_wpnonce_widgets
#ab-awaiting-mod
#access-off
#access-on
#adminmenu
#adminmenuback
#adminmenushadow
#adminmenuwrap
#adv-settings
#available-widgets
#collapse-button
#collapse-menu
#colors-css
#contextual-help-back
#contextual-help-columns
#contextual-help-link
#contextual-help-link-wrap
#contextual-help-wrap
#debug-bar-actions
#debug-bar-cron
#debug-bar-css
#debug-bar-info
#debug-bar-menu
#debug-bar-wp-query
#debug-menu-link-Debug_Bar_Object_Cache
#debug-menu-link-Debug_Bar_Queries
#debug-menu-link-Debug_Bar_WP_Query
#debug-menu-link-ZT_Debug_Bar_Cron
#debug-menu-links
#debug-menu-target-Debug_Bar_Object_Cache
#debug-menu-target-Debug_Bar_Queries
#debug-menu-target-Debug_Bar_WP_Query
#debug-menu-target-ZT_Debug_Bar_Cron
#debug-menu-targets
#debug-status
#debug-status-db
#debug-status-memory
#debug-status-php
#debug-status-site
#footer
#footer-left
#footer-thankyou
#footer-upgrade
#icon-themes
#menu-appearance
#menu-comments
#menu-dashboard
#menu-links
#menu-media
#menu-pages
#menu-plugins
#menu-posts
#menu-posts-domicile
#menu-settings
#menu-tools
#menu-users
#object-cache-stats
#querylist
#removing-widget
#rss-items-2
#rss-items-__i__
#rss-show-author-2
#rss-show-author-__i__
#rss-show-date-2
#rss-show-date-__i__
#rss-show-summary-2
#rss-show-summary-__i__
#rss-title-2
#rss-title-__i__
#rss-url-2
#rss-url-__i__
#screen-meta
#screen-meta-links
#screen-options-link-wrap
#screen-options-wrap
#screenoptionnonce
#show-settings-link
#tab-link-missing-widgets
#tab-link-overview
#tab-link-removing-reusing
#tab-panel-missing-widgets
#tab-panel-overview
#tab-panel-removing-reusing
#widget-10_recent-posts-__i__
#widget-11_rss-__i__
#widget-12_search-__i__
#widget-13_tag_cloud-__i__
#widget-14_text-__i__
#widget-15_widget_twentyeleven_ephemera-__i__
#widget-16_rss-2
#widget-1_archives-__i__
#widget-2_calendar-__i__
#widget-3_categories-__i__
#widget-4_nav_menu-__i__
#widget-5_links-__i__
#widget-6_meta-__i__
#widget-7_monster-__i__
#widget-8_pages-__i__
#widget-9_recent-comments-__i__
#widget-archives-__i__-count
#widget-archives-__i__-dropdown
#widget-archives-__i__-savewidget
#widget-archives-__i__-title
#widget-calendar-__i__-savewidget
#widget-calendar-__i__-title
#widget-categories-__i__-count
#widget-categories-__i__-dropdown
#widget-categories-__i__-hierarchical
#widget-categories-__i__-savewidget
#widget-categories-__i__-title
#widget-links-__i__-category
#widget-links-__i__-description
#widget-links-__i__-images
#widget-links-__i__-limit
#widget-links-__i__-name
#widget-links-__i__-orderby
#widget-links-__i__-rating
#widget-links-__i__-savewidget
#widget-list
#widget-meta-__i__-savewidget
#widget-meta-__i__-title
#widget-monster-__i__-savewidget
#widget-nav_menu-__i__-nav_menu
#widget-nav_menu-__i__-savewidget
#widget-nav_menu-__i__-title
#widget-pages-__i__-exclude
#widget-pages-__i__-savewidget
#widget-pages-__i__-sortby
#widget-pages-__i__-title
#widget-recent-comments-__i__-number
#widget-recent-comments-__i__-savewidget
#widget-recent-comments-__i__-title
#widget-recent-posts-__i__-number
#widget-recent-posts-__i__-savewidget
#widget-recent-posts-__i__-title
#widget-rss-2-savewidget
#widget-rss-__i__-savewidget
#widget-search-__i__-savewidget
#widget-search-__i__-title
#widget-tag_cloud-__i__-savewidget
#widget-tag_cloud-__i__-taxonomy
#widget-tag_cloud-__i__-title
#widget-text-__i__-filter
#widget-text-__i__-savewidget
#widget-text-__i__-text
#widget-text-__i__-title
#widget-widget_twentyeleven_ephemera-__i__-number
#widget-widget_twentyeleven_ephemera-__i__-savewidget
#widget-widget_twentyeleven_ephemera-__i__-title
#widgets-left
#widgets-right
#wp-admin-bar-a8c_developer
#wp-admin-bar-comments
#wp-admin-bar-debug-bar
#wp-admin-bar-edit-profile
#wp-admin-bar-logout
#wp-admin-bar-my-account
#wp-admin-bar-new-content
#wp-admin-bar-new-content-default
#wp-admin-bar-new-domicile
#wp-admin-bar-new-link
#wp-admin-bar-new-media
#wp-admin-bar-new-page
#wp-admin-bar-new-post
#wp-admin-bar-new-user
#wp-admin-bar-root-default
#wp-admin-bar-site-name
#wp-admin-bar-site-name-default
#wp-admin-bar-top-secondary
#wp-admin-bar-updates
#wp-admin-bar-user-actions
#wp-admin-bar-user-info
#wp-admin-bar-view-site
#wp_inactive_widgets
#wpadminbar
#wpbody
#wpbody-content
#wpcontent
#wpwrap
#zt-debug-bar-cron-css
```
I collected the IDs with a small plugin that can be used on any page:
```php
<?php # -*- coding: utf-8 -*-
/* Plugin Name: T5 List IDs */
add_action( 'shutdown', function()
{ ?>
<script>
jQuery( function( $ )
{
var els = []
$( '[id]' ).each( function() { els.push( this.id ) } )
els.sort()
var pre = $( '<pre/>' ).css( 'margin','10px' ).html( '#'+els.join( '<br>#' ) )
$( document.documentElement ).append( pre )
})
</script><?php
}
);
``` | You have to avoid multiple `-` characters, like `test1---test2` |
59,973 | I want to register a sidebar but I am a little confused about the uses of the `id` argument in [`register_sidebar`](http://codex.wordpress.org/Function_Reference/register_sidebar) function.
>
> Codex says: id - Sidebar id - Must be all in lowercase, with no spaces
> (default is a numeric auto-incremented ID).
>
>
>
Of what use is the `id` argument and must it always be in numeric form?. | 2012/07/28 | [
"https://wordpress.stackexchange.com/questions/59973",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11125/"
] | John Landells’ answer is good and correct.
I want to add a **List of forbidden or reserved IDs** – these IDs may appear on the widget config page `/wp-admin/widgets.php`. If you use one of these … strange things will happen due to duplicated IDs. Drag and drop will probably not work anymore. See [Ticket #14466](http://core.trac.wordpress.org/ticket/14466) for the most obvious case: `#footer`.
**Update, Sept. 17.:** `#footer` will be [allowed in WP 3.5](http://core.trac.wordpress.org/changeset/21878).
**Update, Nov., 06.:** Per [ticket 14466](http://core.trac.wordpress.org/ticket/14466) all widget IDs in `widgets.php` are prefixed with `sidebar-` now. The following list will be obsolete with WordPress 3.5. Probably.
Also, an ID should not start with a number, that’s invalid HTML.
Installed plugins affecting this list: [Debug Bar](http://wordpress.org/extend/plugins/debug-bar/), [Debug Bar Cron](http://wordpress.org/extend/plugins/debug-bar-cron/), [Monster Widget](http://wordpress.org/extend/plugins/monster-widget/).
```none
#_wpnonce_widgets
#ab-awaiting-mod
#access-off
#access-on
#adminmenu
#adminmenuback
#adminmenushadow
#adminmenuwrap
#adv-settings
#available-widgets
#collapse-button
#collapse-menu
#colors-css
#contextual-help-back
#contextual-help-columns
#contextual-help-link
#contextual-help-link-wrap
#contextual-help-wrap
#debug-bar-actions
#debug-bar-cron
#debug-bar-css
#debug-bar-info
#debug-bar-menu
#debug-bar-wp-query
#debug-menu-link-Debug_Bar_Object_Cache
#debug-menu-link-Debug_Bar_Queries
#debug-menu-link-Debug_Bar_WP_Query
#debug-menu-link-ZT_Debug_Bar_Cron
#debug-menu-links
#debug-menu-target-Debug_Bar_Object_Cache
#debug-menu-target-Debug_Bar_Queries
#debug-menu-target-Debug_Bar_WP_Query
#debug-menu-target-ZT_Debug_Bar_Cron
#debug-menu-targets
#debug-status
#debug-status-db
#debug-status-memory
#debug-status-php
#debug-status-site
#footer
#footer-left
#footer-thankyou
#footer-upgrade
#icon-themes
#menu-appearance
#menu-comments
#menu-dashboard
#menu-links
#menu-media
#menu-pages
#menu-plugins
#menu-posts
#menu-posts-domicile
#menu-settings
#menu-tools
#menu-users
#object-cache-stats
#querylist
#removing-widget
#rss-items-2
#rss-items-__i__
#rss-show-author-2
#rss-show-author-__i__
#rss-show-date-2
#rss-show-date-__i__
#rss-show-summary-2
#rss-show-summary-__i__
#rss-title-2
#rss-title-__i__
#rss-url-2
#rss-url-__i__
#screen-meta
#screen-meta-links
#screen-options-link-wrap
#screen-options-wrap
#screenoptionnonce
#show-settings-link
#tab-link-missing-widgets
#tab-link-overview
#tab-link-removing-reusing
#tab-panel-missing-widgets
#tab-panel-overview
#tab-panel-removing-reusing
#widget-10_recent-posts-__i__
#widget-11_rss-__i__
#widget-12_search-__i__
#widget-13_tag_cloud-__i__
#widget-14_text-__i__
#widget-15_widget_twentyeleven_ephemera-__i__
#widget-16_rss-2
#widget-1_archives-__i__
#widget-2_calendar-__i__
#widget-3_categories-__i__
#widget-4_nav_menu-__i__
#widget-5_links-__i__
#widget-6_meta-__i__
#widget-7_monster-__i__
#widget-8_pages-__i__
#widget-9_recent-comments-__i__
#widget-archives-__i__-count
#widget-archives-__i__-dropdown
#widget-archives-__i__-savewidget
#widget-archives-__i__-title
#widget-calendar-__i__-savewidget
#widget-calendar-__i__-title
#widget-categories-__i__-count
#widget-categories-__i__-dropdown
#widget-categories-__i__-hierarchical
#widget-categories-__i__-savewidget
#widget-categories-__i__-title
#widget-links-__i__-category
#widget-links-__i__-description
#widget-links-__i__-images
#widget-links-__i__-limit
#widget-links-__i__-name
#widget-links-__i__-orderby
#widget-links-__i__-rating
#widget-links-__i__-savewidget
#widget-list
#widget-meta-__i__-savewidget
#widget-meta-__i__-title
#widget-monster-__i__-savewidget
#widget-nav_menu-__i__-nav_menu
#widget-nav_menu-__i__-savewidget
#widget-nav_menu-__i__-title
#widget-pages-__i__-exclude
#widget-pages-__i__-savewidget
#widget-pages-__i__-sortby
#widget-pages-__i__-title
#widget-recent-comments-__i__-number
#widget-recent-comments-__i__-savewidget
#widget-recent-comments-__i__-title
#widget-recent-posts-__i__-number
#widget-recent-posts-__i__-savewidget
#widget-recent-posts-__i__-title
#widget-rss-2-savewidget
#widget-rss-__i__-savewidget
#widget-search-__i__-savewidget
#widget-search-__i__-title
#widget-tag_cloud-__i__-savewidget
#widget-tag_cloud-__i__-taxonomy
#widget-tag_cloud-__i__-title
#widget-text-__i__-filter
#widget-text-__i__-savewidget
#widget-text-__i__-text
#widget-text-__i__-title
#widget-widget_twentyeleven_ephemera-__i__-number
#widget-widget_twentyeleven_ephemera-__i__-savewidget
#widget-widget_twentyeleven_ephemera-__i__-title
#widgets-left
#widgets-right
#wp-admin-bar-a8c_developer
#wp-admin-bar-comments
#wp-admin-bar-debug-bar
#wp-admin-bar-edit-profile
#wp-admin-bar-logout
#wp-admin-bar-my-account
#wp-admin-bar-new-content
#wp-admin-bar-new-content-default
#wp-admin-bar-new-domicile
#wp-admin-bar-new-link
#wp-admin-bar-new-media
#wp-admin-bar-new-page
#wp-admin-bar-new-post
#wp-admin-bar-new-user
#wp-admin-bar-root-default
#wp-admin-bar-site-name
#wp-admin-bar-site-name-default
#wp-admin-bar-top-secondary
#wp-admin-bar-updates
#wp-admin-bar-user-actions
#wp-admin-bar-user-info
#wp-admin-bar-view-site
#wp_inactive_widgets
#wpadminbar
#wpbody
#wpbody-content
#wpcontent
#wpwrap
#zt-debug-bar-cron-css
```
I collected the IDs with a small plugin that can be used on any page:
```php
<?php # -*- coding: utf-8 -*-
/* Plugin Name: T5 List IDs */
add_action( 'shutdown', function()
{ ?>
<script>
jQuery( function( $ )
{
var els = []
$( '[id]' ).each( function() { els.push( this.id ) } )
els.sort()
var pre = $( '<pre/>' ).css( 'margin','10px' ).html( '#'+els.join( '<br>#' ) )
$( document.documentElement ).append( pre )
})
</script><?php
}
);
``` | Apparently, you have to avoid IDs that include prefixes from the above list as well:
e.g.:
```
#footer-xxx
#footer-yyy
```
The following setup initially worked, but resulted in errors (using the monsoon theme):
```
register_sidebar( array(
'name' => esc_html__( 'Footer Area', 'monsoon' ),
'id' => 'footer-area',
'description' => esc_html__( 'Appears above the footer.', 'monsoon' ),
'before_widget' => '<div class="col-sm-3 footer-area widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
) );
```
By renaming the sidebar, the errors disappeared. I haven't tested on other themes, though. So this might only be applicable to my setup.
However, thus thread really helped me in my search for a solution :) |
17,435,950 | I am trying to improve the performance of a hammered wordpress DB by adding indexes to queries that appear in the slow query log.
In MS SQL you can use query hints to force a query to use an index but it is usually quite easy to get a query to use an index if you cover the columns correctly etc.
I have this query that appears in the slow query log a lot
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish')
ORDER BY wp_posts.post_date DESC
LIMIT 18310, 5;
```
I created a covering unique index on `wp_posts` on `post_date, post_status, post_type and post_id` and restarted MySQL however when I run explain the index used is
```
status_password_id
```
and in the possible keys my new index doesn't even appear although it's a covering index e.g I just get
```
type_status_date,status_password_id
```
Therefore neither the used index or the possible choices the "optimiser" if MySQL has one is even considering my index which has post\_date as the first column. I would have thought a query that is basically doing a TOP and ordering by date with
```
ORDER BY wp_posts.post_date DESC LIMIT 18310, 5;
```
Would want to use an index sorted by date for speed, especially one that had all the other fields required to satisfy the query in it as well?
Does MySQL have query hints to force an index to be used for speed/performance tests or is there something else I need to do to see why this index is being ignored.
I would love it if Navicat had a Visual Query Execution Plan like MS SQL but it seems EXPLAIN is the best it has to offer.
Anyone with any hints on how I can either force the index to be used or work out why its being ignored would be very helpful!
Thanks | 2013/07/02 | [
"https://Stackoverflow.com/questions/17435950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037545/"
] | >
> Does MySQL have query hints to force an index to be used for speed/performance tests or is there something else I need to do to see why this index is being ignored.
>
>
>
[The documentation](http://dev.mysql.com/doc/refman/5.0/en/index-hints.html) answers this question in some detail:
>
> By specifying `USE INDEX`*`(index_list)`*, you can tell MySQL to use
> only one of the named indexes to find rows in the table. The
> alternative syntax `IGNORE INDEX`*`(index_list)`* can be used to tell
> MySQL to not use some particular index or indexes. These hints are
> useful if [`EXPLAIN`](http://dev.mysql.com/doc/refman/5.0/en/explain.html) shows that MySQL is using the wrong index
> from the list of possible indexes.
>
>
> You can also use `FORCE INDEX`, which acts like `USE INDEX`*`(index_list)`*
> but with the addition that a table scan is assumed to be *very
> expensive*. In other words, a table scan is used only if there is no
> way to use one of the given indexes to find rows in the table.
>
>
> Each hint requires the names of indexes, not the names of columns. The
> name of a `PRIMARY KEY` is `PRIMARY`. To see the index names for a
> table, use [`SHOW INDEX`](http://dev.mysql.com/doc/refman/5.0/en/show-index.html).
>
>
>
If `USE INDEX` doesn't work, try using `IGNORE INDEX` to see what the optimizer's second choice is (or third, and so on).
A simple example of the syntax would be:
```
SELECT * FROM t1 USE INDEX (i1) IGNORE INDEX (i2) WHERE ...
```
There are many more where that came from, in the linked docs. I've linked to the version 5.0 pages, but you can easily navigate to the appropriate version using the left sidebar; some additional syntax options are available as of version 5.1. | Try changing the order of your index definition to
```
post_type, post_status, post_date, post_id
```
or
```
post_date desc, post_type, post_status, post_id
``` |
17,435,950 | I am trying to improve the performance of a hammered wordpress DB by adding indexes to queries that appear in the slow query log.
In MS SQL you can use query hints to force a query to use an index but it is usually quite easy to get a query to use an index if you cover the columns correctly etc.
I have this query that appears in the slow query log a lot
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish')
ORDER BY wp_posts.post_date DESC
LIMIT 18310, 5;
```
I created a covering unique index on `wp_posts` on `post_date, post_status, post_type and post_id` and restarted MySQL however when I run explain the index used is
```
status_password_id
```
and in the possible keys my new index doesn't even appear although it's a covering index e.g I just get
```
type_status_date,status_password_id
```
Therefore neither the used index or the possible choices the "optimiser" if MySQL has one is even considering my index which has post\_date as the first column. I would have thought a query that is basically doing a TOP and ordering by date with
```
ORDER BY wp_posts.post_date DESC LIMIT 18310, 5;
```
Would want to use an index sorted by date for speed, especially one that had all the other fields required to satisfy the query in it as well?
Does MySQL have query hints to force an index to be used for speed/performance tests or is there something else I need to do to see why this index is being ignored.
I would love it if Navicat had a Visual Query Execution Plan like MS SQL but it seems EXPLAIN is the best it has to offer.
Anyone with any hints on how I can either force the index to be used or work out why its being ignored would be very helpful!
Thanks | 2013/07/02 | [
"https://Stackoverflow.com/questions/17435950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037545/"
] | MySQL 5.6 has support for a new format of EXPLAIN, which the [MySQL Workbench](http://www.mysql.com/products/workbench/) GUI can visualize in a more appealing way. But that doesn't help you if you're stuck on MySQL 5.5 or earlier.
MySQL does have hints as @AirThomas mentions, but you should really use them sparingly. In a simple query like the one you show, it should never be necessary to use index hints -- if you have the right index. And using index hints means you have hard-coded index names into your application, so if you add or drop indexes, you have to update your code.
In your query, an index on `(post_date, post_status, post_type, post_id)` is not going to help.
You want the left-most column in the index to be used for row restriction. So put `post_status, post_type` first. Best if the more selective column is first. That is, if `post_type = 'post'` matches 3% of the table, and `post_status = 'publish'` matches 1% of the table, then put post\_status first before post\_type.
Since you used `=` for both conditions and the `AND` operator, you know that all matching rows are basically tied with respect to those two columns. So if you use `post_date` as the third column in the index, then the optimizer knows it can fetch the rows in the order they are stored in the index, and it can skip doing any other work for the ORDER BY. You can see this working if "Using filesort" disappears from your EXPLAIN output.
So your index likely should be:
```
ALTER TABLE wp_posts ADD INDEX (post_status, post_type, post_date);
```
You may also enjoy my presentation [How to Design Indexes, Really](http://www.slideshare.net/billkarwin/how-to-design-indexes-really).
You don't need to add ID to the index in this case, because InnoDB indexes automatically contain the primary key column(s).
`LIMIT 18310, 5` is bound to be costly. MySQL has to generate the whole result set on the server side, up to 18315 rows, only to discard most of them. Who in the world needs to skip to the 3662nd page, anyway?!
`SQL_CALC_FOUND_ROWS` is a *major* performance killer when you have large result sets that you're paging through, because MySQL has to generate the *whole* result set, both before and after the page you requested. Best to get rid of that query modifier unless you really need `FOUND_ROWS()`, and even if you do need the number of rows, it can sometimes\* be quicker to run two queries, one with `SELECT COUNT(*)`.
(\* Test both ways to make sure.)
Here are some more tips on optimizing LIMIT:
* <http://www.mysqlperformanceblog.com/2006/09/01/order-by-limit-performance-optimization/>
* <http://www.mysqlperformanceblog.com/2008/09/24/four-ways-to-optimize-paginated-displays/>
* <http://dev.mysql.com/doc/refman/5.6/en/limit-optimization.html> | Try changing the order of your index definition to
```
post_type, post_status, post_date, post_id
```
or
```
post_date desc, post_type, post_status, post_id
``` |
17,435,950 | I am trying to improve the performance of a hammered wordpress DB by adding indexes to queries that appear in the slow query log.
In MS SQL you can use query hints to force a query to use an index but it is usually quite easy to get a query to use an index if you cover the columns correctly etc.
I have this query that appears in the slow query log a lot
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish')
ORDER BY wp_posts.post_date DESC
LIMIT 18310, 5;
```
I created a covering unique index on `wp_posts` on `post_date, post_status, post_type and post_id` and restarted MySQL however when I run explain the index used is
```
status_password_id
```
and in the possible keys my new index doesn't even appear although it's a covering index e.g I just get
```
type_status_date,status_password_id
```
Therefore neither the used index or the possible choices the "optimiser" if MySQL has one is even considering my index which has post\_date as the first column. I would have thought a query that is basically doing a TOP and ordering by date with
```
ORDER BY wp_posts.post_date DESC LIMIT 18310, 5;
```
Would want to use an index sorted by date for speed, especially one that had all the other fields required to satisfy the query in it as well?
Does MySQL have query hints to force an index to be used for speed/performance tests or is there something else I need to do to see why this index is being ignored.
I would love it if Navicat had a Visual Query Execution Plan like MS SQL but it seems EXPLAIN is the best it has to offer.
Anyone with any hints on how I can either force the index to be used or work out why its being ignored would be very helpful!
Thanks | 2013/07/02 | [
"https://Stackoverflow.com/questions/17435950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037545/"
] | Try changing the order of your index definition to
```
post_type, post_status, post_date, post_id
```
or
```
post_date desc, post_type, post_status, post_id
``` | Just to let you know I am on a different PC so my username has changed but I did write the original question.
What I think would be very helpful is a conversion guide to help people from MS SQL backgrounds covert to MySQL as it seems there's some difference in the index tuning I didn't realise especially that different storage engines automatically add in primary keys, plus how to handle the lack of tools to aid performance tuning.
I am used to creating my main clustered index, primary key and other unique constraints and indexes, then non-clustered indexes with included keys, some covering indexes etc.
I will then run a timed job to log the missing index DMV report to a table to prevent the data being lost during any restart. I can then run reports to check for indexes the SQL optimiser thinks "should" be used or those it is "not" using. I can then use this information, counters of mis-hits and potential efficiency percentage if the missing index was used, as a guide to help fine tune the indexing for performance.
As far as I can tell MySQL doesn't have anything similar to the DMV's MsSQL has?
The nice graphical execution plan built into MS SQL Studio from aeons ago helps with tuning a lot and the bog standard MySQL explain is poor in comparison. I will look into that tool you mentioned although running a select @@version returns 5.0.51a-24+lenny5-log so I doubt it will help me.
A couple of things though regarding the posts:
1. The aim was to have a covering index so no bookmark lookups (if you call them that in MySQL) were required and the data could come straight from the index.
2. As nearly all my posts are "published" (99.99%) and the post\_type is nearly all "post" (99.99%) with a tiny percentage of "pages". There is no selectivity in those two columns and they are in the index for the cover. I've turned off auto-drafts to prevent a build up of revisions etc and the number of drafts is very small.
3. Therefore I would have thought having the post\_date as the first key in the index would have been of more help as the LIMIT (as you say is expensive, and I have no control over Wordpress's code) therefore surely the ORDER BY and LIMIT (which is basically a TOP) would have been the most costly and selective part of the query and of more use to the index in comparison with the other keys (which are not selective at all). This is why I put it first.
4. I am using Wordpress and the table is wp\_posts and its storage engine is MyISAM which I believe I cannot change due to the requirement for it to have full text searching.
5. As I said to someone else I already have an index with the order **post\_type, post\_status and post\_date** but EXPLAIN only shows it in the possible keys and then ignores it to use the index based around these columns: **post\_status, password and id**.
6. As password is not used in the query and post\_status is totally unselective (as all my post\_types are "post") I am a loss to why MySQL's ***"clever" optimiser*** thinks this index should be selected above either the ones provided OR my own?
So I am still stuck as no suggestion seems to work.
I've tried changing the ordering several times and even though I only have 20k rows it takes half an hour or more each time! I don't know if this is normal in MySQL or not but in MSSQL it takes minutes to add/drop indexes on tables with millions of rows.
So as nothing has worked so far I want to know (why?) and obviously about query hints to see if that does any good at all.
I have re-started the DB after re-indexing (and even restarted the webserver).
Thanks for your help. |
17,435,950 | I am trying to improve the performance of a hammered wordpress DB by adding indexes to queries that appear in the slow query log.
In MS SQL you can use query hints to force a query to use an index but it is usually quite easy to get a query to use an index if you cover the columns correctly etc.
I have this query that appears in the slow query log a lot
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish')
ORDER BY wp_posts.post_date DESC
LIMIT 18310, 5;
```
I created a covering unique index on `wp_posts` on `post_date, post_status, post_type and post_id` and restarted MySQL however when I run explain the index used is
```
status_password_id
```
and in the possible keys my new index doesn't even appear although it's a covering index e.g I just get
```
type_status_date,status_password_id
```
Therefore neither the used index or the possible choices the "optimiser" if MySQL has one is even considering my index which has post\_date as the first column. I would have thought a query that is basically doing a TOP and ordering by date with
```
ORDER BY wp_posts.post_date DESC LIMIT 18310, 5;
```
Would want to use an index sorted by date for speed, especially one that had all the other fields required to satisfy the query in it as well?
Does MySQL have query hints to force an index to be used for speed/performance tests or is there something else I need to do to see why this index is being ignored.
I would love it if Navicat had a Visual Query Execution Plan like MS SQL but it seems EXPLAIN is the best it has to offer.
Anyone with any hints on how I can either force the index to be used or work out why its being ignored would be very helpful!
Thanks | 2013/07/02 | [
"https://Stackoverflow.com/questions/17435950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037545/"
] | >
> Does MySQL have query hints to force an index to be used for speed/performance tests or is there something else I need to do to see why this index is being ignored.
>
>
>
[The documentation](http://dev.mysql.com/doc/refman/5.0/en/index-hints.html) answers this question in some detail:
>
> By specifying `USE INDEX`*`(index_list)`*, you can tell MySQL to use
> only one of the named indexes to find rows in the table. The
> alternative syntax `IGNORE INDEX`*`(index_list)`* can be used to tell
> MySQL to not use some particular index or indexes. These hints are
> useful if [`EXPLAIN`](http://dev.mysql.com/doc/refman/5.0/en/explain.html) shows that MySQL is using the wrong index
> from the list of possible indexes.
>
>
> You can also use `FORCE INDEX`, which acts like `USE INDEX`*`(index_list)`*
> but with the addition that a table scan is assumed to be *very
> expensive*. In other words, a table scan is used only if there is no
> way to use one of the given indexes to find rows in the table.
>
>
> Each hint requires the names of indexes, not the names of columns. The
> name of a `PRIMARY KEY` is `PRIMARY`. To see the index names for a
> table, use [`SHOW INDEX`](http://dev.mysql.com/doc/refman/5.0/en/show-index.html).
>
>
>
If `USE INDEX` doesn't work, try using `IGNORE INDEX` to see what the optimizer's second choice is (or third, and so on).
A simple example of the syntax would be:
```
SELECT * FROM t1 USE INDEX (i1) IGNORE INDEX (i2) WHERE ...
```
There are many more where that came from, in the linked docs. I've linked to the version 5.0 pages, but you can easily navigate to the appropriate version using the left sidebar; some additional syntax options are available as of version 5.1. | MySQL 5.6 has support for a new format of EXPLAIN, which the [MySQL Workbench](http://www.mysql.com/products/workbench/) GUI can visualize in a more appealing way. But that doesn't help you if you're stuck on MySQL 5.5 or earlier.
MySQL does have hints as @AirThomas mentions, but you should really use them sparingly. In a simple query like the one you show, it should never be necessary to use index hints -- if you have the right index. And using index hints means you have hard-coded index names into your application, so if you add or drop indexes, you have to update your code.
In your query, an index on `(post_date, post_status, post_type, post_id)` is not going to help.
You want the left-most column in the index to be used for row restriction. So put `post_status, post_type` first. Best if the more selective column is first. That is, if `post_type = 'post'` matches 3% of the table, and `post_status = 'publish'` matches 1% of the table, then put post\_status first before post\_type.
Since you used `=` for both conditions and the `AND` operator, you know that all matching rows are basically tied with respect to those two columns. So if you use `post_date` as the third column in the index, then the optimizer knows it can fetch the rows in the order they are stored in the index, and it can skip doing any other work for the ORDER BY. You can see this working if "Using filesort" disappears from your EXPLAIN output.
So your index likely should be:
```
ALTER TABLE wp_posts ADD INDEX (post_status, post_type, post_date);
```
You may also enjoy my presentation [How to Design Indexes, Really](http://www.slideshare.net/billkarwin/how-to-design-indexes-really).
You don't need to add ID to the index in this case, because InnoDB indexes automatically contain the primary key column(s).
`LIMIT 18310, 5` is bound to be costly. MySQL has to generate the whole result set on the server side, up to 18315 rows, only to discard most of them. Who in the world needs to skip to the 3662nd page, anyway?!
`SQL_CALC_FOUND_ROWS` is a *major* performance killer when you have large result sets that you're paging through, because MySQL has to generate the *whole* result set, both before and after the page you requested. Best to get rid of that query modifier unless you really need `FOUND_ROWS()`, and even if you do need the number of rows, it can sometimes\* be quicker to run two queries, one with `SELECT COUNT(*)`.
(\* Test both ways to make sure.)
Here are some more tips on optimizing LIMIT:
* <http://www.mysqlperformanceblog.com/2006/09/01/order-by-limit-performance-optimization/>
* <http://www.mysqlperformanceblog.com/2008/09/24/four-ways-to-optimize-paginated-displays/>
* <http://dev.mysql.com/doc/refman/5.6/en/limit-optimization.html> |
17,435,950 | I am trying to improve the performance of a hammered wordpress DB by adding indexes to queries that appear in the slow query log.
In MS SQL you can use query hints to force a query to use an index but it is usually quite easy to get a query to use an index if you cover the columns correctly etc.
I have this query that appears in the slow query log a lot
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish')
ORDER BY wp_posts.post_date DESC
LIMIT 18310, 5;
```
I created a covering unique index on `wp_posts` on `post_date, post_status, post_type and post_id` and restarted MySQL however when I run explain the index used is
```
status_password_id
```
and in the possible keys my new index doesn't even appear although it's a covering index e.g I just get
```
type_status_date,status_password_id
```
Therefore neither the used index or the possible choices the "optimiser" if MySQL has one is even considering my index which has post\_date as the first column. I would have thought a query that is basically doing a TOP and ordering by date with
```
ORDER BY wp_posts.post_date DESC LIMIT 18310, 5;
```
Would want to use an index sorted by date for speed, especially one that had all the other fields required to satisfy the query in it as well?
Does MySQL have query hints to force an index to be used for speed/performance tests or is there something else I need to do to see why this index is being ignored.
I would love it if Navicat had a Visual Query Execution Plan like MS SQL but it seems EXPLAIN is the best it has to offer.
Anyone with any hints on how I can either force the index to be used or work out why its being ignored would be very helpful!
Thanks | 2013/07/02 | [
"https://Stackoverflow.com/questions/17435950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037545/"
] | >
> Does MySQL have query hints to force an index to be used for speed/performance tests or is there something else I need to do to see why this index is being ignored.
>
>
>
[The documentation](http://dev.mysql.com/doc/refman/5.0/en/index-hints.html) answers this question in some detail:
>
> By specifying `USE INDEX`*`(index_list)`*, you can tell MySQL to use
> only one of the named indexes to find rows in the table. The
> alternative syntax `IGNORE INDEX`*`(index_list)`* can be used to tell
> MySQL to not use some particular index or indexes. These hints are
> useful if [`EXPLAIN`](http://dev.mysql.com/doc/refman/5.0/en/explain.html) shows that MySQL is using the wrong index
> from the list of possible indexes.
>
>
> You can also use `FORCE INDEX`, which acts like `USE INDEX`*`(index_list)`*
> but with the addition that a table scan is assumed to be *very
> expensive*. In other words, a table scan is used only if there is no
> way to use one of the given indexes to find rows in the table.
>
>
> Each hint requires the names of indexes, not the names of columns. The
> name of a `PRIMARY KEY` is `PRIMARY`. To see the index names for a
> table, use [`SHOW INDEX`](http://dev.mysql.com/doc/refman/5.0/en/show-index.html).
>
>
>
If `USE INDEX` doesn't work, try using `IGNORE INDEX` to see what the optimizer's second choice is (or third, and so on).
A simple example of the syntax would be:
```
SELECT * FROM t1 USE INDEX (i1) IGNORE INDEX (i2) WHERE ...
```
There are many more where that came from, in the linked docs. I've linked to the version 5.0 pages, but you can easily navigate to the appropriate version using the left sidebar; some additional syntax options are available as of version 5.1. | Just to let you know I am on a different PC so my username has changed but I did write the original question.
What I think would be very helpful is a conversion guide to help people from MS SQL backgrounds covert to MySQL as it seems there's some difference in the index tuning I didn't realise especially that different storage engines automatically add in primary keys, plus how to handle the lack of tools to aid performance tuning.
I am used to creating my main clustered index, primary key and other unique constraints and indexes, then non-clustered indexes with included keys, some covering indexes etc.
I will then run a timed job to log the missing index DMV report to a table to prevent the data being lost during any restart. I can then run reports to check for indexes the SQL optimiser thinks "should" be used or those it is "not" using. I can then use this information, counters of mis-hits and potential efficiency percentage if the missing index was used, as a guide to help fine tune the indexing for performance.
As far as I can tell MySQL doesn't have anything similar to the DMV's MsSQL has?
The nice graphical execution plan built into MS SQL Studio from aeons ago helps with tuning a lot and the bog standard MySQL explain is poor in comparison. I will look into that tool you mentioned although running a select @@version returns 5.0.51a-24+lenny5-log so I doubt it will help me.
A couple of things though regarding the posts:
1. The aim was to have a covering index so no bookmark lookups (if you call them that in MySQL) were required and the data could come straight from the index.
2. As nearly all my posts are "published" (99.99%) and the post\_type is nearly all "post" (99.99%) with a tiny percentage of "pages". There is no selectivity in those two columns and they are in the index for the cover. I've turned off auto-drafts to prevent a build up of revisions etc and the number of drafts is very small.
3. Therefore I would have thought having the post\_date as the first key in the index would have been of more help as the LIMIT (as you say is expensive, and I have no control over Wordpress's code) therefore surely the ORDER BY and LIMIT (which is basically a TOP) would have been the most costly and selective part of the query and of more use to the index in comparison with the other keys (which are not selective at all). This is why I put it first.
4. I am using Wordpress and the table is wp\_posts and its storage engine is MyISAM which I believe I cannot change due to the requirement for it to have full text searching.
5. As I said to someone else I already have an index with the order **post\_type, post\_status and post\_date** but EXPLAIN only shows it in the possible keys and then ignores it to use the index based around these columns: **post\_status, password and id**.
6. As password is not used in the query and post\_status is totally unselective (as all my post\_types are "post") I am a loss to why MySQL's ***"clever" optimiser*** thinks this index should be selected above either the ones provided OR my own?
So I am still stuck as no suggestion seems to work.
I've tried changing the ordering several times and even though I only have 20k rows it takes half an hour or more each time! I don't know if this is normal in MySQL or not but in MSSQL it takes minutes to add/drop indexes on tables with millions of rows.
So as nothing has worked so far I want to know (why?) and obviously about query hints to see if that does any good at all.
I have re-started the DB after re-indexing (and even restarted the webserver).
Thanks for your help. |
17,435,950 | I am trying to improve the performance of a hammered wordpress DB by adding indexes to queries that appear in the slow query log.
In MS SQL you can use query hints to force a query to use an index but it is usually quite easy to get a query to use an index if you cover the columns correctly etc.
I have this query that appears in the slow query log a lot
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
WHERE 1=1
AND wp_posts.post_type = 'post'
AND (wp_posts.post_status = 'publish')
ORDER BY wp_posts.post_date DESC
LIMIT 18310, 5;
```
I created a covering unique index on `wp_posts` on `post_date, post_status, post_type and post_id` and restarted MySQL however when I run explain the index used is
```
status_password_id
```
and in the possible keys my new index doesn't even appear although it's a covering index e.g I just get
```
type_status_date,status_password_id
```
Therefore neither the used index or the possible choices the "optimiser" if MySQL has one is even considering my index which has post\_date as the first column. I would have thought a query that is basically doing a TOP and ordering by date with
```
ORDER BY wp_posts.post_date DESC LIMIT 18310, 5;
```
Would want to use an index sorted by date for speed, especially one that had all the other fields required to satisfy the query in it as well?
Does MySQL have query hints to force an index to be used for speed/performance tests or is there something else I need to do to see why this index is being ignored.
I would love it if Navicat had a Visual Query Execution Plan like MS SQL but it seems EXPLAIN is the best it has to offer.
Anyone with any hints on how I can either force the index to be used or work out why its being ignored would be very helpful!
Thanks | 2013/07/02 | [
"https://Stackoverflow.com/questions/17435950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1037545/"
] | MySQL 5.6 has support for a new format of EXPLAIN, which the [MySQL Workbench](http://www.mysql.com/products/workbench/) GUI can visualize in a more appealing way. But that doesn't help you if you're stuck on MySQL 5.5 or earlier.
MySQL does have hints as @AirThomas mentions, but you should really use them sparingly. In a simple query like the one you show, it should never be necessary to use index hints -- if you have the right index. And using index hints means you have hard-coded index names into your application, so if you add or drop indexes, you have to update your code.
In your query, an index on `(post_date, post_status, post_type, post_id)` is not going to help.
You want the left-most column in the index to be used for row restriction. So put `post_status, post_type` first. Best if the more selective column is first. That is, if `post_type = 'post'` matches 3% of the table, and `post_status = 'publish'` matches 1% of the table, then put post\_status first before post\_type.
Since you used `=` for both conditions and the `AND` operator, you know that all matching rows are basically tied with respect to those two columns. So if you use `post_date` as the third column in the index, then the optimizer knows it can fetch the rows in the order they are stored in the index, and it can skip doing any other work for the ORDER BY. You can see this working if "Using filesort" disappears from your EXPLAIN output.
So your index likely should be:
```
ALTER TABLE wp_posts ADD INDEX (post_status, post_type, post_date);
```
You may also enjoy my presentation [How to Design Indexes, Really](http://www.slideshare.net/billkarwin/how-to-design-indexes-really).
You don't need to add ID to the index in this case, because InnoDB indexes automatically contain the primary key column(s).
`LIMIT 18310, 5` is bound to be costly. MySQL has to generate the whole result set on the server side, up to 18315 rows, only to discard most of them. Who in the world needs to skip to the 3662nd page, anyway?!
`SQL_CALC_FOUND_ROWS` is a *major* performance killer when you have large result sets that you're paging through, because MySQL has to generate the *whole* result set, both before and after the page you requested. Best to get rid of that query modifier unless you really need `FOUND_ROWS()`, and even if you do need the number of rows, it can sometimes\* be quicker to run two queries, one with `SELECT COUNT(*)`.
(\* Test both ways to make sure.)
Here are some more tips on optimizing LIMIT:
* <http://www.mysqlperformanceblog.com/2006/09/01/order-by-limit-performance-optimization/>
* <http://www.mysqlperformanceblog.com/2008/09/24/four-ways-to-optimize-paginated-displays/>
* <http://dev.mysql.com/doc/refman/5.6/en/limit-optimization.html> | Just to let you know I am on a different PC so my username has changed but I did write the original question.
What I think would be very helpful is a conversion guide to help people from MS SQL backgrounds covert to MySQL as it seems there's some difference in the index tuning I didn't realise especially that different storage engines automatically add in primary keys, plus how to handle the lack of tools to aid performance tuning.
I am used to creating my main clustered index, primary key and other unique constraints and indexes, then non-clustered indexes with included keys, some covering indexes etc.
I will then run a timed job to log the missing index DMV report to a table to prevent the data being lost during any restart. I can then run reports to check for indexes the SQL optimiser thinks "should" be used or those it is "not" using. I can then use this information, counters of mis-hits and potential efficiency percentage if the missing index was used, as a guide to help fine tune the indexing for performance.
As far as I can tell MySQL doesn't have anything similar to the DMV's MsSQL has?
The nice graphical execution plan built into MS SQL Studio from aeons ago helps with tuning a lot and the bog standard MySQL explain is poor in comparison. I will look into that tool you mentioned although running a select @@version returns 5.0.51a-24+lenny5-log so I doubt it will help me.
A couple of things though regarding the posts:
1. The aim was to have a covering index so no bookmark lookups (if you call them that in MySQL) were required and the data could come straight from the index.
2. As nearly all my posts are "published" (99.99%) and the post\_type is nearly all "post" (99.99%) with a tiny percentage of "pages". There is no selectivity in those two columns and they are in the index for the cover. I've turned off auto-drafts to prevent a build up of revisions etc and the number of drafts is very small.
3. Therefore I would have thought having the post\_date as the first key in the index would have been of more help as the LIMIT (as you say is expensive, and I have no control over Wordpress's code) therefore surely the ORDER BY and LIMIT (which is basically a TOP) would have been the most costly and selective part of the query and of more use to the index in comparison with the other keys (which are not selective at all). This is why I put it first.
4. I am using Wordpress and the table is wp\_posts and its storage engine is MyISAM which I believe I cannot change due to the requirement for it to have full text searching.
5. As I said to someone else I already have an index with the order **post\_type, post\_status and post\_date** but EXPLAIN only shows it in the possible keys and then ignores it to use the index based around these columns: **post\_status, password and id**.
6. As password is not used in the query and post\_status is totally unselective (as all my post\_types are "post") I am a loss to why MySQL's ***"clever" optimiser*** thinks this index should be selected above either the ones provided OR my own?
So I am still stuck as no suggestion seems to work.
I've tried changing the ordering several times and even though I only have 20k rows it takes half an hour or more each time! I don't know if this is normal in MySQL or not but in MSSQL it takes minutes to add/drop indexes on tables with millions of rows.
So as nothing has worked so far I want to know (why?) and obviously about query hints to see if that does any good at all.
I have re-started the DB after re-indexing (and even restarted the webserver).
Thanks for your help. |
51,384,796 | I have a table that have logins in one column and phone numbers in another. I need to copy all phone numbers of each login and paste them to another sheet. But i need only unique phone numbers as one login may contain many records with the same phone number. What i have tried and what failed
```
For Each rCell In Sheets("PotentialFraud").Range("B1:B" & IndexValueLastRow("B:B"))
.Range("A2").AutoFilter _
field:=12, _
Criteria1:=rCell.Value2
LastRow = .Cells(1, 1).SpecialCells(xlCellTypeVisible).End(xlDown).Row
.Range("P1:P" & LastRow).Offset(1, 0).SpecialCells(xlCellTypeVisible).Copy
Worksheets("PotentialFraud").Range(rCell.Offset(0, 2).Address).PasteSpecial Transpose:=True
Next rCell
```
This Method does not give me an option to copy only unique values.
Another option I found was to use Advanced Filter
```
.Range("P2:P" & LastRow).Offset(1, 0).SpecialCells(xlCellTypeVisible).AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=Worksheets("PotentialFraud").Range("A:A"), _
Unique:=True
```
However, this lead to error 1004 saying either **This command requires at least two rows of source data...** even though there are 2500 rows visible. Either **Application-defined or object-defined error** if i change the range to
```
.Range("P:P" & LastRow).Offset(1, 0).SpecialCells(xlCellTypeVisible).AdvancedFilter _
Action:=xlFilterCopy, _
CopyToRange:=Worksheets("PotentialFraud").Range("A:A"), _
Unique:=True
```
*("P2:P") to ("P:P")* | 2018/07/17 | [
"https://Stackoverflow.com/questions/51384796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5874458/"
] | you can add this
```
onFocus={useTheOnFocus ? onFocusHandler : undefined}
```
or set a handler
```
onFocus={onFocusHandler}
```
and check a condition in a handler
```
onFocusHandler = (ev) => {
if(!condition) {
return null;
}
// your code
}
``` | You can give event handlers a value of `undefined` if you don't want them to be active.
**Example**
```js
class App extends React.Component {
state = { useTheOnFocus: false };
componentDidMount() {
setInterval(() => {
this.setState(prevState => ({
useTheOnFocus: !prevState.useTheOnFocus
}));
}, 2000);
}
onFocusHandler = evt => {
evt.preventDefault();
console.log("Focus handler active");
};
render() {
const { useTheOnFocus } = this.state;
return (
<input
type="text"
className="some-class"
onFocus={useTheOnFocus ? this.onFocusHandler : undefined}
/>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
``` |
24,440,216 | I have line like this
and I am searching for how the input works when the code is executed
```
scanf("%d, %f",&withdrawal ,&balance );
```
I use Cygwin to compile the code and afterwards I am asked for inputs.
Does it mean that I have to write two numbers separated by space
```
60 120
```
or there is some trick to do that ?
It could be an easy question, but I just would like to understand how it works when it is asked for more then one input value.
Thanks | 2014/06/26 | [
"https://Stackoverflow.com/questions/24440216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3460161/"
] | scanf(), or scan formatted, expects input in the format you specified. scanf("%d, %f") simply means you expect input in this exact format, for example: 62, 2.15 . | scanf expects an input as specified in quotes, as Matt Phillips mentioned.
so, whether change a scanf to:
`scanf("%d %f", &withdrawal, &balance);` and then input `60 120` or just input `60, 120` |
24,440,216 | I have line like this
and I am searching for how the input works when the code is executed
```
scanf("%d, %f",&withdrawal ,&balance );
```
I use Cygwin to compile the code and afterwards I am asked for inputs.
Does it mean that I have to write two numbers separated by space
```
60 120
```
or there is some trick to do that ?
It could be an easy question, but I just would like to understand how it works when it is asked for more then one input value.
Thanks | 2014/06/26 | [
"https://Stackoverflow.com/questions/24440216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3460161/"
] | scanf(), or scan formatted, expects input in the format you specified. scanf("%d, %f") simply means you expect input in this exact format, for example: 62, 2.15 . | On encountering non-white-space character (`,` in your case) in a format string (`"%d, %f"`), `scanf` compares it with the next input character.
>
> * If the two characters match, `scanf` discards the input character and continues processing the format string.
> * If the character doesn't match, `scanf` puts the offending character back into the input buffer and aborts without further processing the format string.
>
>
>
Therefore you need to input `60, 120.0` so that `scanf` read the input successfully. |
42,461,533 | i'm developing a java program that shows area and perimeter of two rectangle with fixed width&length, current date and reads input from user to solve a linear equation. I was able to ask a user if they want to re-run the program or not. the problem is that if they input y or Y, the program runs, but if the user enters anything els the program quits. I'd like to check this input and see if:
1- it's a y or Y, re-run
2- it's n or N, quit
3- neither 1 nor 2, ask the user again if he/she wants to re-run the program of not.
Here's my code:
```
public static void main(String[] args) {
char ch = 'y';
GregorianCalendar calendar = new GregorianCalendar();
LinearEquation le = new LinearEquation(1.0,1.0,1.0,1.0,1.0,1.0);
Rectangle rec1 = new Rectangle(4.0,40.0);
Rectangle rec2 = new Rectangle(3.5,35.9);
Scanner input = new Scanner(System.in);
Double a, b, c, d, e,f;
do{
System.out.println("First rectangle info is: ");
System.out.print(" width is: "+ rec1.getWidth() +
"\n height is: " + rec1.getHeight()+
"\n Area is: "+ rec1.getArea() +
"\n Perimeter is: " + rec1.getPerimeter());
System.out.println();
System.out.println();
System.out.println("Second rectangle info is: ");
System.out.print(" width is: "+ rec2.getWidth() +
"\n height is: " + rec2.getHeight()+
"\n Area is: "+ rec2.getArea() +
"\n Perimeter is: " + rec2.getPerimeter());
System.out.println();
System.out.println("Current date is: " + calendar.get(GregorianCalendar.DAY_OF_MONTH) +
"-" + (calendar.get(GregorianCalendar.MONTH) + 1)+
"-" + calendar.get(GregorianCalendar.YEAR));
System.out.println("Date after applying 1234567898765L to setTimeInMillis(long) is: ");
calendar.setTimeInMillis(1234567898765L);
System.out.println(calendar.get(GregorianCalendar.DAY_OF_MONTH) +
"-" + (calendar.get(GregorianCalendar.MONTH) + 1)+
"-" + calendar.get(GregorianCalendar.YEAR));
System.out.println();
System.out.println("Please, enter a, b, c, d, e and f to solve the equation:");
try{
System.out.println("a: ");
a = input.nextDouble();
System.out.println("b: ");
b = input.nextDouble();
System.out.println("c: ");
c = input.nextDouble();
System.out.println("d: ");
d = input.nextDouble();
System.out.println("e: ");
e = input.nextDouble();
System.out.println("f: ");
f = input.nextDouble();
le.setA(a);
le.setB(b);
le.setC(c);
le.setD(d);
le.setE(e);
le.setF(f);
if(le.isSolvable()){
System.out.println("x is: "+ le.getX() + "\ny is: "+ le.getY());
}else {
System.out.println("The equation has no solution.");
}
//System.out.println("Would you like to re-run the program( y or n)");
//ch = input.next().charAt(0);
}
catch (Exception ee) {
System.out.println("Invalid input");
//System.out.println("Would you like to re-run the program( y or n)");
ch = input.next().charAt(0);
}
System.out.println("Would you like to re-run the program( y or any other input to quit)");
ch = input.next().charAt(0);
}while(ch == 'y' || ch == 'Y');
}
``` | 2017/02/25 | [
"https://Stackoverflow.com/questions/42461533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2066392/"
] | You can add a `do while` when you asks the user whether if he wants to repeat the program.
Besides, instead of specifying both uppercase and lowercase in statement : `while(ch == 'y' || ch == 'Y');` you can use `Character.toLowerCase()` method to reduce the number of tests to perform.
```
do {
System.out.println("Would you like to re-run the program( y or any other input to quit)");
ch = input.next().charAt(0);
ch = Character.toLowerCase(ch);
} while (ch != 'y' && ch != 'n');
```
Now your code could look like that :
```
do {
....
do {
System.out.println("Would you like to re-run the program( y or any other input to quit)");
ch = input.next().charAt(0);
ch = Character.toLowerCase(ch);
} while (ch != 'y' && ch != 'n');
} while (ch == 'y');
``` | At the end of your loop (but still IN your loop), you could do something like
```
ch = 'x'; // Just a dummy value
while (ch != 'y' && ch != 'n') {
System.out.prinln("Enter y or n:");
ch = input.next().charAt(0);
}
if (ch == 'n') {
break;
}
``` |
34,778,041 | I want to know what `[=]` does? Here's a short example
```
template <typename T>
std::function<T (T)> makeConverter(T factor, T offset) {
return [=] (T input) -> T { return (offset + input) * factor; };
}
auto milesToKm = makeConverter(1.60936, 0.0);
```
How would the code work with `[]` instead of `[=]`?
I assume that
```
std::function<T (T)>
```
means an function prototype which gets `(T)` as argument and return type `T`? | 2016/01/13 | [
"https://Stackoverflow.com/questions/34778041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4503737/"
] | The `[=]` you're referring to is part of the *capture list* for the lambda expression. This tells C++ that the code inside the lambda expression is initialized so that the lambda gets a copy of all the local variables it uses when it's created. This is necessary for the lambda expression to be able to refer to `factor` and `offset`, which are local variables inside the function.
If you replace the `[=]` with `[]`, you'll get a compiler error because the code inside the lambda expression won't know what the variables `offset` and `factor` refer to. Many compilers give good diagnostic error messages if you do this, so try it and see what happens! | It's a [lambda](http://en.cppreference.com/w/cpp/language/lambda) capture list. Makes variables available for the lambda. You can use `[=]` which copies by value, or `[&]` which passes by reference. |
51,206,456 | I have restructured my project folders. I see that i lost commit history before restructuring of files in my remote repository.
I have the history before restructuring locally.
Right now everyone who clone the repository doesn't have the commit history before restructuring.
Is there anyway i can rebuild the commit history and merge it to the remote repository?
When i try this command :
```
git log --follow pom.xml
```
I can see full history of file, but when i dont use --follow the log stops at restructuring commit.I would like that it shows all the history. Is there any way to fix this? | 2018/07/06 | [
"https://Stackoverflow.com/questions/51206456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1057347/"
] | The only way to lose history in Git is to remove commits. This is because the commits *are* the history. There is no file history; there are only commits.
When you use `git log --follow pom.xml`, you are telling Git to *synthesize* a file history, by wandering through the commit history and noting when a file named `pom.xml` is touched. The `--follow` option tells Git that in addition to checking to see if `pom.xml` is *changed* in that commit, it should also check to see if it is *renamed* in that commit. If so, Git checks *earlier* commits for the *old name* (including its full directory path) instead of the new name—so Git is no longer looking for `new/pom.xml` but now looking for `old/pom.xml` or whatever, and constructing a file history for *that* file.
If you use an IDE, the IDE must do the same thing as Git—synthesize a file history by selecting commits that change that file, and check for rename operations in the process, if that's what you want it to do. | Finally i found out thats an issue only on Bitbucket and Eclipse.
Bitbucket shows all commits to the repository but can not show the sinbgle file log with the command --follow.
The same issue is with Eclipse.
Intellij works fine. |
7,515,167 | What I want is when checkbox1 is selected both checkbox labelled 1 will get selected and background will be removed
[here is the fiddle](http://jsfiddle.net/rigids/D2vCf/)
for eg if i select checkbox1 it should select both checkbox labelled checkbox1 | 2011/09/22 | [
"https://Stackoverflow.com/questions/7515167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/791441/"
] | The problem is that searching for ID $("#somethin") is not possible to select more than one element. IF you search for class, then your example works.. well, with [some minor changes](http://jsfiddle.net/D2vCf/11/) :)
```
$(document).ready(function() {
$('input[type=checkbox]').change(function(){
var pos;
pos = this.id;
// global hook - unblock UI when ajax request completes
$(document).ajaxStop($.unblockUI);
if($(this).prop("checked")) {
$("."+pos).parent().removeClass("highlight");
$("."+pos).prop('checked', true)
//ajax to add uni
} else {
//ajax to remove uni
$("."+pos).parent().addClass("highlight");
$("."+pos).prop('checked', false)
}
});
});
``` | You can't have multiple DOM elements with the same id.
See [this fiddle](http://jsfiddle.net/PL6MW/1/) for a working example, but it's not as generic as you may need. |
7,515,167 | What I want is when checkbox1 is selected both checkbox labelled 1 will get selected and background will be removed
[here is the fiddle](http://jsfiddle.net/rigids/D2vCf/)
for eg if i select checkbox1 it should select both checkbox labelled checkbox1 | 2011/09/22 | [
"https://Stackoverflow.com/questions/7515167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/791441/"
] | The problem is that searching for ID $("#somethin") is not possible to select more than one element. IF you search for class, then your example works.. well, with [some minor changes](http://jsfiddle.net/D2vCf/11/) :)
```
$(document).ready(function() {
$('input[type=checkbox]').change(function(){
var pos;
pos = this.id;
// global hook - unblock UI when ajax request completes
$(document).ajaxStop($.unblockUI);
if($(this).prop("checked")) {
$("."+pos).parent().removeClass("highlight");
$("."+pos).prop('checked', true)
//ajax to add uni
} else {
//ajax to remove uni
$("."+pos).parent().addClass("highlight");
$("."+pos).prop('checked', false)
}
});
});
``` | Select multiple elements using class. You can try this..
```
<script language="javascript" type="text/javascript">
$(function () {
$("#checkbox1").click(function () {
$('.case').attr('checked', this.checked);
});
});
</script>
```
and your html code will be like below
```
<div>
<table>
<tr>
<td><input type="checkbox" id="checkbox1" class="highlight"/></td>
<td>Item1</td>
<td>value</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
<td>Item2</td>
<td>value</td>
</tr>
</table>
</div>
``` |
4,195,726 | I want to create a custom TableViewCell on which I want to have UITextField with editing possibility.
So I created new class with xib. Add TableViewCell element. Drag on it UITextField. Added outlets in my class and connect them all together. In my TableView method cellForRowAtIndexPath I create my custom cells, BUT they are not my custom cells - they are just usual cells. How can I fix this problem, and why it is? thanx!
//EditCell. h
```
#import <UIKit/UIKit.h>
@interface EditCell : UITableViewCell
{
IBOutlet UITextField *editRow;
}
@property (nonatomic, retain) IBOutlet UITextField *editRow;
@end
```
//EditCell.m
```
#import "EditCell.h"
@implementation EditCell
@synthesize editRow;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidUnload
{
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
self.editRow = nil;
}
@end
```
//in my code
```
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"EditCell";
EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[EditCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}
cell.editRow.text = @"some text to test";
return cell;
}
``` | 2010/11/16 | [
"https://Stackoverflow.com/questions/4195726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/449007/"
] | Do not use UITableViewCell's initializer, but make the cell load from your nib:
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"EditCell";
EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"YourNibNameHere" owner:self options:nil];
cell = (EditCell *)[nib objectAtIndex:0];
}
cell.editRow.text = @"some text to test";
return cell;
}
```
Of course, you need to specify the correct nib name. | You need to load your xib and retrieve your custom cell:
```
NSArray *uiObjects = [[NSBundle mainBundle] loadNibNamed:@"yourNib"
owner:self
options:nil];
for (id uiObject in uiObjects) {
if ([uiObject isKindOfClass:[EditCell class]]) {
cell = (EditCell *) uiObject;
}
}
```
Make also sure you actually changed the tableViewCell class in your xib to EditCell.
You also need to change the tableView row heigh to the right size.
One other way is to just build your cell programmatically in your EditCell class, which I believe let's you be much more free and precise than within InterfaceBuilder:
In EditCell.m:
```
- (id)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
CGRect textFieldRect = CGRectMake(5, 5, 300, 30);
UITextField *textField = [[UITextField alloc] initWithFrame:textFieldRect];
textField.tag = kTextFieldTag;
[self.contentView addSubview:textField];
[textField release];
}
return self;
}
```
Then in your tableViewController you create the cell the way you did and retrieve your textField with the tag. |
4,195,726 | I want to create a custom TableViewCell on which I want to have UITextField with editing possibility.
So I created new class with xib. Add TableViewCell element. Drag on it UITextField. Added outlets in my class and connect them all together. In my TableView method cellForRowAtIndexPath I create my custom cells, BUT they are not my custom cells - they are just usual cells. How can I fix this problem, and why it is? thanx!
//EditCell. h
```
#import <UIKit/UIKit.h>
@interface EditCell : UITableViewCell
{
IBOutlet UITextField *editRow;
}
@property (nonatomic, retain) IBOutlet UITextField *editRow;
@end
```
//EditCell.m
```
#import "EditCell.h"
@implementation EditCell
@synthesize editRow;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidUnload
{
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
self.editRow = nil;
}
@end
```
//in my code
```
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"EditCell";
EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[EditCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}
cell.editRow.text = @"some text to test";
return cell;
}
``` | 2010/11/16 | [
"https://Stackoverflow.com/questions/4195726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/449007/"
] | Do not use UITableViewCell's initializer, but make the cell load from your nib:
```
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"EditCell";
EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"YourNibNameHere" owner:self options:nil];
cell = (EditCell *)[nib objectAtIndex:0];
}
cell.editRow.text = @"some text to test";
return cell;
}
```
Of course, you need to specify the correct nib name. | You can load custom UITableViewCells from NIB files without creating a subclass of UITableViewCell first, but with a subclass you can configure more about the cell.
**First solution, without subclass:**
**In ViewController:**
• Define cell ivar as IBOutlet
```
UITableViewCell *tableViewCell;
@property (nonatomic, assign) IBOutlet UITableViewCell *tableViewCell;
@synthesize ...
```
**In IB:**
• Create new empty NIB file and open in Interface Builder
• Drag table view cell from library to the document window and open it with double click
• Customise the cell, don't forget to tag added views
• Select cell and add an identifier (for later use in tableView:cellForRowAtIndexPath:)
• Set File's Owner to the controller class that will be loading this cell
• Connect file's owner's cell outlet with cell in NIB
**In ViewController:**
• In tableView:cellForRowAtIndexPath:
```
static NSString * cellIdentifier = @"SameIdentifierAsInNIB";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"NibFileNameWithoutSuffix" owner:self options:nil];
cell = tableViewCell;
// Configure the cell
self.tableViewCell = nil;
}
// Configure the cell
```
all set
/\* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \*/
**Second solution, with subclass:**
**In Code editor:**
`1.` Create new subclass of UITableViewCell
`2.` Add initWithCoder method, add customisations
>
>
> ```
> - (id)initWithCoder:(NSCoder *)aDecoder {
> self = [super initWithCoder:aDecoder];
> if (self) {
> // init magic here
> self.contentView.backgroundColor = [UIColor lightGrayColor];
> }
> return self;
> }
>
> ```
>
>
`3.` Add method for setting up values (like "setupCellWith:")
>
>
> ```
> - (id)setupCellWith:(NSDictionary *)someSetupDict {
>
> // more magic here
> }
>
> ```
>
>
--> Outlets will be added later from IB
**In IB:**
`4.` Create new empty XIB file
`5.` Change file's owner = UIViewController
`6.` Drag TableView cell from Library
`7.` Change its class to custom subclass (see 1.)
`8.` Set the cell's identifier property // careful here, same as in cellForRowAtIndexPath:
`9.` Connect view outlet of file's owner to TableView cell
`10.` Add interface elements set them up properly (set class, …)
`11.` Create the outlets needed via Ctrl-Drag to CustomSubclass.h
--> weak or strong? --> weak, strong only top level objects without predefined outlets (i.e. like "view")
**In Code editor:**
`12.` Customize "tableView:cellForRowAtIndexPath:"
>
>
> ```
> - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
> {
> static NSString *cellIdentifier = @"CustomIdentifier";
>
> CustomCellSubclass *cell = (CustomCellSubclass *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
>
> if (cell == nil) {
> //cell = [[CustomCellSubclass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
> UIViewController *tempController = [[UIViewController alloc] initWithNibName:@"CustomCellSubclassXIBName" bundle:nil];
> cell = (CustomCellSubclass *)tempController.view;
> //[tempController release]; // not needed with ARC
> }
> // Configure the cell...
> [cell setupCellWith:…];
>
> // do other setup magic here
>
> return cell;
> }
>
> ```
>
> |
4,195,726 | I want to create a custom TableViewCell on which I want to have UITextField with editing possibility.
So I created new class with xib. Add TableViewCell element. Drag on it UITextField. Added outlets in my class and connect them all together. In my TableView method cellForRowAtIndexPath I create my custom cells, BUT they are not my custom cells - they are just usual cells. How can I fix this problem, and why it is? thanx!
//EditCell. h
```
#import <UIKit/UIKit.h>
@interface EditCell : UITableViewCell
{
IBOutlet UITextField *editRow;
}
@property (nonatomic, retain) IBOutlet UITextField *editRow;
@end
```
//EditCell.m
```
#import "EditCell.h"
@implementation EditCell
@synthesize editRow;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidUnload
{
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
self.editRow = nil;
}
@end
```
//in my code
```
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"EditCell";
EditCell *cell = (EditCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[EditCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}
cell.editRow.text = @"some text to test";
return cell;
}
``` | 2010/11/16 | [
"https://Stackoverflow.com/questions/4195726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/449007/"
] | You can load custom UITableViewCells from NIB files without creating a subclass of UITableViewCell first, but with a subclass you can configure more about the cell.
**First solution, without subclass:**
**In ViewController:**
• Define cell ivar as IBOutlet
```
UITableViewCell *tableViewCell;
@property (nonatomic, assign) IBOutlet UITableViewCell *tableViewCell;
@synthesize ...
```
**In IB:**
• Create new empty NIB file and open in Interface Builder
• Drag table view cell from library to the document window and open it with double click
• Customise the cell, don't forget to tag added views
• Select cell and add an identifier (for later use in tableView:cellForRowAtIndexPath:)
• Set File's Owner to the controller class that will be loading this cell
• Connect file's owner's cell outlet with cell in NIB
**In ViewController:**
• In tableView:cellForRowAtIndexPath:
```
static NSString * cellIdentifier = @"SameIdentifierAsInNIB";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:@"NibFileNameWithoutSuffix" owner:self options:nil];
cell = tableViewCell;
// Configure the cell
self.tableViewCell = nil;
}
// Configure the cell
```
all set
/\* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \* \*/
**Second solution, with subclass:**
**In Code editor:**
`1.` Create new subclass of UITableViewCell
`2.` Add initWithCoder method, add customisations
>
>
> ```
> - (id)initWithCoder:(NSCoder *)aDecoder {
> self = [super initWithCoder:aDecoder];
> if (self) {
> // init magic here
> self.contentView.backgroundColor = [UIColor lightGrayColor];
> }
> return self;
> }
>
> ```
>
>
`3.` Add method for setting up values (like "setupCellWith:")
>
>
> ```
> - (id)setupCellWith:(NSDictionary *)someSetupDict {
>
> // more magic here
> }
>
> ```
>
>
--> Outlets will be added later from IB
**In IB:**
`4.` Create new empty XIB file
`5.` Change file's owner = UIViewController
`6.` Drag TableView cell from Library
`7.` Change its class to custom subclass (see 1.)
`8.` Set the cell's identifier property // careful here, same as in cellForRowAtIndexPath:
`9.` Connect view outlet of file's owner to TableView cell
`10.` Add interface elements set them up properly (set class, …)
`11.` Create the outlets needed via Ctrl-Drag to CustomSubclass.h
--> weak or strong? --> weak, strong only top level objects without predefined outlets (i.e. like "view")
**In Code editor:**
`12.` Customize "tableView:cellForRowAtIndexPath:"
>
>
> ```
> - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
> {
> static NSString *cellIdentifier = @"CustomIdentifier";
>
> CustomCellSubclass *cell = (CustomCellSubclass *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
>
> if (cell == nil) {
> //cell = [[CustomCellSubclass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
> UIViewController *tempController = [[UIViewController alloc] initWithNibName:@"CustomCellSubclassXIBName" bundle:nil];
> cell = (CustomCellSubclass *)tempController.view;
> //[tempController release]; // not needed with ARC
> }
> // Configure the cell...
> [cell setupCellWith:…];
>
> // do other setup magic here
>
> return cell;
> }
>
> ```
>
> | You need to load your xib and retrieve your custom cell:
```
NSArray *uiObjects = [[NSBundle mainBundle] loadNibNamed:@"yourNib"
owner:self
options:nil];
for (id uiObject in uiObjects) {
if ([uiObject isKindOfClass:[EditCell class]]) {
cell = (EditCell *) uiObject;
}
}
```
Make also sure you actually changed the tableViewCell class in your xib to EditCell.
You also need to change the tableView row heigh to the right size.
One other way is to just build your cell programmatically in your EditCell class, which I believe let's you be much more free and precise than within InterfaceBuilder:
In EditCell.m:
```
- (id)initWithStyle:(UITableViewCellStyle)style
reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
CGRect textFieldRect = CGRectMake(5, 5, 300, 30);
UITextField *textField = [[UITextField alloc] initWithFrame:textFieldRect];
textField.tag = kTextFieldTag;
[self.contentView addSubview:textField];
[textField release];
}
return self;
}
```
Then in your tableViewController you create the cell the way you did and retrieve your textField with the tag. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.