qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
68,967,488
Check if there are any orders before a given date (`Date` column). The procedure has a passing parameter "date" as date and another passing parameter "count". This parameter returns the number of orders before this date. The simple way of doing it would be: ``` SELECT COUNT([Sales].[dbo].[Order].[Date]) FROM [Sales].[dbo].[Order] WHERE [Sales].[dbo].[Order].[Date] >= '2019-03-11' ``` But unfortunately I have to use the procedure and the cursor. My attempt is this: ``` CREATE OR ALTER PROCEDURE OrderBeforeDate (@date date, @count int OUT) AS BEGIN SET @count = 0; DECLARE cursor1 SCROLL CURSOR FOR SELECT [Sales].[dbo].[Order].[Date] FROM [Sales].[dbo].[Order] FOR READ ONLY OPEN cursor1; FETCH NEXT FROM cursor1 INTO @date WHILE @@FETCH_STATUS = 0 BEGIN IF @date <= '2019-03-11' SET @count = @count + 1; END CLOSE cursor1; DEALLOCATE cursor1; END DECLARE @count int EXEC OrderBeforeDate @count OUT PRINT 'Number of Orders after 2019-03-11'': ' + CAST(@count AS VARCHAR(10)) ``` But I get the following error message: > > Operand type collision: int is incompatible with date > > > I don't know what to do. Please give me a helping hand.
2021/08/28
[ "https://Stackoverflow.com/questions/68967488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16769977/" ]
Thanks for all your input! I think it works now with the code like this: ``` CREATE OR ALTER PROC OrderBeforeDate(@date date, @count int out) AS BEGIN SET @count = 0; DECLARE cursor1 scroll cursor for SELECT [Sales].[dbo].[Order].[Date] FROM [Sales].[dbo].[Order] FOR READ ONLY OPEN cursor1; FETCH NEXT FROM cursor1 INTO @date WHILE @@FETCH_STATUS = 0 BEGIN IF @date < '2019-03-11' SET @count = @count + 1; FETCH NEXT FROM cursor1 INTO @date END CLOSE cursor1; DEALLOCATE cursor1; END DECLARE @count int DECLARE @date date EXEC OrderBeforeDate @date, @count OUT PRINT 'Number of Orders before 2019-03-11: ' + CAST(@count AS VARCHAR(10)) ``` You're right that this method is way slower than the one I mentioned in the first place. (1 minute versus less than a second) Thanks everyone for your help!
Probably you miss giving the value for date parameter when call OrderBeforeDate procedure. You only pass in 1 argument and SQL server may regard @count value as the value for date paramter. ``` EXEC OrderBeforeDate @count OUT ```
68,967,488
Check if there are any orders before a given date (`Date` column). The procedure has a passing parameter "date" as date and another passing parameter "count". This parameter returns the number of orders before this date. The simple way of doing it would be: ``` SELECT COUNT([Sales].[dbo].[Order].[Date]) FROM [Sales].[dbo].[Order] WHERE [Sales].[dbo].[Order].[Date] >= '2019-03-11' ``` But unfortunately I have to use the procedure and the cursor. My attempt is this: ``` CREATE OR ALTER PROCEDURE OrderBeforeDate (@date date, @count int OUT) AS BEGIN SET @count = 0; DECLARE cursor1 SCROLL CURSOR FOR SELECT [Sales].[dbo].[Order].[Date] FROM [Sales].[dbo].[Order] FOR READ ONLY OPEN cursor1; FETCH NEXT FROM cursor1 INTO @date WHILE @@FETCH_STATUS = 0 BEGIN IF @date <= '2019-03-11' SET @count = @count + 1; END CLOSE cursor1; DEALLOCATE cursor1; END DECLARE @count int EXEC OrderBeforeDate @count OUT PRINT 'Number of Orders after 2019-03-11'': ' + CAST(@count AS VARCHAR(10)) ``` But I get the following error message: > > Operand type collision: int is incompatible with date > > > I don't know what to do. Please give me a helping hand.
2021/08/28
[ "https://Stackoverflow.com/questions/68967488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16769977/" ]
You are not passing the expected parameters. In your mock-up I would expect to see ``` DECLARE @count int=0, @Date date='20190311' EXEC OrderBeforeDate @Date, @count OUT PRINT 'Number of Orders after 2019-03-11: ' + CAST(@count AS VARCHAR(10)) ``` I would also point out (as you presumably already know) this cursor serves no purpose other than to put the brakes on SQL Server performance. Also your procedure is counting rows *before* your date value, your `print` statement states the opposite.
Yor stored procedure expects 2 parameters while you pro ide only one. Date parameter is missing. Your cursor has infinite loop and yoyr procedure will never end Using a cursor for this is a verry bad idea, put your count in the sored procedure
68,967,488
Check if there are any orders before a given date (`Date` column). The procedure has a passing parameter "date" as date and another passing parameter "count". This parameter returns the number of orders before this date. The simple way of doing it would be: ``` SELECT COUNT([Sales].[dbo].[Order].[Date]) FROM [Sales].[dbo].[Order] WHERE [Sales].[dbo].[Order].[Date] >= '2019-03-11' ``` But unfortunately I have to use the procedure and the cursor. My attempt is this: ``` CREATE OR ALTER PROCEDURE OrderBeforeDate (@date date, @count int OUT) AS BEGIN SET @count = 0; DECLARE cursor1 SCROLL CURSOR FOR SELECT [Sales].[dbo].[Order].[Date] FROM [Sales].[dbo].[Order] FOR READ ONLY OPEN cursor1; FETCH NEXT FROM cursor1 INTO @date WHILE @@FETCH_STATUS = 0 BEGIN IF @date <= '2019-03-11' SET @count = @count + 1; END CLOSE cursor1; DEALLOCATE cursor1; END DECLARE @count int EXEC OrderBeforeDate @count OUT PRINT 'Number of Orders after 2019-03-11'': ' + CAST(@count AS VARCHAR(10)) ``` But I get the following error message: > > Operand type collision: int is incompatible with date > > > I don't know what to do. Please give me a helping hand.
2021/08/28
[ "https://Stackoverflow.com/questions/68967488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16769977/" ]
Thanks for all your input! I think it works now with the code like this: ``` CREATE OR ALTER PROC OrderBeforeDate(@date date, @count int out) AS BEGIN SET @count = 0; DECLARE cursor1 scroll cursor for SELECT [Sales].[dbo].[Order].[Date] FROM [Sales].[dbo].[Order] FOR READ ONLY OPEN cursor1; FETCH NEXT FROM cursor1 INTO @date WHILE @@FETCH_STATUS = 0 BEGIN IF @date < '2019-03-11' SET @count = @count + 1; FETCH NEXT FROM cursor1 INTO @date END CLOSE cursor1; DEALLOCATE cursor1; END DECLARE @count int DECLARE @date date EXEC OrderBeforeDate @date, @count OUT PRINT 'Number of Orders before 2019-03-11: ' + CAST(@count AS VARCHAR(10)) ``` You're right that this method is way slower than the one I mentioned in the first place. (1 minute versus less than a second) Thanks everyone for your help!
Yor stored procedure expects 2 parameters while you pro ide only one. Date parameter is missing. Your cursor has infinite loop and yoyr procedure will never end Using a cursor for this is a verry bad idea, put your count in the sored procedure
152,448
I saw in a [recent answer](https://rpg.stackexchange.com/a/152447/15689) a reference to 1/3 casters and 1/2 casters, and have never encountered this terminology before: > > Paladin's are known as 1/2 casters, so their spell progression isn't as big as full casters. > > > What does it mean to be a 1/3 caster vs a 1/2 caster vs a full caster? How does one distinguish between the three, and which classes correspond to which types of caster?
2019/07/25
[ "https://rpg.stackexchange.com/questions/152448", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/15689/" ]
It refers to the speed at which classes gain spell slots and new levels of spells during their progression. Full casters (like a Wizard) gain spell slots fastest, while 1/3rd casters only gain slots and new spell levels at about a third that rate. The name "1/2 caster" and "1/3 caster" comes from the Multiclassing rules, which state that if you have levels in multiple classes capable of casting spells, you use a specific table to determine your spell slots. You only get to add half and a third of the levels in those classes (rounded down) to determine your total spell slots. You can read more about this in the PHB on page 164, under the header "Spellcasting". Note that these terms only refer to classes that have the **Spellcasting** class feature. Classes that cast spells through a different system (like a Warlock or 4 Elements Monk) don't have a caster progression and don't stack with levels in other classes when multiclassing. For a list of classes: ### Full casters * Bard * Cleric * Druid * Sorceror * Wizard ### Half casters * Paladin * Ranger ### Third casters * Eldritch Knight Fighters * Arcane Trickster Rogues
The fractions here come from the multiclassing rules: when figuring out what level of “multiclassed spellcaster” you are, in order to figure out your spell slots, you need to add your full level in some classes (like wizard), half your level in other classes (like paladin), and a third of your level in yet other classes (like arcane trickster). These fractions roughly correspond to how much spellcasting those classes actually give: wizards and other “1” classes get 9th-level spells, paladins and other “½” classes get 5th-level spells, and arcane tricksters and other “⅓” classes get 4th-level spells.
152,448
I saw in a [recent answer](https://rpg.stackexchange.com/a/152447/15689) a reference to 1/3 casters and 1/2 casters, and have never encountered this terminology before: > > Paladin's are known as 1/2 casters, so their spell progression isn't as big as full casters. > > > What does it mean to be a 1/3 caster vs a 1/2 caster vs a full caster? How does one distinguish between the three, and which classes correspond to which types of caster?
2019/07/25
[ "https://rpg.stackexchange.com/questions/152448", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/15689/" ]
"1/X Caster" is shorthand for how quickly a character gains "spellcaster levels" (and with them, more spell slots) ================================================================================================================== The progression for each of these spellcaster types looks like this, with the first column representing Character Level as a Single-classed X and the other columns representing the "Spellcaster Level" they have as that Single-classed X at a given level. | **Character Level** | **Full** | **Half** | **Third** | | --- | --- | --- | --- | | 1 | 1 | - | - | | 2 | 2 | 1 | - | | 3 | 3 | 2 | 1 | | 4 | 4 | 2 | 2 | | 5 | 5 | 3 | 2 | | 6 | 6 | 3 | 2 | | 7 | 7 | 4 | 3 | | 8 | 8 | 4 | 3 | | 9 | 9 | 5 | 3 | | 10 | 10 | 5 | 4 | | 11 | 11 | 6 | 4 | | 12 | 12 | 6 | 4 | | 13 | 13 | 7 | 5 | | 14 | 14 | 7 | 5 | | 15 | 15 | 8 | 5 | | 16 | 16 | 8 | 6 | | 17 | 17 | 9 | 6 | | 18 | 18 | 9 | 6 | | 19 | 19 | 10 | 7 | | 20 | 20 | 10 | 7 | The classes that fall into these categories are: | **Full** | **Half** | **Third** | **Other** | | --- | --- | --- | --- | | Bard | Artificer\* | Arcane Trickster | Warlock† | | Cleric | Paladin | Artificer (Unearthed Arcana) | | | Druid | Ranger | Eldritch Knight | | | Sorcerer | | | | | Wizard | | | | \*The Artificer is a Half-Spellcaster, but unlike other Half Spellcasters, they gain their spellcasting feature at level 1, instead of level 2, and are treated like level 1 spellcasters at that level. †Warlocks are unique in that their spell access *resembles* that of a Full Spellcaster, but their Spell Slots are completely divorced from the system that all other spellcasters use, so they need their own category. Your spellcaster level determines how many spell slots you have, and the maximum level of spell slot that you'll have will (usually) be half your spellcasting level, rounded up. So if you're a level 9 Paladin (Half Spellcaster), you have a Spellcaster level of 5 (See the Character Level 9 row for a Half Spellcaster). Therefore, you have spell slots equivalent to a level 5 Cleric (Full Spellcaster) and to a level 13 (or 14 or 15) Eldritch Knight (Third Spellcaster)—and for each of these characters, their Spell Slot total is: * 4 1st Level Slots, * 3 2nd Level Slots, * 2 3rd Level Slots. "1/X Caster" also comes into play in the Multiclassing Rules ============================================================ What kind of Spellcaster you are affects how your levels are added together when you Multiclass into multiple kinds of spellcaster. > > **Spell Slots.** You determine your available spell slots by adding together all your levels in the bard, cleric, druid, sorcerer, and wizard classes, half your levels (rounded down) in the paladin and ranger classes, and a third of your fighter or rogue levels (rounded down) if you have the Eldritch Knight or the Arcane Trickster feature.† Use this total to determine your spell slots by consulting the Multiclass Spellcaster table. > > > —**Multiclassing**, Player's Handbook, pg. 164 > > > †Artificers have a special rule: when adding their levels for multiclassing purposes, you round up after dividing by two, instead of rounding down. Note also that Warlocks are not included in this list; again, their Spellcasting is completely different from other classes, so they aren't considered in calculating a character's normal spellcasting level. For example, suppose we have a Multiclassed Wizard 5/Eldritch Knight 11. We add their levels by first dividing them by the level of spellcaster they are, so we take 5 Wizard Levels (5 \* 1/1 = 5) and 11 Eldritch Knight Levels (11 \* 1/3 = 3.666 → Rounded Down to 3) and add them together to find that this character is the equivalent of a Level 8 Spellcaster, gaining 4 1st Level Slots, 3 2nd Level Slots, 3 3rd Level Slots, and 2 4th Level Slots.
The fractions here come from the multiclassing rules: when figuring out what level of “multiclassed spellcaster” you are, in order to figure out your spell slots, you need to add your full level in some classes (like wizard), half your level in other classes (like paladin), and a third of your level in yet other classes (like arcane trickster). These fractions roughly correspond to how much spellcasting those classes actually give: wizards and other “1” classes get 9th-level spells, paladins and other “½” classes get 5th-level spells, and arcane tricksters and other “⅓” classes get 4th-level spells.
152,448
I saw in a [recent answer](https://rpg.stackexchange.com/a/152447/15689) a reference to 1/3 casters and 1/2 casters, and have never encountered this terminology before: > > Paladin's are known as 1/2 casters, so their spell progression isn't as big as full casters. > > > What does it mean to be a 1/3 caster vs a 1/2 caster vs a full caster? How does one distinguish between the three, and which classes correspond to which types of caster?
2019/07/25
[ "https://rpg.stackexchange.com/questions/152448", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/15689/" ]
"1/X Caster" is shorthand for how quickly a character gains "spellcaster levels" (and with them, more spell slots) ================================================================================================================== The progression for each of these spellcaster types looks like this, with the first column representing Character Level as a Single-classed X and the other columns representing the "Spellcaster Level" they have as that Single-classed X at a given level. | **Character Level** | **Full** | **Half** | **Third** | | --- | --- | --- | --- | | 1 | 1 | - | - | | 2 | 2 | 1 | - | | 3 | 3 | 2 | 1 | | 4 | 4 | 2 | 2 | | 5 | 5 | 3 | 2 | | 6 | 6 | 3 | 2 | | 7 | 7 | 4 | 3 | | 8 | 8 | 4 | 3 | | 9 | 9 | 5 | 3 | | 10 | 10 | 5 | 4 | | 11 | 11 | 6 | 4 | | 12 | 12 | 6 | 4 | | 13 | 13 | 7 | 5 | | 14 | 14 | 7 | 5 | | 15 | 15 | 8 | 5 | | 16 | 16 | 8 | 6 | | 17 | 17 | 9 | 6 | | 18 | 18 | 9 | 6 | | 19 | 19 | 10 | 7 | | 20 | 20 | 10 | 7 | The classes that fall into these categories are: | **Full** | **Half** | **Third** | **Other** | | --- | --- | --- | --- | | Bard | Artificer\* | Arcane Trickster | Warlock† | | Cleric | Paladin | Artificer (Unearthed Arcana) | | | Druid | Ranger | Eldritch Knight | | | Sorcerer | | | | | Wizard | | | | \*The Artificer is a Half-Spellcaster, but unlike other Half Spellcasters, they gain their spellcasting feature at level 1, instead of level 2, and are treated like level 1 spellcasters at that level. †Warlocks are unique in that their spell access *resembles* that of a Full Spellcaster, but their Spell Slots are completely divorced from the system that all other spellcasters use, so they need their own category. Your spellcaster level determines how many spell slots you have, and the maximum level of spell slot that you'll have will (usually) be half your spellcasting level, rounded up. So if you're a level 9 Paladin (Half Spellcaster), you have a Spellcaster level of 5 (See the Character Level 9 row for a Half Spellcaster). Therefore, you have spell slots equivalent to a level 5 Cleric (Full Spellcaster) and to a level 13 (or 14 or 15) Eldritch Knight (Third Spellcaster)—and for each of these characters, their Spell Slot total is: * 4 1st Level Slots, * 3 2nd Level Slots, * 2 3rd Level Slots. "1/X Caster" also comes into play in the Multiclassing Rules ============================================================ What kind of Spellcaster you are affects how your levels are added together when you Multiclass into multiple kinds of spellcaster. > > **Spell Slots.** You determine your available spell slots by adding together all your levels in the bard, cleric, druid, sorcerer, and wizard classes, half your levels (rounded down) in the paladin and ranger classes, and a third of your fighter or rogue levels (rounded down) if you have the Eldritch Knight or the Arcane Trickster feature.† Use this total to determine your spell slots by consulting the Multiclass Spellcaster table. > > > —**Multiclassing**, Player's Handbook, pg. 164 > > > †Artificers have a special rule: when adding their levels for multiclassing purposes, you round up after dividing by two, instead of rounding down. Note also that Warlocks are not included in this list; again, their Spellcasting is completely different from other classes, so they aren't considered in calculating a character's normal spellcasting level. For example, suppose we have a Multiclassed Wizard 5/Eldritch Knight 11. We add their levels by first dividing them by the level of spellcaster they are, so we take 5 Wizard Levels (5 \* 1/1 = 5) and 11 Eldritch Knight Levels (11 \* 1/3 = 3.666 → Rounded Down to 3) and add them together to find that this character is the equivalent of a Level 8 Spellcaster, gaining 4 1st Level Slots, 3 2nd Level Slots, 3 3rd Level Slots, and 2 4th Level Slots.
It refers to the speed at which classes gain spell slots and new levels of spells during their progression. Full casters (like a Wizard) gain spell slots fastest, while 1/3rd casters only gain slots and new spell levels at about a third that rate. The name "1/2 caster" and "1/3 caster" comes from the Multiclassing rules, which state that if you have levels in multiple classes capable of casting spells, you use a specific table to determine your spell slots. You only get to add half and a third of the levels in those classes (rounded down) to determine your total spell slots. You can read more about this in the PHB on page 164, under the header "Spellcasting". Note that these terms only refer to classes that have the **Spellcasting** class feature. Classes that cast spells through a different system (like a Warlock or 4 Elements Monk) don't have a caster progression and don't stack with levels in other classes when multiclassing. For a list of classes: ### Full casters * Bard * Cleric * Druid * Sorceror * Wizard ### Half casters * Paladin * Ranger ### Third casters * Eldritch Knight Fighters * Arcane Trickster Rogues
2,616,443
I'm looking for some examples which could show that normal topological space doesn't imply the space is paracompact. Thanks in advance.
2018/01/22
[ "https://math.stackexchange.com/questions/2616443", "https://math.stackexchange.com", "https://math.stackexchange.com/users/333019/" ]
The space $\omega\_1$, the set of countable ordinals, in the order topology, is hereditarily normal (as all ordered spaces), countably (para)compact, collectionwise normal, but not paracompact, because a paracompact countably compact is compact, which $\omega\_1$ is not. The nice resource [$\pi$-base](https://topology.jdabbs.com/spaces?q=T_4%20%2B%20~Paracompact) has some more examples, some derived from this one (like the long line), others like Dowker spaces (a normal not countably paracompact space, which are harder to come by). Bing's spaces like "G" (nicely explained [here](https://dantopology.wordpress.com/2016/12/05/a-stroll-in-bings-example-g/) and "H" (see [here](https://dantopology.wordpress.com/2014/02/02/bings-example-h/)) are also classics, introduced to explore the gap between normality-like properties and paracompact-like properties. I think $\omega\_1$ is the easiest example though.
An example is built here, have you read it: <https://projecteuclid.org/download/pdf_1/euclid.bams/1183549052>
501,816
I'm using C++ to understand how exactly pointers work. I have this piece of code using arrays, which I'm using just to understand how the equivalent works with pointers. ``` int main() { int arr[10] = {1,2,3}; char arr2[10] = {'c','i','a','o','\0'}; cout << arr << endl; cout << arr2 << endl; } ``` However when I run this, `arr` outputs the address of the first element of the array of ints (as expected) but `arr2` doesn't output the address of the first element of the array of chars; it actually prints "ciao". What is it that I'm missing or that I haven't learned yet about this?
2009/02/01
[ "https://Stackoverflow.com/questions/501816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50394/" ]
Because cout's `operator <<` is overloaded for `char*` to output strings, and `arr2` matches that. If you want the address, try casting the character array as a void pointer.
There is a standard overload for char\* that outputs a NUL terminated string.
501,816
I'm using C++ to understand how exactly pointers work. I have this piece of code using arrays, which I'm using just to understand how the equivalent works with pointers. ``` int main() { int arr[10] = {1,2,3}; char arr2[10] = {'c','i','a','o','\0'}; cout << arr << endl; cout << arr2 << endl; } ``` However when I run this, `arr` outputs the address of the first element of the array of ints (as expected) but `arr2` doesn't output the address of the first element of the array of chars; it actually prints "ciao". What is it that I'm missing or that I haven't learned yet about this?
2009/02/01
[ "https://Stackoverflow.com/questions/501816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50394/" ]
It's the operator<< that is overloaded for `const void*` and for `const char*`. Your char array is converted to `const char*` and passed to that overload, because it fits better than to `const void*`. The int array, however, is converted to `const void*` and passed to that version. The version of operator<< taking `const void*` just outputs the address. The version taking the `const char*` actually treats it like a C-string and outputs every character until the terminating null character. If you don't want that, convert your char array to `const void*` explicitly when passing it to operator<<: ``` cout << static_cast<const void*>(arr2) << endl; ```
There is a standard overload for char\* that outputs a NUL terminated string.
501,816
I'm using C++ to understand how exactly pointers work. I have this piece of code using arrays, which I'm using just to understand how the equivalent works with pointers. ``` int main() { int arr[10] = {1,2,3}; char arr2[10] = {'c','i','a','o','\0'}; cout << arr << endl; cout << arr2 << endl; } ``` However when I run this, `arr` outputs the address of the first element of the array of ints (as expected) but `arr2` doesn't output the address of the first element of the array of chars; it actually prints "ciao". What is it that I'm missing or that I haven't learned yet about this?
2009/02/01
[ "https://Stackoverflow.com/questions/501816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50394/" ]
It's the operator<< that is overloaded for `const void*` and for `const char*`. Your char array is converted to `const char*` and passed to that overload, because it fits better than to `const void*`. The int array, however, is converted to `const void*` and passed to that version. The version of operator<< taking `const void*` just outputs the address. The version taking the `const char*` actually treats it like a C-string and outputs every character until the terminating null character. If you don't want that, convert your char array to `const void*` explicitly when passing it to operator<<: ``` cout << static_cast<const void*>(arr2) << endl; ```
Because cout's `operator <<` is overloaded for `char*` to output strings, and `arr2` matches that. If you want the address, try casting the character array as a void pointer.
501,816
I'm using C++ to understand how exactly pointers work. I have this piece of code using arrays, which I'm using just to understand how the equivalent works with pointers. ``` int main() { int arr[10] = {1,2,3}; char arr2[10] = {'c','i','a','o','\0'}; cout << arr << endl; cout << arr2 << endl; } ``` However when I run this, `arr` outputs the address of the first element of the array of ints (as expected) but `arr2` doesn't output the address of the first element of the array of chars; it actually prints "ciao". What is it that I'm missing or that I haven't learned yet about this?
2009/02/01
[ "https://Stackoverflow.com/questions/501816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50394/" ]
Because cout's `operator <<` is overloaded for `char*` to output strings, and `arr2` matches that. If you want the address, try casting the character array as a void pointer.
While casting is probably a more meaningful approach, you could also use the addressof operator: ``` cout << &arr2 << endl; ```
501,816
I'm using C++ to understand how exactly pointers work. I have this piece of code using arrays, which I'm using just to understand how the equivalent works with pointers. ``` int main() { int arr[10] = {1,2,3}; char arr2[10] = {'c','i','a','o','\0'}; cout << arr << endl; cout << arr2 << endl; } ``` However when I run this, `arr` outputs the address of the first element of the array of ints (as expected) but `arr2` doesn't output the address of the first element of the array of chars; it actually prints "ciao". What is it that I'm missing or that I haven't learned yet about this?
2009/02/01
[ "https://Stackoverflow.com/questions/501816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50394/" ]
It's the operator<< that is overloaded for `const void*` and for `const char*`. Your char array is converted to `const char*` and passed to that overload, because it fits better than to `const void*`. The int array, however, is converted to `const void*` and passed to that version. The version of operator<< taking `const void*` just outputs the address. The version taking the `const char*` actually treats it like a C-string and outputs every character until the terminating null character. If you don't want that, convert your char array to `const void*` explicitly when passing it to operator<<: ``` cout << static_cast<const void*>(arr2) << endl; ```
While casting is probably a more meaningful approach, you could also use the addressof operator: ``` cout << &arr2 << endl; ```
46,226,287
I have a cluster/server with multiple nodes that handle requests from the application. The application the user is running, opens 2 web clients with the following URLs: * <https://myprocess.myapp.com/api/json/v1> * <https://myprocess.myapp.com/api/protobuf/v1> In order to support stickiness (I want each of the 2 web clients will keep the connection against the nodes - persistence), the [ConnectionLeaseTimeout](https://msdn.microsoft.com/en-us/library/system.net.servicepoint.connectionleasetimeout(v=vs.110).aspx) stayed with the default value, which means "don't close the connection" and because the [DefaultPersistentConnectionLimit](https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.defaultpersistentconnectionlimit(v=vs.110).aspx) is 2 by default, I set the [DefaultConnectionLimit](https://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.defaultconnectionlimit(v=vs.110).aspx) to 1. **The problem:** 1. servicePoint.CurrentConnections is 2, although servicePoint.ConnectionLimit is 1. 2. In the server, I see that the remote host port is changing, i.e. I see more than 2 ports (more than 1 port for each client). **What am I doing wrong?** My class output: CommunicationWebClient <https://myprocess.myapp.com/api/json/v1> CommunicationWebClient <https://myprocess.myapp.com/api/protobuf/v1> SendAsync \_uri=<https://myprocess.myapp.com/api/json/v1> servicePoint.Address=<https://myprocess.myapp.com/api/json/v1> servicePoint.ConnectionLimit=1 servicePoint.CurrentConnections=2 ... SendAsync \_uri=<https://myprocess.myapp.com/api/protobuf/v1> servicePoint.Address=<https://myprocess.myapp.com/api/json/v1> servicePoint.ConnectionLimit=1 servicePoint.CurrentConnections=2 ... ``` public sealed class CommunicationWebClient : IDisposable { private HttpClient _httpClient; private Uri _uri; public CommunicationWebClient(Uri uri) { Logger.Debug($"{nameof(CommunicationWebClient)} {nameof(uri)}={uri}"); _uri = uri; ServicePointManager.DefaultConnectionLimit = 1; _httpClient = new HttpClient(new WebRequestHandler()) { Timeout = 10.Minutes(), }; } public void Dispose() { _httpClient.Dispose(); } public async Task SendAsync( ByteArrayContent content) { var servicePoint = ServicePointManager.FindServicePoint(_uri); Logger.Debug($"{nameof(SendAsync)} " + $"{nameof(_uri)}={_uri} " + $"{nameof(servicePoint.Address)}={servicePoint.Address} " + $"{nameof(servicePoint.ConnectionLimit)}={servicePoint.ConnectionLimit} " + $"{nameof(servicePoint.CurrentConnections)}={servicePoint.CurrentConnections}"); using (var httpResponseMessage = await _httpClient.PostAsync(_uri, content)) { ... } } } ```
2017/09/14
[ "https://Stackoverflow.com/questions/46226287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1806982/" ]
If you still have a problem, check that your CommunicationWebClient is not disposed too often. It disposes HttpClient but it behaves not as usually people expect. Checkout this article: <https://learn.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/> Shortly speaking when you dispose HttpClient in case of windows, you ask windows to close all opened sockets. But by default windows have 4 minute timeout to completely close the socket. So for all these 4 minutes there will be a connection between your HttpClient and web server.
In most cases, http client are recommended to use one per application. Disposing http client doesn't get throwing the socket it used right away .
38,439,194
I must create webhook endpoint that will consume JSON messages. Messages is send as x-www-form-urlencoded in form: > > key = json > > value = {"user\_Id": "728409840", "call\_id": "1114330","answered\_time": "2015-04-16 15:37:47"} > > > as shown in PostMan: [![enter image description here](https://i.stack.imgur.com/DCDP8.png)](https://i.stack.imgur.com/DCDP8.png) request looks like this: > > json=%7B%22user\_Id%22%3A+%22728409840%22%2C+%22call\_id%22%3A+%221114330%22%2C%22answered\_time%22%3A+%222015-04-16+15%3A37%3A47%22%7D > > > To get values from request as my class (model) I must create temporary object containing single string property: ``` public class Tmp { public string json { get; set; } } ``` and method inside my controller that consumes that request: ``` [AllowAnonymous] [Route("save_data")] [HttpPost] public IHttpActionResult SaveData(Tmp tmp) { JObject json2 = JObject.Parse(tmp.json); var details = json2.ToObject<CallDetails>(); Debug.WriteLine(details); //data processing return Content(HttpStatusCode.OK, "OK", new TextMediaTypeFormatter(), "text/plain"); } ``` As You can see Tmp class is useless. Is there a way to get request data as this class: ``` public class CallDetails { public string UserId { get; set; } public string CallId { get; set; } public string AnsweredTime { get; set; } } ``` I'm aware of `IModelBinder` class, but before I start I'd like to know if there is an easier way. I can't change web-request format, by format I mean that is will always be POST containing single key - `JSON` yhat has json string as value.
2016/07/18
[ "https://Stackoverflow.com/questions/38439194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/965722/" ]
You can use `JsonProperty` attribute for mapping json object properties to c# object properties: ``` public class CallDetails { [JsonProperty("user_id")] public string UserId { get; set; } [JsonProperty("call_id")] public string CallId { get; set; } [JsonProperty("answered_time")] public string AnsweredTime { get; set; } } ``` Then it can be used without temp class: ``` [AllowAnonymous] [Route("save_data")] [HttpPost] public IHttpActionResult SaveData(CallDetails callDetails) ``` --- **Update.** Because the data is sent as x-www-form-urlencoded - I think the way you handled it is most straightforward and not so bad. If you want to check another options here're some of them: Option 1 - custom model binder. Something like this: ``` public class CustomModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var body = actionContext.Request.Content.ReadAsStringAsync().Result; body = body.Replace("json=", ""); var json = HttpUtility.UrlDecode(body); bindingContext.Model = JsonConvert.DeserializeObject<CallDetails>(json); return true; } } ``` And usage: `SaveData([ModelBinder(typeof(CustomModelBinder))]CallDetails callDetails)`. Downside - you'll lose validation and maybe other stuff defined in web api pipeline. Option 2 - `DelegatingHandler` ``` public class NormalizeHandler : DelegatingHandler { public NormalizeHandler(HttpConfiguration httpConfiguration) { InnerHandler = new HttpControllerDispatcher(httpConfiguration); } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var source = await request.Content.ReadAsStringAsync(); source = source.Replace("json=", ""); source = HttpUtility.UrlDecode(source); request.Content = new StringContent(source, Encoding.UTF8, "application/json"); return await base.SendAsync(request, cancellationToken); } } ``` Usage: ``` [AllowAnonymous] [HttpPost] public IHttpActionResult SaveData(CallDetails callDetails) ``` Downside - you'll need to define custom route for it: ``` config.Routes.MapHttpRoute( name: "save_data", routeTemplate: "save_data", defaults: new { controller = "YourController", action = "SaveData" }, constraints: null, handler: new NormalizeHandler(config) ); ```
Json.NET by NewtonSoft can help you [deserialize an object](http://www.newtonsoft.com/json/help/html/deserializeobject.htm). If your json property names don't match your actual class names you can write a custom converter to help. **EDIT** You could try this if you are on MVC6. Change your parameter from type `Tmp` to type `CallDetails` and mark it with attribute `[FromBody]`, like this: ``` public IHttpActionResult SaveData([FromBody]CallDetails details) ``` For example look at the section "Different model binding" in [this post](http://www.dotnetcurry.com/aspnet-mvc/1149/convert-aspnet-webapi2-aspnet5-mvc6). However, I'm still thinking that you will need to deserialize manually because the property names of class `CallDetails` don't exactly match the incoming JSON properties.
38,439,194
I must create webhook endpoint that will consume JSON messages. Messages is send as x-www-form-urlencoded in form: > > key = json > > value = {"user\_Id": "728409840", "call\_id": "1114330","answered\_time": "2015-04-16 15:37:47"} > > > as shown in PostMan: [![enter image description here](https://i.stack.imgur.com/DCDP8.png)](https://i.stack.imgur.com/DCDP8.png) request looks like this: > > json=%7B%22user\_Id%22%3A+%22728409840%22%2C+%22call\_id%22%3A+%221114330%22%2C%22answered\_time%22%3A+%222015-04-16+15%3A37%3A47%22%7D > > > To get values from request as my class (model) I must create temporary object containing single string property: ``` public class Tmp { public string json { get; set; } } ``` and method inside my controller that consumes that request: ``` [AllowAnonymous] [Route("save_data")] [HttpPost] public IHttpActionResult SaveData(Tmp tmp) { JObject json2 = JObject.Parse(tmp.json); var details = json2.ToObject<CallDetails>(); Debug.WriteLine(details); //data processing return Content(HttpStatusCode.OK, "OK", new TextMediaTypeFormatter(), "text/plain"); } ``` As You can see Tmp class is useless. Is there a way to get request data as this class: ``` public class CallDetails { public string UserId { get; set; } public string CallId { get; set; } public string AnsweredTime { get; set; } } ``` I'm aware of `IModelBinder` class, but before I start I'd like to know if there is an easier way. I can't change web-request format, by format I mean that is will always be POST containing single key - `JSON` yhat has json string as value.
2016/07/18
[ "https://Stackoverflow.com/questions/38439194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/965722/" ]
You can use `JsonProperty` attribute for mapping json object properties to c# object properties: ``` public class CallDetails { [JsonProperty("user_id")] public string UserId { get; set; } [JsonProperty("call_id")] public string CallId { get; set; } [JsonProperty("answered_time")] public string AnsweredTime { get; set; } } ``` Then it can be used without temp class: ``` [AllowAnonymous] [Route("save_data")] [HttpPost] public IHttpActionResult SaveData(CallDetails callDetails) ``` --- **Update.** Because the data is sent as x-www-form-urlencoded - I think the way you handled it is most straightforward and not so bad. If you want to check another options here're some of them: Option 1 - custom model binder. Something like this: ``` public class CustomModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var body = actionContext.Request.Content.ReadAsStringAsync().Result; body = body.Replace("json=", ""); var json = HttpUtility.UrlDecode(body); bindingContext.Model = JsonConvert.DeserializeObject<CallDetails>(json); return true; } } ``` And usage: `SaveData([ModelBinder(typeof(CustomModelBinder))]CallDetails callDetails)`. Downside - you'll lose validation and maybe other stuff defined in web api pipeline. Option 2 - `DelegatingHandler` ``` public class NormalizeHandler : DelegatingHandler { public NormalizeHandler(HttpConfiguration httpConfiguration) { InnerHandler = new HttpControllerDispatcher(httpConfiguration); } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var source = await request.Content.ReadAsStringAsync(); source = source.Replace("json=", ""); source = HttpUtility.UrlDecode(source); request.Content = new StringContent(source, Encoding.UTF8, "application/json"); return await base.SendAsync(request, cancellationToken); } } ``` Usage: ``` [AllowAnonymous] [HttpPost] public IHttpActionResult SaveData(CallDetails callDetails) ``` Downside - you'll need to define custom route for it: ``` config.Routes.MapHttpRoute( name: "save_data", routeTemplate: "save_data", defaults: new { controller = "YourController", action = "SaveData" }, constraints: null, handler: new NormalizeHandler(config) ); ```
You don´t forget to decode the url encoded before use JObject.Parse ?, it´s maybe works. And the properties of the object don´t match the json atributes
39,729,591
Is there a way to clone an object with only few properties of the object in JS? For example.. ``` var Person = { name: "Bob", age: 32, salary: 20000 }; ``` I have to create another person object with just the name and age property so that it will look something like this : ``` var clonedPerson = { name: "Bob", age: 32 }; ``` I could do a deep clone of the object and *delete*. But I wanted to know if there are better ways to do it.
2016/09/27
[ "https://Stackoverflow.com/questions/39729591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1614244/" ]
Using the latest ES6, you can achieve this by the following code.. ```js const Person = { name: "Bob", age: 32, salary: 20000 }; const { salary , ...clonedPerson } = Person console.log(clonedPerson) ```
More simple? ```js var Person = { name: "Bob", age: 32, salary: 20000 }; var ClonedPerson = jQuery.extend({}, Person); delete ClonedPerson.salary; console.log(JSON.stringify(Person)); console.log(JSON.stringify(ClonedPerson)); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ```
39,729,591
Is there a way to clone an object with only few properties of the object in JS? For example.. ``` var Person = { name: "Bob", age: 32, salary: 20000 }; ``` I have to create another person object with just the name and age property so that it will look something like this : ``` var clonedPerson = { name: "Bob", age: 32 }; ``` I could do a deep clone of the object and *delete*. But I wanted to know if there are better ways to do it.
2016/09/27
[ "https://Stackoverflow.com/questions/39729591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1614244/" ]
More simple? ```js var Person = { name: "Bob", age: 32, salary: 20000 }; var ClonedPerson = jQuery.extend({}, Person); delete ClonedPerson.salary; console.log(JSON.stringify(Person)); console.log(JSON.stringify(ClonedPerson)); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ```
an alternative approach using Array member methods: ``` var clone = Object.keys(Person) // convert to an Array of Person keys .filter(function(key){return ["salary"].indexOf(key) == -1;}) // exclude key salary .reduce(function(clone, current){clone[current] = Person[current]; return clone;}, {}); // convert back the array to a cloned literal object ```
39,729,591
Is there a way to clone an object with only few properties of the object in JS? For example.. ``` var Person = { name: "Bob", age: 32, salary: 20000 }; ``` I have to create another person object with just the name and age property so that it will look something like this : ``` var clonedPerson = { name: "Bob", age: 32 }; ``` I could do a deep clone of the object and *delete*. But I wanted to know if there are better ways to do it.
2016/09/27
[ "https://Stackoverflow.com/questions/39729591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1614244/" ]
Using the latest ES6, you can achieve this by the following code.. ```js const Person = { name: "Bob", age: 32, salary: 20000 }; const { salary , ...clonedPerson } = Person console.log(clonedPerson) ```
an alternative approach using Array member methods: ``` var clone = Object.keys(Person) // convert to an Array of Person keys .filter(function(key){return ["salary"].indexOf(key) == -1;}) // exclude key salary .reduce(function(clone, current){clone[current] = Person[current]; return clone;}, {}); // convert back the array to a cloned literal object ```
16,817
My question is what are potential reasons for Naive Bayes to perform well on a train set but poorly on a test set? I am working with a variation of the [20news dataset](http://qwone.com/~jason/20Newsgroups/). The dataset has documents, which are represented as "bag of words" with no metadata. My goal is to classify each document into 1 of 20 labels. My error rate on training data is 20%, but my error rate on test data is 90% (for comparison, guessing yields 95% error rate). For some reason, my classifier is predicting class 16 for almost all documents in test set. In train set this problem does not occur. Furthermore, this issue persists with different train/test splits. I'm trying to figure out what I'm doing wrong. Here are some things I've considered: * Is Naive Bayes overfitting to the training set? If Naive Bayes is implemented correctly, I don't think it should be overfitting like this on a task that it's considered appropriate for (text classification). * Is my train/test split bad? I've tried splitting the data in different ways, but it does not seem to make a difference. Right now I'm splitting the data by placing a random 90% sample of documents into the train set and the rest into the test set - separately for each label. * Problems with numerical accuracy? I've implemented the calculations in log probabilities, but in any case, I would expect that problem to manifest in train set as well. * Problems with unseen words? The fraction of unseen words relative to a particular newsgroup is the same, 20%, for both train and test sets. * Problems with Laplace smoothing? I wasn't sure what was the appropriate way to implement Laplace smoothing for this task, so I tried a variety of ways. To my surprise they all yielded very similar results. * Imbalanced dataset? Doesn't look like it. There are approximately as many unique words inside documents of label 16 as there are in other classes. Also the number of documents per each label is roughly even. Edit: Turns out I had an implementation bug. I won't detail it here as it will be unlikely to help anyone with similar issues.
2017/02/07
[ "https://datascience.stackexchange.com/questions/16817", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/23480/" ]
Text mining is rather a tricky field of machine learning application, since all you've got is "unstructured and semi structured data" and the preprocessing and feature extraction step matters a lot. [The text mining handbook](http://www.goodreads.com/book/show/893219.The_Text_Mining_Handbook) is a priceless reference in this area of research. but to be specific about your case, I can suggest two answers: * as noted, preprocessing step plays a very important role here. in text mining it is likely to get trapped inside the curse of dimensionality, since you probably have say around 1000 documents but more than 15000 unique words in a dataset. techniques such as stemming and lemmatizing, static and dynamic stopword and punctuation erasing all aim solving this issue. So preprocessing and feature extraction is not an option. it is a MUST * Naive Bayes model is a linear classifier. Even though it is a very popular algorithm in text classification, there are still risks of rising such problems as yours. the main reason could be that your word-space matrix is highly sparse. you must have paid attention to the fact that in calculating the posterior probability of belonging to a class, Naive Bayes, naively multiplies all single probabilities of `P(y|x_i)`. and if there is at least one zero probability, your final answer would be zero, no matter what other inverse observation probabilities are. If you have implemented the algorithm yourself, try already-constructed tools in MATLAB, Python sci-kit learn library, or data mining softwares like KNIME and RapidMiner. they have delicately handled such practical issues in implementing Naive Bayes algorithm.
Unless you're doing it on some other related file, you're not removing stopwords. If label 16 makes a great use of such, that's a plausible explanation for such result. On the other hand (unless again, you're doing it on some other file) you're not reducing words to their morphemes. Not doing so might cause these kind of anomalies. Check the Nltk documentation to learn how to do such thing.
16,817
My question is what are potential reasons for Naive Bayes to perform well on a train set but poorly on a test set? I am working with a variation of the [20news dataset](http://qwone.com/~jason/20Newsgroups/). The dataset has documents, which are represented as "bag of words" with no metadata. My goal is to classify each document into 1 of 20 labels. My error rate on training data is 20%, but my error rate on test data is 90% (for comparison, guessing yields 95% error rate). For some reason, my classifier is predicting class 16 for almost all documents in test set. In train set this problem does not occur. Furthermore, this issue persists with different train/test splits. I'm trying to figure out what I'm doing wrong. Here are some things I've considered: * Is Naive Bayes overfitting to the training set? If Naive Bayes is implemented correctly, I don't think it should be overfitting like this on a task that it's considered appropriate for (text classification). * Is my train/test split bad? I've tried splitting the data in different ways, but it does not seem to make a difference. Right now I'm splitting the data by placing a random 90% sample of documents into the train set and the rest into the test set - separately for each label. * Problems with numerical accuracy? I've implemented the calculations in log probabilities, but in any case, I would expect that problem to manifest in train set as well. * Problems with unseen words? The fraction of unseen words relative to a particular newsgroup is the same, 20%, for both train and test sets. * Problems with Laplace smoothing? I wasn't sure what was the appropriate way to implement Laplace smoothing for this task, so I tried a variety of ways. To my surprise they all yielded very similar results. * Imbalanced dataset? Doesn't look like it. There are approximately as many unique words inside documents of label 16 as there are in other classes. Also the number of documents per each label is roughly even. Edit: Turns out I had an implementation bug. I won't detail it here as it will be unlikely to help anyone with similar issues.
2017/02/07
[ "https://datascience.stackexchange.com/questions/16817", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/23480/" ]
Let me try to answer your questions point by point. Perhaps you already solved your problem, but your questions are interesting and so perhaps other people can benefit from this discussion. * Is Naive Bayes overfitting to the training set? If Naive Bayes is implemented correctly, I don't think it should be overfitting like this on a task that it's considered appropriate for (text classification). > > Naive Bayes has shown to perform well on document classification, but that doesn't mean that it cannot overfit data. There is a difference between the task, document classification, and the data. Overfitting can happen even if Naive Bayes is implemented properly. > > > * Is my train/test split bad? I've tried splitting the data in different ways, but it does not seem to make a difference. Right now I'm splitting the data by placing a random 90% sample of documents into the train set and the rest into the test set - separately for each label. > > It's good that you're keeping the class distribution the same in your training and test set. Are you using cross-validation? Perhaps try it because, even though it's rare, it might happen that you just get unlucky with your splitting due to some seed. > > > * Problems with numerical accuracy? I've implemented the calculations in log probabilities, but in any case, I would expect that problem to manifest in train set as well. > > You're correct, if it was an issue, it would show in the training set as well. > > > * Problems with unseen words? The fraction of unseen words relative to a particular newsgroup is the same, 20%, for both train and test sets. > > This doesn't seem to be the issue then. You could perhaps reduce that percentage by using stemming or lemmatization. > > > * Problems with Laplace smoothing? I wasn't sure what was the appropriate way to implement Laplace smoothing for this task, so I tried a variety of ways. To my surprise they all yielded very similar results. > > Laplace smoothing is useful especially when you do not have a lot of data and you need to account for some uncertainty. For this dataset, this doesn't seem to be an issue, as shown by the similar results you've experienced. > > > * Imbalanced dataset? Doesn't look like it. There are approximately as many unique words inside documents of label 16 as there are in other classes. Also the number of documents per each label is roughly even. > > Are the documents of the same lengths? Because perhaps label 16 simply contains documents that are larger and therefore have bigger word frequencies. They might also contain very common words. It would be interesting to look at a histogram of the words in each class. This could be very informative in understanding whether label 16 is very different from the others. > > >
Unless you're doing it on some other related file, you're not removing stopwords. If label 16 makes a great use of such, that's a plausible explanation for such result. On the other hand (unless again, you're doing it on some other file) you're not reducing words to their morphemes. Not doing so might cause these kind of anomalies. Check the Nltk documentation to learn how to do such thing.
16,817
My question is what are potential reasons for Naive Bayes to perform well on a train set but poorly on a test set? I am working with a variation of the [20news dataset](http://qwone.com/~jason/20Newsgroups/). The dataset has documents, which are represented as "bag of words" with no metadata. My goal is to classify each document into 1 of 20 labels. My error rate on training data is 20%, but my error rate on test data is 90% (for comparison, guessing yields 95% error rate). For some reason, my classifier is predicting class 16 for almost all documents in test set. In train set this problem does not occur. Furthermore, this issue persists with different train/test splits. I'm trying to figure out what I'm doing wrong. Here are some things I've considered: * Is Naive Bayes overfitting to the training set? If Naive Bayes is implemented correctly, I don't think it should be overfitting like this on a task that it's considered appropriate for (text classification). * Is my train/test split bad? I've tried splitting the data in different ways, but it does not seem to make a difference. Right now I'm splitting the data by placing a random 90% sample of documents into the train set and the rest into the test set - separately for each label. * Problems with numerical accuracy? I've implemented the calculations in log probabilities, but in any case, I would expect that problem to manifest in train set as well. * Problems with unseen words? The fraction of unseen words relative to a particular newsgroup is the same, 20%, for both train and test sets. * Problems with Laplace smoothing? I wasn't sure what was the appropriate way to implement Laplace smoothing for this task, so I tried a variety of ways. To my surprise they all yielded very similar results. * Imbalanced dataset? Doesn't look like it. There are approximately as many unique words inside documents of label 16 as there are in other classes. Also the number of documents per each label is roughly even. Edit: Turns out I had an implementation bug. I won't detail it here as it will be unlikely to help anyone with similar issues.
2017/02/07
[ "https://datascience.stackexchange.com/questions/16817", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/23480/" ]
Let me try to answer your questions point by point. Perhaps you already solved your problem, but your questions are interesting and so perhaps other people can benefit from this discussion. * Is Naive Bayes overfitting to the training set? If Naive Bayes is implemented correctly, I don't think it should be overfitting like this on a task that it's considered appropriate for (text classification). > > Naive Bayes has shown to perform well on document classification, but that doesn't mean that it cannot overfit data. There is a difference between the task, document classification, and the data. Overfitting can happen even if Naive Bayes is implemented properly. > > > * Is my train/test split bad? I've tried splitting the data in different ways, but it does not seem to make a difference. Right now I'm splitting the data by placing a random 90% sample of documents into the train set and the rest into the test set - separately for each label. > > It's good that you're keeping the class distribution the same in your training and test set. Are you using cross-validation? Perhaps try it because, even though it's rare, it might happen that you just get unlucky with your splitting due to some seed. > > > * Problems with numerical accuracy? I've implemented the calculations in log probabilities, but in any case, I would expect that problem to manifest in train set as well. > > You're correct, if it was an issue, it would show in the training set as well. > > > * Problems with unseen words? The fraction of unseen words relative to a particular newsgroup is the same, 20%, for both train and test sets. > > This doesn't seem to be the issue then. You could perhaps reduce that percentage by using stemming or lemmatization. > > > * Problems with Laplace smoothing? I wasn't sure what was the appropriate way to implement Laplace smoothing for this task, so I tried a variety of ways. To my surprise they all yielded very similar results. > > Laplace smoothing is useful especially when you do not have a lot of data and you need to account for some uncertainty. For this dataset, this doesn't seem to be an issue, as shown by the similar results you've experienced. > > > * Imbalanced dataset? Doesn't look like it. There are approximately as many unique words inside documents of label 16 as there are in other classes. Also the number of documents per each label is roughly even. > > Are the documents of the same lengths? Because perhaps label 16 simply contains documents that are larger and therefore have bigger word frequencies. They might also contain very common words. It would be interesting to look at a histogram of the words in each class. This could be very informative in understanding whether label 16 is very different from the others. > > >
Text mining is rather a tricky field of machine learning application, since all you've got is "unstructured and semi structured data" and the preprocessing and feature extraction step matters a lot. [The text mining handbook](http://www.goodreads.com/book/show/893219.The_Text_Mining_Handbook) is a priceless reference in this area of research. but to be specific about your case, I can suggest two answers: * as noted, preprocessing step plays a very important role here. in text mining it is likely to get trapped inside the curse of dimensionality, since you probably have say around 1000 documents but more than 15000 unique words in a dataset. techniques such as stemming and lemmatizing, static and dynamic stopword and punctuation erasing all aim solving this issue. So preprocessing and feature extraction is not an option. it is a MUST * Naive Bayes model is a linear classifier. Even though it is a very popular algorithm in text classification, there are still risks of rising such problems as yours. the main reason could be that your word-space matrix is highly sparse. you must have paid attention to the fact that in calculating the posterior probability of belonging to a class, Naive Bayes, naively multiplies all single probabilities of `P(y|x_i)`. and if there is at least one zero probability, your final answer would be zero, no matter what other inverse observation probabilities are. If you have implemented the algorithm yourself, try already-constructed tools in MATLAB, Python sci-kit learn library, or data mining softwares like KNIME and RapidMiner. they have delicately handled such practical issues in implementing Naive Bayes algorithm.
52,540,983
I have a quick question. I have a form with a for loop. Each for loop has a text box. I want to have two buttons that when I click on one, all the text boxes get populated with the value in the button. For example, when I click on the button "Add 50 minutes," I want all my text boxes to populate with 50. The same goes for if I click on the button "Add 110 minutes" (Screen shot attached) [![Image](https://i.stack.imgur.com/Y8qIw.png)](https://i.stack.imgur.com/Y8qIw.png) Here is my form ``` @using (Html.BeginForm("Index", "Minutes", FormMethod.Post, new { enctype = "multipart/form-date", onsubmit = "popup()" })) { @Html.ValidationSummary(true) <fieldset> <div> <table id="tablereport" class="table table-striped table-bordered table-hover table-condensed"> <thead style="background-color:black; font-weight:bold; color:aliceblue"> <tr> </thead> <tr> <td><b>@Html.Label("Date :")</b></td> <td>@Html.TextBox("datepicker", DateTime.Now.ToString("MM/dd/yyyy"), new { required = "required" })</td> </tr> <tr> <td><input type="button" id="btnSetText" value="Add 50 Minutes" class="btn btn-default" onclick="setText" /></td> <td><input type="button" value="Add 110 Minutes" class="btn btn-default" /></td> </tr> </table> </div> @if (ViewBag.Message != null) { <div id="dialog-message" title="Alert !!"> <p> <span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span> @ViewBag.Message </p> </div> } <table id="tablereport" class="table table-striped table-bordered table-hover table-condensed"> <thead style="background-color:black; font-weight:bold; color:aliceblue"> <tr> </thead> <tr> <th>Class ID</th> <th>Course Title</th> <th>Department</th> <th>SID</th> <th>Full Name</th> <th>Minutes</th> </tr> @for (var i = 0; i < Model.Count; i++) { <tr> <td> @Html.DisplayFor(model => model[i].ClassID) @Html.HiddenFor(model => model[i].ClassID) </td> <td> @Html.DisplayFor(model => model[i].CourseTitle) @Html.HiddenFor(model => model[i].CourseTitle) </td> <td> @Html.DisplayFor(model => model[i].Department) @Html.HiddenFor(model => model[i].Department) </td> <td> @Html.DisplayFor(model => model[i].SID) @Html.HiddenFor(model => model[i].SID) </td> <td> @Html.DisplayFor(model => model[i].FullName) @Html.HiddenFor(model => model[i].FullName) </td> <td> @Html.TextBoxFor(model => model[i].Minutes, new { @Value = "0" }) @Html.ValidationMessageFor(model => model[i].Minutes) </td> </tr> } </table> <table align="center"> <tr> <td><input type="submit" value="Save" class="btn btn-default" onclick="popup()" /></td> </tr> </table> </fieldset> } ``` Here is my script ``` <script> var date = new Date(); var maxdate = date.getDate(); //var currentDate = $(".selector").datepicker("getDate"); $(function () { $("#datepicker").datepicker({ defaultDate: maxdate, minDate: '-1M', maxDate: '+0D' }); }); **function setText(){ var setText = document.getElementById('setText'); setText.value = '50'; }** ``` The script I have is working, but will only populate one text box. Thank you!!
2018/09/27
[ "https://Stackoverflow.com/questions/52540983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9554984/" ]
Rather than hiding, showing, and repositioning the dice elements you have created, you could just create the element you need on click (with some css modifications to take advantage of the random number generation to help position the dots). As an aside, there is no real need for jQuery here, but it is used in the example since you were using it in your original approach. The js creates a click event listener on the `#roll` button. Each time the button is clicked, the `num` variable is set to a random number between 1 and 6. The `cls` variable sets the prefix for the various classes that determine the positioning of the dots on the die - it assumes the roll is an odd number and then adjusts if it is even. Then, we remove any child elements from `#die` with `empty()` (so any dots from a previous roll are removed before we add new ones). Finally, we use a loop to append the same number of dots to `#die` as generated in our `num` variable. At the same time, we append the numbered class for each dot (which is why we named our classes `odd-1`, `even-1`, etc). For example: ```js $('#roll').click(() => { const num = Math.floor(Math.random() * 6) + 1; let cls = 'odd-' if (num % 2 === 0) { cls = 'even-' } $('#die').empty(); for (let i = 1; i <= num; i++) { $('#die').append(`<div class="dot ${cls}${i}"></div>`); } }); ``` ```css .dice { position: relative; margin: 8px; border: solid 3px #aaa; border-radius: 3px; width: 100px; height: 100px; } .dice .dot { position: absolute; background: #000; border-radius: 50%; width: 16px; height: 16px; transform: translate(-8px, -8px); } .odd-1 { top: 50%; left: 50%; } .even-1, .odd-2 { top: 25%; left: 25%; } .even-2, .odd-3 { top: 75%; left: 75%; } .even-3, .odd-4 { top: 75%; left: 25%; } .even-4, .odd-5 { top: 25%; left: 75%; } .even-5 { top: 50%; left: 75%; } .even-6 { top: 50%; left: 25%; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <button id="roll" type="button">Click to roll</button> <div id="die" class="dice"> </div> </div> ```
Something possessed me to create a Vanilla JS version of @benvc's excellent answer (upvoted). This uses the exact same strategy, but of course without the jQuery conveniences like `.empty()` and `.append()` I also chose to use `const` in place of `let` where possible, collapsed the determination of the class name "cls" into a ternary `?:` in place of an `if`, and I'm displaying the random number to visually confirm that the rendered die matches the number which makes for minor changes in the HTML. The CSS is completely unchanged. ```js const die = document.getElementById('die'); const val = document.getElementById('value'); document.getElementById('roll') .addEventListener('click', () => { const num = Math.floor(Math.random() * 6) + 1; const cls = num % 2 === 0 ? 'even-' : 'odd-'; val.innerText = num; die.innerHTML = ''; for (let i = 1; i <= num; i++) { die.innerHTML += `<div class="dot ${cls}${i}"></div>`; } }); ``` ```css .dice { position: relative; margin: 8px; border: solid 3px #aaa; border-radius: 3px; width: 100px; height: 100px; } .dice .dot { position: absolute; background: #000; border-radius: 50%; width: 16px; height: 16px; transform: translate(-8px, -8px); } .odd-1 { top: 50%; left: 50%; } .even-1, .odd-2 { top: 25%; left: 25%; } .even-2, .odd-3 { top: 75%; left: 75%; } .even-3, .odd-4 { top: 75%; left: 25%; } .even-4, .odd-5 { top: 25%; left: 75%; } .even-5 { top: 50%; left: 75%; } .even-6 { top: 50%; left: 25%; } ``` ```html <div> <button id="roll" type="button">Click to roll</button> <span id="value">0</span> <div id="die" class="dice"></div> </div> ```
39,808,267
I have a script that inserts a new user into a table, and the user is defined by the id. I use the id in several other tables to relate certain aspects to that user. For example: ``` USER TABLE id | phone number CATEGORY TABLE id | userID | cat1 | cat2 TRACKING TABLE id | userID | track1 ``` In the three tables above, I use the id from USER TABLE to relate that entry to the userID in the two other tables. I am attempting to take the newest id (max(id)) from USER TABLE to input default values into the other two tables. For example, when user 3 (id=3, auto\_increment) is added to the USER TABLE through an onboarding process from my home page, and SQL script will take the id number and input it into userID in the other two tables as well as default values for cat1, cat2, and track1. Is there an efficient way to do this with one query or one block of queries that can be sent at once?
2016/10/01
[ "https://Stackoverflow.com/questions/39808267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6605868/" ]
Use `last_insert_id()`: ``` insert into usertable ( phone ) values ( '12345' ); set @userid = last_insert_id(); insert into category ( userid, cat1, cat2 ) values (@userid, 'cat1', 'cat2'); insert into tracking ( userid, track1 ) values (@userid, 'track1'); ```
``` insert into usertable ( phone ) values ( '12345' ); insert into category ( userid, cat1, cat2 ) select u.id , 'cat1', 'cat2' from usertable u where u.phone='12345'; insert into tracking ( userid, track1 ) select id, 'track1' from usertable u where u.phone='12345'; ``` You should probably place a unique constraint on the phone field of usertable and wrap these query in a transaction so there is no duplication.
26,939,837
For some reason im losing scope of ngtable params in my view , everything in ngtableparams is undefined ( i see in angularjs batarang binding ). my controller code is ``` this.contractsParams = new ngTableParams({ defaultSort: 'asc', counts: [], total: 10, // length of data getData: function ($defer, params) { this.MyService.query( angular.bind( function (data) { debugger; $defer.resolve(data.Data); })); } }); ``` also , the getdata is not getting called at all ever. My View ``` <table ng-table="controller.contractsParams"> <tr ng-repeat="contract in $data"> <td data-title="'Title'" data-sortable="'Title'">{{contract.Title}}</td> </tr> ```
2014/11/14
[ "https://Stackoverflow.com/questions/26939837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638366/" ]
For each condition there's a different answer For ``` coalesce(Indicator, 'N') = 'N' ``` You get ``` coalesce('N', 'N') = 'N' --> 'N' = 'N' --> True coalesce('Y', 'N') = 'N' --> 'Y' = 'N' --> False coalesce(Null, 'N') = 'N' --> 'N' = 'N' --> True ``` and for ``` coalesce(Indicator, 'N') = 'Y' ``` you get ``` coalesce('N', 'N') = 'N' --> 'N' = 'N' --> True coalesce('Y', 'N') = 'N' --> 'Y' = 'N' --> False coalesce(Null, 'N') = 'Y' --> 'N' = 'Y' --> False ```
The logic does two things. Functionally, the first expression is equivalent to: ``` (Indicator = 'N' or Indicator is null) ``` In addition, it also prevents an index from being used on `indicator` (in most databases). For a binary indicator, the use of the index is typically of minor importance. In addition, SQL optimizers are pretty bad at using indexes for `or` conditions. And, they almost never use them when a column is an argument to a function.
26,939,837
For some reason im losing scope of ngtable params in my view , everything in ngtableparams is undefined ( i see in angularjs batarang binding ). my controller code is ``` this.contractsParams = new ngTableParams({ defaultSort: 'asc', counts: [], total: 10, // length of data getData: function ($defer, params) { this.MyService.query( angular.bind( function (data) { debugger; $defer.resolve(data.Data); })); } }); ``` also , the getdata is not getting called at all ever. My View ``` <table ng-table="controller.contractsParams"> <tr ng-repeat="contract in $data"> <td data-title="'Title'" data-sortable="'Title'">{{contract.Title}}</td> </tr> ```
2014/11/14
[ "https://Stackoverflow.com/questions/26939837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638366/" ]
For each condition there's a different answer For ``` coalesce(Indicator, 'N') = 'N' ``` You get ``` coalesce('N', 'N') = 'N' --> 'N' = 'N' --> True coalesce('Y', 'N') = 'N' --> 'Y' = 'N' --> False coalesce(Null, 'N') = 'N' --> 'N' = 'N' --> True ``` and for ``` coalesce(Indicator, 'N') = 'Y' ``` you get ``` coalesce('N', 'N') = 'N' --> 'N' = 'N' --> True coalesce('Y', 'N') = 'N' --> 'Y' = 'N' --> False coalesce(Null, 'N') = 'Y' --> 'N' = 'Y' --> False ```
`coalesce(Indicator, 'N')` says if `Indicator is null` then take `N` as it's value else the value holded by `Indicator`. so, if `Indicator is null` then the below condition holds `TRUE` ``` coalesce(Indicator, 'N') = 'N' ```
65,856,095
How can I auto reload html page based on the value assigned to the session? ``` if ($_SESSION["LoadPage"]) { //Reload my html page } ``` I know how to use `<meta http-equiv="refresh" content="5" >` but it cannot start auto refresh itself without someone to refresh Please anyone can help me
2021/01/23
[ "https://Stackoverflow.com/questions/65856095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13303505/" ]
Try; adb root This will switch the adb server as root.
According to android doc. > > Apps that run on Android 11 but target Android 10 (API level 29) can still request the requestLegacyExternalStorage attribute. > > > So try to change your target API level. Recommended way would be to use [ContentResolver](https://developer.android.com/reference/android/content/ContentResolver) or can say [Scoped storage](https://developer.android.com/training/data-storage#scoped-storage) instead of Legacy deprecated storage APIs. Check out this for more details. [Scoped storage enforcement](https://developer.android.com/about/versions/11/privacy/storage#scoped-storage)
65,856,095
How can I auto reload html page based on the value assigned to the session? ``` if ($_SESSION["LoadPage"]) { //Reload my html page } ``` I know how to use `<meta http-equiv="refresh" content="5" >` but it cannot start auto refresh itself without someone to refresh Please anyone can help me
2021/01/23
[ "https://Stackoverflow.com/questions/65856095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13303505/" ]
Try `adb push test.txt /sdcard/`, this will work. On Android 11, we cannot access /mnt by ADB. But use the symlink is ok, see [this link](https://android.stackexchange.com/a/229825/342816) for details. I run `ls` command on the Android 11 emulator, we can see `sdcard -> ?` within `/mnt`, and `sdcard -> /storage/self/primary` within `/`, which means softlink `/mnt/sdcard` is not working on Android 11. ```sh # symeonchen @ SBook in ~ [22:16:05] $ adb shell ls -al / | grep sdcard lrw-r--r-- 1 root root 21 2020-12-17 02:01 sdcard -> /storage/self/primary # symeonchen @ SBook in ~ [22:16:14] $ adb shell ls -al /mnt | grep sdcard l????????? ? ? ? ? ? sdcard -> ? ```
According to android doc. > > Apps that run on Android 11 but target Android 10 (API level 29) can still request the requestLegacyExternalStorage attribute. > > > So try to change your target API level. Recommended way would be to use [ContentResolver](https://developer.android.com/reference/android/content/ContentResolver) or can say [Scoped storage](https://developer.android.com/training/data-storage#scoped-storage) instead of Legacy deprecated storage APIs. Check out this for more details. [Scoped storage enforcement](https://developer.android.com/about/versions/11/privacy/storage#scoped-storage)
15,590,977
I have read [this](http://entityframework.codeplex.com/wikipage?title=Custom%20Conventions) documentation about convention in Entity Framework 6. But it does not contain convention for Relationship. Suppose I have following model: ``` [TablePrefix("mst")] public class Guru { public int Id { get; set; } public int? IdKotaLahir { get; set; } public virtual Kota KotaLahir { get; set; } } ``` I want property `IdKotaLahir` to be foreign key of navigation property `KotaLahir`. Foreign key name is `"Id"+<NavigationPropertyName>`. Is it possible using current version of entity framework (EF 6 alpha 3)?
2013/03/23
[ "https://Stackoverflow.com/questions/15590977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1091308/" ]
firstly, you cannot change div's `background-color`, without changing its CSS `background-color` property. How could you? Guessing what you want is to maintain last background-color (for some action or to swap it back), then save it in some hidden input variables. And then, you can use it to display anywhere you want. Also, if you want to grab the `background-color` property and show it `as a text` on the div, you can do that very easily. ``` var color = $('#selector').css('backgroundColor'); ``` , but it will return you RGB value. if you want hex, use this handy methods: ``` var hexDigits = new Array ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); //Function to convert hex format to a rgb color function rgb2hex(rgb) { rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } function hex(x) { return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; } ``` taken from [here](https://stackoverflow.com/questions/1740700/get-hex-value-rather-than-rgb-value-using-jquery) Update, ======= currently your `divs` are like this: ``` <div id="a1" class="card"></div> <div id="a2" class="card"></div> <div id="a3" class="card"></div> .. .. ``` and since you want to assign a secret color to each of these divs update them through javascript, inside your while loop, to make them like this: ``` <div id="a1" class="card" data-color-index="1"></div> <div id="a2" class="card" data-color-index="2"></div> <div id="a3" class="card" data-color-index="3"></div> ``` now, you when you click on a particular div, grab its index and choose that item from the `colors` array of yours. since, you are `splicing` your original array, i had to make a copy of it, to use it later. you can grab any element's attribute `data-color-index` through jquery like this: ``` $('#selector').data('color-index'); ``` see this [fiddle](http://jsfiddle.net/manishmishra121/WJQkA/7/). it does what you want to do
As Manish said, you cannot change the appearance of the div without changing the CSS property - but there are several hacky ways of doing the same thing. One example is to create a child div in each of the coloured squares that covers the entire area and then set the colour of that div to grey. You can then use the CSS display property to show and hide the overlay divs. However, I would recommend having a copy of the colours in JavaScript and just referring to the value associated with each square when it is clicked instead of checking the DOM every time as this keeps the logic separate from the appearance :)
15,590,977
I have read [this](http://entityframework.codeplex.com/wikipage?title=Custom%20Conventions) documentation about convention in Entity Framework 6. But it does not contain convention for Relationship. Suppose I have following model: ``` [TablePrefix("mst")] public class Guru { public int Id { get; set; } public int? IdKotaLahir { get; set; } public virtual Kota KotaLahir { get; set; } } ``` I want property `IdKotaLahir` to be foreign key of navigation property `KotaLahir`. Foreign key name is `"Id"+<NavigationPropertyName>`. Is it possible using current version of entity framework (EF 6 alpha 3)?
2013/03/23
[ "https://Stackoverflow.com/questions/15590977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1091308/" ]
Not sure if I understand what you are going for... but would using :after work? ``` .card { position: relative; } .card:after { content: ""; display: block; position: absolute; left: 0; right: 0; top: 0; bottom: 0; background: black; } .card:hover:after { display: none; } ``` Example: <http://jsfiddle.net/29TCZ/> You could replace :hover with a class and toggle it as required.
firstly, you cannot change div's `background-color`, without changing its CSS `background-color` property. How could you? Guessing what you want is to maintain last background-color (for some action or to swap it back), then save it in some hidden input variables. And then, you can use it to display anywhere you want. Also, if you want to grab the `background-color` property and show it `as a text` on the div, you can do that very easily. ``` var color = $('#selector').css('backgroundColor'); ``` , but it will return you RGB value. if you want hex, use this handy methods: ``` var hexDigits = new Array ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); //Function to convert hex format to a rgb color function rgb2hex(rgb) { rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } function hex(x) { return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; } ``` taken from [here](https://stackoverflow.com/questions/1740700/get-hex-value-rather-than-rgb-value-using-jquery) Update, ======= currently your `divs` are like this: ``` <div id="a1" class="card"></div> <div id="a2" class="card"></div> <div id="a3" class="card"></div> .. .. ``` and since you want to assign a secret color to each of these divs update them through javascript, inside your while loop, to make them like this: ``` <div id="a1" class="card" data-color-index="1"></div> <div id="a2" class="card" data-color-index="2"></div> <div id="a3" class="card" data-color-index="3"></div> ``` now, you when you click on a particular div, grab its index and choose that item from the `colors` array of yours. since, you are `splicing` your original array, i had to make a copy of it, to use it later. you can grab any element's attribute `data-color-index` through jquery like this: ``` $('#selector').data('color-index'); ``` see this [fiddle](http://jsfiddle.net/manishmishra121/WJQkA/7/). it does what you want to do
15,590,977
I have read [this](http://entityframework.codeplex.com/wikipage?title=Custom%20Conventions) documentation about convention in Entity Framework 6. But it does not contain convention for Relationship. Suppose I have following model: ``` [TablePrefix("mst")] public class Guru { public int Id { get; set; } public int? IdKotaLahir { get; set; } public virtual Kota KotaLahir { get; set; } } ``` I want property `IdKotaLahir` to be foreign key of navigation property `KotaLahir`. Foreign key name is `"Id"+<NavigationPropertyName>`. Is it possible using current version of entity framework (EF 6 alpha 3)?
2013/03/23
[ "https://Stackoverflow.com/questions/15590977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1091308/" ]
Not sure if I understand what you are going for... but would using :after work? ``` .card { position: relative; } .card:after { content: ""; display: block; position: absolute; left: 0; right: 0; top: 0; bottom: 0; background: black; } .card:hover:after { display: none; } ``` Example: <http://jsfiddle.net/29TCZ/> You could replace :hover with a class and toggle it as required.
As Manish said, you cannot change the appearance of the div without changing the CSS property - but there are several hacky ways of doing the same thing. One example is to create a child div in each of the coloured squares that covers the entire area and then set the colour of that div to grey. You can then use the CSS display property to show and hide the overlay divs. However, I would recommend having a copy of the colours in JavaScript and just referring to the value associated with each square when it is clicked instead of checking the DOM every time as this keeps the logic separate from the appearance :)
51,282
I am using the `subfig` package for including subfigures into my thesis. That alone has been going without problem. However, as soon as I use the `\ContinuedFloat` command in order to split a figure over a single page, the following figure, which also uses the `\ContinuedFloat` command, just carries on with the subfigure numbering (e.g. Figure 2c, 2d instead of 2a, 2b). If a figure *without* the `\ContinuedFloat` command is inserted it also continues the numbering (e.g. 3f) and only the next figure without this command starts with the normal labelling (e.g. 4a). This is a minimal working example. ``` \documentclass[12pt,twoside,a4paper]{report} \usepackage{setspace} \usepackage[inner=3cm, outer=3cm, top=1.0in, bottom=1.0in]{geometry} % \geometry{bindingoffset=0.5cm} \usepackage{graphicx} \usepackage[]{subfig} \usepackage{float} \usepackage[font=small,labelfont=bf]{caption} \begin{document} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=14cm]{...figue code...}} \caption[]{figure1}\label{figure1} \end{figure} \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=12cm]{...figue code...}} \caption[figure1]{figure1} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=14cm]{...figue code...}}\\ \subfloat[]{\includegraphics[width=10cm]{...figue code...}}\\ \caption{[]figure2}\label{figure2} \end{figure} \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure3]{figure3} \label{figure3} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure3]{figure3} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure4]{figure4}\label{figure4} \end{figure} \end{document} ```
2012/04/09
[ "https://tex.stackexchange.com/questions/51282", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/13419/" ]
This question has been cross-posted to [LaTeX-Community.org](http://latex-community.org/) and there's a possible [solution](http://latex-community.org/forum/viewtopic.php?f=45&t=19752). The effect is caused by using the `float` package and the `H` option. Removing H and using `!htbp` instead (or less) fixed it for me.
Try to add `\setcounter{subfigure}{0}` in place where you want to reset the counter of subfig. In your case: ``` \documentclass[12pt,twoside,a4paper]{report} (...) \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=12cm]{...figue code...}} \caption[figure1]{figure1} \end{figure} \begin{figure}[H] \centering \setcounter{subfigure}{0} \subfloat[]{\includegraphics[width=14cm]{...figue code...}}\\ \subfloat[]{\includegraphics[width=10cm]{...figue code...}}\\ \caption{[]figure2}\label{figure2} \end{figure} (...) \end{document} ```
51,282
I am using the `subfig` package for including subfigures into my thesis. That alone has been going without problem. However, as soon as I use the `\ContinuedFloat` command in order to split a figure over a single page, the following figure, which also uses the `\ContinuedFloat` command, just carries on with the subfigure numbering (e.g. Figure 2c, 2d instead of 2a, 2b). If a figure *without* the `\ContinuedFloat` command is inserted it also continues the numbering (e.g. 3f) and only the next figure without this command starts with the normal labelling (e.g. 4a). This is a minimal working example. ``` \documentclass[12pt,twoside,a4paper]{report} \usepackage{setspace} \usepackage[inner=3cm, outer=3cm, top=1.0in, bottom=1.0in]{geometry} % \geometry{bindingoffset=0.5cm} \usepackage{graphicx} \usepackage[]{subfig} \usepackage{float} \usepackage[font=small,labelfont=bf]{caption} \begin{document} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=14cm]{...figue code...}} \caption[]{figure1}\label{figure1} \end{figure} \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=12cm]{...figue code...}} \caption[figure1]{figure1} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=14cm]{...figue code...}}\\ \subfloat[]{\includegraphics[width=10cm]{...figue code...}}\\ \caption{[]figure2}\label{figure2} \end{figure} \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure3]{figure3} \label{figure3} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure3]{figure3} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure4]{figure4}\label{figure4} \end{figure} \end{document} ```
2012/04/09
[ "https://tex.stackexchange.com/questions/51282", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/13419/" ]
This question has been cross-posted to [LaTeX-Community.org](http://latex-community.org/) and there's a possible [solution](http://latex-community.org/forum/viewtopic.php?f=45&t=19752). The effect is caused by using the `float` package and the `H` option. Removing H and using `!htbp` instead (or less) fixed it for me.
I have used `\setcounter{subfigure}{number_initial}` or `\setcounter{figure}{number_initial}` and I have solved my problems. The new problem in this case is that you need to know the number or your figure/subfigure, but if you edit the text where your figures are located, this is a good option.
51,282
I am using the `subfig` package for including subfigures into my thesis. That alone has been going without problem. However, as soon as I use the `\ContinuedFloat` command in order to split a figure over a single page, the following figure, which also uses the `\ContinuedFloat` command, just carries on with the subfigure numbering (e.g. Figure 2c, 2d instead of 2a, 2b). If a figure *without* the `\ContinuedFloat` command is inserted it also continues the numbering (e.g. 3f) and only the next figure without this command starts with the normal labelling (e.g. 4a). This is a minimal working example. ``` \documentclass[12pt,twoside,a4paper]{report} \usepackage{setspace} \usepackage[inner=3cm, outer=3cm, top=1.0in, bottom=1.0in]{geometry} % \geometry{bindingoffset=0.5cm} \usepackage{graphicx} \usepackage[]{subfig} \usepackage{float} \usepackage[font=small,labelfont=bf]{caption} \begin{document} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=14cm]{...figue code...}} \caption[]{figure1}\label{figure1} \end{figure} \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=12cm]{...figue code...}} \caption[figure1]{figure1} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=14cm]{...figue code...}}\\ \subfloat[]{\includegraphics[width=10cm]{...figue code...}}\\ \caption{[]figure2}\label{figure2} \end{figure} \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure3]{figure3} \label{figure3} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure3]{figure3} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure4]{figure4}\label{figure4} \end{figure} \end{document} ```
2012/04/09
[ "https://tex.stackexchange.com/questions/51282", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/13419/" ]
The problem seems to go away if you don't use the `[H]` position specifier (you should also load `caption` before `subfig`). If you really must use `[H]`, you can put this in your preamble and use `\resetsubfigs` after `\begin{figure}` to reset the subfigure labels. ``` \makeatletter \newcommand\resetsubfigs{\setcounter{sub\@captype}{0}} \makeatother ``` A fully automated solution may require a lot of hacking.
Try to add `\setcounter{subfigure}{0}` in place where you want to reset the counter of subfig. In your case: ``` \documentclass[12pt,twoside,a4paper]{report} (...) \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=12cm]{...figue code...}} \caption[figure1]{figure1} \end{figure} \begin{figure}[H] \centering \setcounter{subfigure}{0} \subfloat[]{\includegraphics[width=14cm]{...figue code...}}\\ \subfloat[]{\includegraphics[width=10cm]{...figue code...}}\\ \caption{[]figure2}\label{figure2} \end{figure} (...) \end{document} ```
51,282
I am using the `subfig` package for including subfigures into my thesis. That alone has been going without problem. However, as soon as I use the `\ContinuedFloat` command in order to split a figure over a single page, the following figure, which also uses the `\ContinuedFloat` command, just carries on with the subfigure numbering (e.g. Figure 2c, 2d instead of 2a, 2b). If a figure *without* the `\ContinuedFloat` command is inserted it also continues the numbering (e.g. 3f) and only the next figure without this command starts with the normal labelling (e.g. 4a). This is a minimal working example. ``` \documentclass[12pt,twoside,a4paper]{report} \usepackage{setspace} \usepackage[inner=3cm, outer=3cm, top=1.0in, bottom=1.0in]{geometry} % \geometry{bindingoffset=0.5cm} \usepackage{graphicx} \usepackage[]{subfig} \usepackage{float} \usepackage[font=small,labelfont=bf]{caption} \begin{document} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=14cm]{...figue code...}} \caption[]{figure1}\label{figure1} \end{figure} \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=12cm]{...figue code...}} \caption[figure1]{figure1} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=14cm]{...figue code...}}\\ \subfloat[]{\includegraphics[width=10cm]{...figue code...}}\\ \caption{[]figure2}\label{figure2} \end{figure} \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure3]{figure3} \label{figure3} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure3]{figure3} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure4]{figure4}\label{figure4} \end{figure} \end{document} ```
2012/04/09
[ "https://tex.stackexchange.com/questions/51282", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/13419/" ]
The problem seems to go away if you don't use the `[H]` position specifier (you should also load `caption` before `subfig`). If you really must use `[H]`, you can put this in your preamble and use `\resetsubfigs` after `\begin{figure}` to reset the subfigure labels. ``` \makeatletter \newcommand\resetsubfigs{\setcounter{sub\@captype}{0}} \makeatother ``` A fully automated solution may require a lot of hacking.
I have used `\setcounter{subfigure}{number_initial}` or `\setcounter{figure}{number_initial}` and I have solved my problems. The new problem in this case is that you need to know the number or your figure/subfigure, but if you edit the text where your figures are located, this is a good option.
51,282
I am using the `subfig` package for including subfigures into my thesis. That alone has been going without problem. However, as soon as I use the `\ContinuedFloat` command in order to split a figure over a single page, the following figure, which also uses the `\ContinuedFloat` command, just carries on with the subfigure numbering (e.g. Figure 2c, 2d instead of 2a, 2b). If a figure *without* the `\ContinuedFloat` command is inserted it also continues the numbering (e.g. 3f) and only the next figure without this command starts with the normal labelling (e.g. 4a). This is a minimal working example. ``` \documentclass[12pt,twoside,a4paper]{report} \usepackage{setspace} \usepackage[inner=3cm, outer=3cm, top=1.0in, bottom=1.0in]{geometry} % \geometry{bindingoffset=0.5cm} \usepackage{graphicx} \usepackage[]{subfig} \usepackage{float} \usepackage[font=small,labelfont=bf]{caption} \begin{document} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=14cm]{...figue code...}} \caption[]{figure1}\label{figure1} \end{figure} \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=12cm]{...figue code...}} \caption[figure1]{figure1} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=14cm]{...figue code...}}\\ \subfloat[]{\includegraphics[width=10cm]{...figue code...}}\\ \caption{[]figure2}\label{figure2} \end{figure} \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure3]{figure3} \label{figure3} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure3]{figure3} \end{figure} \begin{figure}[H] \centering \subfloat[]{\includegraphics[width=10cm]{...figue code...}} \caption[figure4]{figure4}\label{figure4} \end{figure} \end{document} ```
2012/04/09
[ "https://tex.stackexchange.com/questions/51282", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/13419/" ]
I have used `\setcounter{subfigure}{number_initial}` or `\setcounter{figure}{number_initial}` and I have solved my problems. The new problem in this case is that you need to know the number or your figure/subfigure, but if you edit the text where your figures are located, this is a good option.
Try to add `\setcounter{subfigure}{0}` in place where you want to reset the counter of subfig. In your case: ``` \documentclass[12pt,twoside,a4paper]{report} (...) \begin{figure}[H] \ContinuedFloat \centering \subfloat[]{\includegraphics[width=12cm]{...figue code...}} \caption[figure1]{figure1} \end{figure} \begin{figure}[H] \centering \setcounter{subfigure}{0} \subfloat[]{\includegraphics[width=14cm]{...figue code...}}\\ \subfloat[]{\includegraphics[width=10cm]{...figue code...}}\\ \caption{[]figure2}\label{figure2} \end{figure} (...) \end{document} ```
2,682,259
**UPDATE** I have reverted back to Jquery 1.3.2 and everything is working, not sure what the problem is/was as I have not changed anything else apart of the jquery and ui library versions. **UPDATE END** I having an issue with the [JQuery UI datepicker](http://jqueryui.com/demos/datepicker/). The datepicker is being attached to a class and that part is working but the datepicker is not being displayed. Here is the datepicker code I am using and the inline style that is being generated when I click in the input box that has the class ".datepicker". ``` $('.datepicker').datepicker({dateFormat:'dd/mm/yy'}); display:none; left:418px; position:absolute; top:296px; z-index:1; ``` If I change the display:none to display:block the datepicker works fine except it dosen't close when I select a date. Jquery libraries in use: * jQuery JavaScript Library v1.4.2 * jQuery UI 1.8 jQuery UI Widget 1.8 * jQuery UI Mouse 1.8 jQuery UI * Position 1.8 jQuery UI Draggable 1.8 * jQuery UI Droppable 1.8 jQuery UI * Datepicker 1.8
2010/04/21
[ "https://Stackoverflow.com/questions/2682259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322194/" ]
I had the same issue: the Date Picker was added successfully (and could even be found in FireBug), but was not visible. If you use FireBug to remove the class "ui-helper-hidden-accessible" from the Date Picker div (ID of: "ui-datepicker-div"), the Date Picker becomes visible and will work like normal. If you add the following at the very end of your $(document).ready() function, it will apply this to every Date Picker on you page, and make them all work: ``` $(document).ready(function() { //... //Put all of you other page setup code here //... //after setting everything up (including adding all Date Pickers) //apply this code to every Date Picker $('#ui-datepicker-div').removeClass('ui-helper-hidden-accessible'); }); ``` That was my initial fix. Afterwards, I tried the solution suggested above by Brian Mortenson and it both worked perfectly, and seemed less invasive than removing an entire class from the element. So I modified my code to apply his solution to the method I used (apply at the end of the document setup so that it applies to every Date Picker and does not require repeating): ``` $(document).ready(function() { //... //Put all of you other page setup code here //... //after setting everything up (including adding all Date Pickers) //apply this code to every Date Picker $('#ui-datepicker-div').css('clip', 'auto'); }); ``` Hope this helps to get someone unstuck. EDIT: Fixed a code syntax error.
Just posting because the root cause for my case has not been described her. In my case the problem was that "assets/js/fuelux/treeview/fuelux.min.js" was adding a constructor .datepicker(), so that was overriding the assets/js/datetime/bootstrap-datepicker.js just moving the to be just before the $('.date-picker') solved my problem.
2,682,259
**UPDATE** I have reverted back to Jquery 1.3.2 and everything is working, not sure what the problem is/was as I have not changed anything else apart of the jquery and ui library versions. **UPDATE END** I having an issue with the [JQuery UI datepicker](http://jqueryui.com/demos/datepicker/). The datepicker is being attached to a class and that part is working but the datepicker is not being displayed. Here is the datepicker code I am using and the inline style that is being generated when I click in the input box that has the class ".datepicker". ``` $('.datepicker').datepicker({dateFormat:'dd/mm/yy'}); display:none; left:418px; position:absolute; top:296px; z-index:1; ``` If I change the display:none to display:block the datepicker works fine except it dosen't close when I select a date. Jquery libraries in use: * jQuery JavaScript Library v1.4.2 * jQuery UI 1.8 jQuery UI Widget 1.8 * jQuery UI Mouse 1.8 jQuery UI * Position 1.8 jQuery UI Draggable 1.8 * jQuery UI Droppable 1.8 jQuery UI * Datepicker 1.8
2010/04/21
[ "https://Stackoverflow.com/questions/2682259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322194/" ]
Had the same problem that the datepicker-DIV has been created but didnt get filled and show up on click. My fault was to give the input the class "hasDatepicker" staticly. jQuery-ui hat to set this class by its own. then it works for me.
Had the same problem while working with bootstrap modal. I had accidentally set the z-index for `.ui-datepicker` using `!important` which overrides the date picker z-index css attribute on the element. Removing `!important` worked.
2,682,259
**UPDATE** I have reverted back to Jquery 1.3.2 and everything is working, not sure what the problem is/was as I have not changed anything else apart of the jquery and ui library versions. **UPDATE END** I having an issue with the [JQuery UI datepicker](http://jqueryui.com/demos/datepicker/). The datepicker is being attached to a class and that part is working but the datepicker is not being displayed. Here is the datepicker code I am using and the inline style that is being generated when I click in the input box that has the class ".datepicker". ``` $('.datepicker').datepicker({dateFormat:'dd/mm/yy'}); display:none; left:418px; position:absolute; top:296px; z-index:1; ``` If I change the display:none to display:block the datepicker works fine except it dosen't close when I select a date. Jquery libraries in use: * jQuery JavaScript Library v1.4.2 * jQuery UI 1.8 jQuery UI Widget 1.8 * jQuery UI Mouse 1.8 jQuery UI * Position 1.8 jQuery UI Draggable 1.8 * jQuery UI Droppable 1.8 jQuery UI * Datepicker 1.8
2010/04/21
[ "https://Stackoverflow.com/questions/2682259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322194/" ]
Try putting the z-index of your datepicker css a lot higher (eg z-index: 1000). The datepicker is probably shown under your original content. I had the same problem and this helped me out.
In case you are having this issue when working with WordPress control panel and using a ThemeRoller generated theme - be sure that you are using 1.7.3 Version of theme, 1.8.13 will not work. (If you look closely, the element is being rendered, but .ui-helper-hidden-accessible is causing it to not be displayed. Current WP Version: 3.1.3
2,682,259
**UPDATE** I have reverted back to Jquery 1.3.2 and everything is working, not sure what the problem is/was as I have not changed anything else apart of the jquery and ui library versions. **UPDATE END** I having an issue with the [JQuery UI datepicker](http://jqueryui.com/demos/datepicker/). The datepicker is being attached to a class and that part is working but the datepicker is not being displayed. Here is the datepicker code I am using and the inline style that is being generated when I click in the input box that has the class ".datepicker". ``` $('.datepicker').datepicker({dateFormat:'dd/mm/yy'}); display:none; left:418px; position:absolute; top:296px; z-index:1; ``` If I change the display:none to display:block the datepicker works fine except it dosen't close when I select a date. Jquery libraries in use: * jQuery JavaScript Library v1.4.2 * jQuery UI 1.8 jQuery UI Widget 1.8 * jQuery UI Mouse 1.8 jQuery UI * Position 1.8 jQuery UI Draggable 1.8 * jQuery UI Droppable 1.8 jQuery UI * Datepicker 1.8
2010/04/21
[ "https://Stackoverflow.com/questions/2682259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322194/" ]
Had the same problem that the datepicker-DIV has been created but didnt get filled and show up on click. My fault was to give the input the class "hasDatepicker" staticly. jQuery-ui hat to set this class by its own. then it works for me.
In case you are having this issue when working with WordPress control panel and using a ThemeRoller generated theme - be sure that you are using 1.7.3 Version of theme, 1.8.13 will not work. (If you look closely, the element is being rendered, but .ui-helper-hidden-accessible is causing it to not be displayed. Current WP Version: 3.1.3
2,682,259
**UPDATE** I have reverted back to Jquery 1.3.2 and everything is working, not sure what the problem is/was as I have not changed anything else apart of the jquery and ui library versions. **UPDATE END** I having an issue with the [JQuery UI datepicker](http://jqueryui.com/demos/datepicker/). The datepicker is being attached to a class and that part is working but the datepicker is not being displayed. Here is the datepicker code I am using and the inline style that is being generated when I click in the input box that has the class ".datepicker". ``` $('.datepicker').datepicker({dateFormat:'dd/mm/yy'}); display:none; left:418px; position:absolute; top:296px; z-index:1; ``` If I change the display:none to display:block the datepicker works fine except it dosen't close when I select a date. Jquery libraries in use: * jQuery JavaScript Library v1.4.2 * jQuery UI 1.8 jQuery UI Widget 1.8 * jQuery UI Mouse 1.8 jQuery UI * Position 1.8 jQuery UI Draggable 1.8 * jQuery UI Droppable 1.8 jQuery UI * Datepicker 1.8
2010/04/21
[ "https://Stackoverflow.com/questions/2682259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322194/" ]
I was having the same problem, and I found that in my case the cause was the datepicker div for some reason is retaining the class .ui-helper-hidden-accessible, which has the following CSS: ``` .ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); } ``` I'm using the google CDN hosted versions of jquery, so I couldn't modify the code or the CSS. I had also tried changing the z-index without any success. The solution that worked for me was to set the clip property for the datepicker back to its default value, auto: ``` $('.date').datepicker(); $('#ui-datepicker-div').css('clip', 'auto'); ``` Since this specifically targets the datepicker div, there's less of a chance of unintended side effects on other widgets than changing the ui-helper-hidden-accessible class as a whole.
I had the same issue: the Date Picker was added successfully (and could even be found in FireBug), but was not visible. If you use FireBug to remove the class "ui-helper-hidden-accessible" from the Date Picker div (ID of: "ui-datepicker-div"), the Date Picker becomes visible and will work like normal. If you add the following at the very end of your $(document).ready() function, it will apply this to every Date Picker on you page, and make them all work: ``` $(document).ready(function() { //... //Put all of you other page setup code here //... //after setting everything up (including adding all Date Pickers) //apply this code to every Date Picker $('#ui-datepicker-div').removeClass('ui-helper-hidden-accessible'); }); ``` That was my initial fix. Afterwards, I tried the solution suggested above by Brian Mortenson and it both worked perfectly, and seemed less invasive than removing an entire class from the element. So I modified my code to apply his solution to the method I used (apply at the end of the document setup so that it applies to every Date Picker and does not require repeating): ``` $(document).ready(function() { //... //Put all of you other page setup code here //... //after setting everything up (including adding all Date Pickers) //apply this code to every Date Picker $('#ui-datepicker-div').css('clip', 'auto'); }); ``` Hope this helps to get someone unstuck. EDIT: Fixed a code syntax error.
2,682,259
**UPDATE** I have reverted back to Jquery 1.3.2 and everything is working, not sure what the problem is/was as I have not changed anything else apart of the jquery and ui library versions. **UPDATE END** I having an issue with the [JQuery UI datepicker](http://jqueryui.com/demos/datepicker/). The datepicker is being attached to a class and that part is working but the datepicker is not being displayed. Here is the datepicker code I am using and the inline style that is being generated when I click in the input box that has the class ".datepicker". ``` $('.datepicker').datepicker({dateFormat:'dd/mm/yy'}); display:none; left:418px; position:absolute; top:296px; z-index:1; ``` If I change the display:none to display:block the datepicker works fine except it dosen't close when I select a date. Jquery libraries in use: * jQuery JavaScript Library v1.4.2 * jQuery UI 1.8 jQuery UI Widget 1.8 * jQuery UI Mouse 1.8 jQuery UI * Position 1.8 jQuery UI Draggable 1.8 * jQuery UI Droppable 1.8 jQuery UI * Datepicker 1.8
2010/04/21
[ "https://Stackoverflow.com/questions/2682259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322194/" ]
it's the css file in the new one doesn't work. Try to include the old 1.7.\* css file on your header too, and try again. Also, did you try to do a .datepicker( "show" ) right after it constructed?
I had the same issue: the Date Picker was added successfully (and could even be found in FireBug), but was not visible. If you use FireBug to remove the class "ui-helper-hidden-accessible" from the Date Picker div (ID of: "ui-datepicker-div"), the Date Picker becomes visible and will work like normal. If you add the following at the very end of your $(document).ready() function, it will apply this to every Date Picker on you page, and make them all work: ``` $(document).ready(function() { //... //Put all of you other page setup code here //... //after setting everything up (including adding all Date Pickers) //apply this code to every Date Picker $('#ui-datepicker-div').removeClass('ui-helper-hidden-accessible'); }); ``` That was my initial fix. Afterwards, I tried the solution suggested above by Brian Mortenson and it both worked perfectly, and seemed less invasive than removing an entire class from the element. So I modified my code to apply his solution to the method I used (apply at the end of the document setup so that it applies to every Date Picker and does not require repeating): ``` $(document).ready(function() { //... //Put all of you other page setup code here //... //after setting everything up (including adding all Date Pickers) //apply this code to every Date Picker $('#ui-datepicker-div').css('clip', 'auto'); }); ``` Hope this helps to get someone unstuck. EDIT: Fixed a code syntax error.
2,682,259
**UPDATE** I have reverted back to Jquery 1.3.2 and everything is working, not sure what the problem is/was as I have not changed anything else apart of the jquery and ui library versions. **UPDATE END** I having an issue with the [JQuery UI datepicker](http://jqueryui.com/demos/datepicker/). The datepicker is being attached to a class and that part is working but the datepicker is not being displayed. Here is the datepicker code I am using and the inline style that is being generated when I click in the input box that has the class ".datepicker". ``` $('.datepicker').datepicker({dateFormat:'dd/mm/yy'}); display:none; left:418px; position:absolute; top:296px; z-index:1; ``` If I change the display:none to display:block the datepicker works fine except it dosen't close when I select a date. Jquery libraries in use: * jQuery JavaScript Library v1.4.2 * jQuery UI 1.8 jQuery UI Widget 1.8 * jQuery UI Mouse 1.8 jQuery UI * Position 1.8 jQuery UI Draggable 1.8 * jQuery UI Droppable 1.8 jQuery UI * Datepicker 1.8
2010/04/21
[ "https://Stackoverflow.com/questions/2682259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322194/" ]
I've had a similar issue with 1.7.2 versions of jQuery and jQuery UI. The popup wasn't showing up and none of the applicable suggestions above helped. What helped in my case was taking out the class="hasDatepicker" which (as the accepted answer here notes: [jQuery UI datepicker will not display - full code included](https://stackoverflow.com/questions/2820867/jquery-ui-datepicker-will-not-display-full-code-included)) is used by jquery-ui to indicate that a datepicker has already been added to the text field. Wish I found that answer sooner.
Here is the full code, it's working from my side: just test. ``` <!doctype html> <html lang="en"> <head> <title>jQuery Datepicker</title> <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <script> $(function() { $( "#datepicker1" ).datepicker(); }); </script> </head> <body> <p>Enter Date: <input type="text" id="datepicker1"></p> </body> </html> ```
2,682,259
**UPDATE** I have reverted back to Jquery 1.3.2 and everything is working, not sure what the problem is/was as I have not changed anything else apart of the jquery and ui library versions. **UPDATE END** I having an issue with the [JQuery UI datepicker](http://jqueryui.com/demos/datepicker/). The datepicker is being attached to a class and that part is working but the datepicker is not being displayed. Here is the datepicker code I am using and the inline style that is being generated when I click in the input box that has the class ".datepicker". ``` $('.datepicker').datepicker({dateFormat:'dd/mm/yy'}); display:none; left:418px; position:absolute; top:296px; z-index:1; ``` If I change the display:none to display:block the datepicker works fine except it dosen't close when I select a date. Jquery libraries in use: * jQuery JavaScript Library v1.4.2 * jQuery UI 1.8 jQuery UI Widget 1.8 * jQuery UI Mouse 1.8 jQuery UI * Position 1.8 jQuery UI Draggable 1.8 * jQuery UI Droppable 1.8 jQuery UI * Datepicker 1.8
2010/04/21
[ "https://Stackoverflow.com/questions/2682259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322194/" ]
I had the same problem using JQuery-UI 1.8.21, and JQuery-UI 1.8.22. Problem was because I had two DatePicker script, one embedded with *jquery-ui-1.8.22.custom.min.js* and another one in *jquery.ui.datepicker.js* (an old version before I upgrade to 1.8.21). Deleting the **duplicate** *jquery.ui.datepicker.js*, resolve problem for both 1.8.21 and 1.8.22.
``` * html .ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); } ``` This just works for IE, so I apply this hack and works fine on FF, Safari and others.
2,682,259
**UPDATE** I have reverted back to Jquery 1.3.2 and everything is working, not sure what the problem is/was as I have not changed anything else apart of the jquery and ui library versions. **UPDATE END** I having an issue with the [JQuery UI datepicker](http://jqueryui.com/demos/datepicker/). The datepicker is being attached to a class and that part is working but the datepicker is not being displayed. Here is the datepicker code I am using and the inline style that is being generated when I click in the input box that has the class ".datepicker". ``` $('.datepicker').datepicker({dateFormat:'dd/mm/yy'}); display:none; left:418px; position:absolute; top:296px; z-index:1; ``` If I change the display:none to display:block the datepicker works fine except it dosen't close when I select a date. Jquery libraries in use: * jQuery JavaScript Library v1.4.2 * jQuery UI 1.8 jQuery UI Widget 1.8 * jQuery UI Mouse 1.8 jQuery UI * Position 1.8 jQuery UI Draggable 1.8 * jQuery UI Droppable 1.8 jQuery UI * Datepicker 1.8
2010/04/21
[ "https://Stackoverflow.com/questions/2682259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322194/" ]
Had the same problem that the datepicker-DIV has been created but didnt get filled and show up on click. My fault was to give the input the class "hasDatepicker" staticly. jQuery-ui hat to set this class by its own. then it works for me.
Seems to happen with some themes (cupertino/theme.css) in my case. And the problem is the .ui-helper-hidden-accessible class which have clip property, like previous users said. Just Overwrite it and it will be fine ``` $(document).ready(function() { $("#datePicker").datepicker({ dateFormat: "yy-m-d" }); $('#ui-datepicker-div').css('clip', 'auto'); }); ```
2,682,259
**UPDATE** I have reverted back to Jquery 1.3.2 and everything is working, not sure what the problem is/was as I have not changed anything else apart of the jquery and ui library versions. **UPDATE END** I having an issue with the [JQuery UI datepicker](http://jqueryui.com/demos/datepicker/). The datepicker is being attached to a class and that part is working but the datepicker is not being displayed. Here is the datepicker code I am using and the inline style that is being generated when I click in the input box that has the class ".datepicker". ``` $('.datepicker').datepicker({dateFormat:'dd/mm/yy'}); display:none; left:418px; position:absolute; top:296px; z-index:1; ``` If I change the display:none to display:block the datepicker works fine except it dosen't close when I select a date. Jquery libraries in use: * jQuery JavaScript Library v1.4.2 * jQuery UI 1.8 jQuery UI Widget 1.8 * jQuery UI Mouse 1.8 jQuery UI * Position 1.8 jQuery UI Draggable 1.8 * jQuery UI Droppable 1.8 jQuery UI * Datepicker 1.8
2010/04/21
[ "https://Stackoverflow.com/questions/2682259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322194/" ]
I've had a similar issue with 1.7.2 versions of jQuery and jQuery UI. The popup wasn't showing up and none of the applicable suggestions above helped. What helped in my case was taking out the class="hasDatepicker" which (as the accepted answer here notes: [jQuery UI datepicker will not display - full code included](https://stackoverflow.com/questions/2820867/jquery-ui-datepicker-will-not-display-full-code-included)) is used by jquery-ui to indicate that a datepicker has already been added to the text field. Wish I found that answer sooner.
Seems to happen with some themes (cupertino/theme.css) in my case. And the problem is the .ui-helper-hidden-accessible class which have clip property, like previous users said. Just Overwrite it and it will be fine ``` $(document).ready(function() { $("#datePicker").datepicker({ dateFormat: "yy-m-d" }); $('#ui-datepicker-div').css('clip', 'auto'); }); ```
4,949,338
Is there any way to put a non printing or non obtrusive character at the beginning of a string of data in sqlserver. so that when an **order by** is performed, the string is sorted after the letter z alphabetically? I have used a space at the beginning of the string to get the string at the top of the sorted list, but I am looking to do something similar to put a string at the end of the list. I would rather not put another field such as "SortOrder" in the table to use to order the sort, and I would rather not have to sort the list in my code. Added: Yes I know this is a bad idea, thanks to all for mentioning it, but still, I am curious if what I am asking can be done
2011/02/09
[ "https://Stackoverflow.com/questions/4949338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105407/" ]
Since no one is venturing to answer your question properly, here's my answer **Given:** You are already adding `<space>` to some other data to make them appear top **Solution:** Add CHAR(160) to make it appear at the bottom. This is in reality also a space, but is designed for computer systems to not treat it as a word break (hence the name). <http://en.wikipedia.org/wiki/Non-breaking_space> Your requirements: 1. Without adding another field such as "SortOrder" to the table 2. Without sorting the list in your code I think this fits! ``` create table my(id int,data varchar(100)) insert my select 1,'Banana' union all select 2,Char(160) + 'mustappearlast' union all select 3,' ' +N'mustappearfirst' union all select 4,'apple' union all select 5,'pear' select * from my order by ASCII(lower(data)), data ``` (ok I cheated, I had to add `ASCII(lower(` but this is closest to your requirements than all the other answers so far)
Could you you include something like: ``` "<SORT1>This is my string" "<SORT2>I'd like this to go second" ``` And remove them later? I think using invisible characters is fragile and hacky.
4,949,338
Is there any way to put a non printing or non obtrusive character at the beginning of a string of data in sqlserver. so that when an **order by** is performed, the string is sorted after the letter z alphabetically? I have used a space at the beginning of the string to get the string at the top of the sorted list, but I am looking to do something similar to put a string at the end of the list. I would rather not put another field such as "SortOrder" in the table to use to order the sort, and I would rather not have to sort the list in my code. Added: Yes I know this is a bad idea, thanks to all for mentioning it, but still, I am curious if what I am asking can be done
2011/02/09
[ "https://Stackoverflow.com/questions/4949338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105407/" ]
Since no one is venturing to answer your question properly, here's my answer **Given:** You are already adding `<space>` to some other data to make them appear top **Solution:** Add CHAR(160) to make it appear at the bottom. This is in reality also a space, but is designed for computer systems to not treat it as a word break (hence the name). <http://en.wikipedia.org/wiki/Non-breaking_space> Your requirements: 1. Without adding another field such as "SortOrder" to the table 2. Without sorting the list in your code I think this fits! ``` create table my(id int,data varchar(100)) insert my select 1,'Banana' union all select 2,Char(160) + 'mustappearlast' union all select 3,' ' +N'mustappearfirst' union all select 4,'apple' union all select 5,'pear' select * from my order by ASCII(lower(data)), data ``` (ok I cheated, I had to add `ASCII(lower(` but this is closest to your requirements than all the other answers so far)
You could put a sort order in the query and use unions (no guarantees on performance). ``` select 1 as SortOrder, * from table where ... --first tier union select 2, * from table where ... --second tier order by SortOrder ```
4,949,338
Is there any way to put a non printing or non obtrusive character at the beginning of a string of data in sqlserver. so that when an **order by** is performed, the string is sorted after the letter z alphabetically? I have used a space at the beginning of the string to get the string at the top of the sorted list, but I am looking to do something similar to put a string at the end of the list. I would rather not put another field such as "SortOrder" in the table to use to order the sort, and I would rather not have to sort the list in my code. Added: Yes I know this is a bad idea, thanks to all for mentioning it, but still, I am curious if what I am asking can be done
2011/02/09
[ "https://Stackoverflow.com/questions/4949338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105407/" ]
Since no one is venturing to answer your question properly, here's my answer **Given:** You are already adding `<space>` to some other data to make them appear top **Solution:** Add CHAR(160) to make it appear at the bottom. This is in reality also a space, but is designed for computer systems to not treat it as a word break (hence the name). <http://en.wikipedia.org/wiki/Non-breaking_space> Your requirements: 1. Without adding another field such as "SortOrder" to the table 2. Without sorting the list in your code I think this fits! ``` create table my(id int,data varchar(100)) insert my select 1,'Banana' union all select 2,Char(160) + 'mustappearlast' union all select 3,' ' +N'mustappearfirst' union all select 4,'apple' union all select 5,'pear' select * from my order by ASCII(lower(data)), data ``` (ok I cheated, I had to add `ASCII(lower(` but this is closest to your requirements than all the other answers so far)
I'm with everyone else that the ideal way to do this is by adding an additional column for sort order. But if you don't want to add another column, and you already use a space for those items you want to appear at the top of the list, how do you feel about using a pipe (|) for items at the bottom of the list? [By default](http://msdn.microsoft.com/en-us/library/aa933426(v=sql.80).aspx), SQL Server uses a Unicode character set for its sorting. In [Unicode](http://en.wikipedia.org/wiki/List_of_Unicode_characters), the pipe and both curly brackets ({, }) come after z, so any of those three characters should work for you.
4,949,338
Is there any way to put a non printing or non obtrusive character at the beginning of a string of data in sqlserver. so that when an **order by** is performed, the string is sorted after the letter z alphabetically? I have used a space at the beginning of the string to get the string at the top of the sorted list, but I am looking to do something similar to put a string at the end of the list. I would rather not put another field such as "SortOrder" in the table to use to order the sort, and I would rather not have to sort the list in my code. Added: Yes I know this is a bad idea, thanks to all for mentioning it, but still, I am curious if what I am asking can be done
2011/02/09
[ "https://Stackoverflow.com/questions/4949338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105407/" ]
Since no one is venturing to answer your question properly, here's my answer **Given:** You are already adding `<space>` to some other data to make them appear top **Solution:** Add CHAR(160) to make it appear at the bottom. This is in reality also a space, but is designed for computer systems to not treat it as a word break (hence the name). <http://en.wikipedia.org/wiki/Non-breaking_space> Your requirements: 1. Without adding another field such as "SortOrder" to the table 2. Without sorting the list in your code I think this fits! ``` create table my(id int,data varchar(100)) insert my select 1,'Banana' union all select 2,Char(160) + 'mustappearlast' union all select 3,' ' +N'mustappearfirst' union all select 4,'apple' union all select 5,'pear' select * from my order by ASCII(lower(data)), data ``` (ok I cheated, I had to add `ASCII(lower(` but this is closest to your requirements than all the other answers so far)
In my opinion, an invisible character for this purpose is a bad idea because it pollutes the data. I would do exactly what you would rather not do and add a new column. To modify the idea slightly, you could implement it not as a sort order, but a grouping order, defaults to 0, where a negative integer puts the group at top of the list and a positve integer at the bottom, and then "order by sort\_priority, foo"
4,949,338
Is there any way to put a non printing or non obtrusive character at the beginning of a string of data in sqlserver. so that when an **order by** is performed, the string is sorted after the letter z alphabetically? I have used a space at the beginning of the string to get the string at the top of the sorted list, but I am looking to do something similar to put a string at the end of the list. I would rather not put another field such as "SortOrder" in the table to use to order the sort, and I would rather not have to sort the list in my code. Added: Yes I know this is a bad idea, thanks to all for mentioning it, but still, I am curious if what I am asking can be done
2011/02/09
[ "https://Stackoverflow.com/questions/4949338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105407/" ]
Since no one is venturing to answer your question properly, here's my answer **Given:** You are already adding `<space>` to some other data to make them appear top **Solution:** Add CHAR(160) to make it appear at the bottom. This is in reality also a space, but is designed for computer systems to not treat it as a word break (hence the name). <http://en.wikipedia.org/wiki/Non-breaking_space> Your requirements: 1. Without adding another field such as "SortOrder" to the table 2. Without sorting the list in your code I think this fits! ``` create table my(id int,data varchar(100)) insert my select 1,'Banana' union all select 2,Char(160) + 'mustappearlast' union all select 3,' ' +N'mustappearfirst' union all select 4,'apple' union all select 5,'pear' select * from my order by ASCII(lower(data)), data ``` (ok I cheated, I had to add `ASCII(lower(` but this is closest to your requirements than all the other answers so far)
You should use another column in the database to help specify the ordering rather than modifying the string: ``` SELECT * FROM yourtable ORDER BY sortorder, yourstring ``` Where you data might look like this: ``` yourstring sortorder foo 0 bar 0 baz 1 qux 1 quux 2 ``` If you can't modify the table you might be able to put the sortorder column into a different table and join to get it: ``` SELECT * FROM yourtable AS T1 JOIN yourtablesorting AS T2 ON T1.id = T2.T1_id ORDER BY T2.sortorder, T1.yourstring ``` --- Alternative solution: If you really can't modify the database at all, not even adding a new table then you could add any character you like at the start of the string and remove it during the select: ``` SELECT RIGHT(yourstring, LEN(yourstring) - 1) FROM yourtable ORDER BY yourstring ```
4,949,338
Is there any way to put a non printing or non obtrusive character at the beginning of a string of data in sqlserver. so that when an **order by** is performed, the string is sorted after the letter z alphabetically? I have used a space at the beginning of the string to get the string at the top of the sorted list, but I am looking to do something similar to put a string at the end of the list. I would rather not put another field such as "SortOrder" in the table to use to order the sort, and I would rather not have to sort the list in my code. Added: Yes I know this is a bad idea, thanks to all for mentioning it, but still, I am curious if what I am asking can be done
2011/02/09
[ "https://Stackoverflow.com/questions/4949338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105407/" ]
You should use another column in the database to help specify the ordering rather than modifying the string: ``` SELECT * FROM yourtable ORDER BY sortorder, yourstring ``` Where you data might look like this: ``` yourstring sortorder foo 0 bar 0 baz 1 qux 1 quux 2 ``` If you can't modify the table you might be able to put the sortorder column into a different table and join to get it: ``` SELECT * FROM yourtable AS T1 JOIN yourtablesorting AS T2 ON T1.id = T2.T1_id ORDER BY T2.sortorder, T1.yourstring ``` --- Alternative solution: If you really can't modify the database at all, not even adding a new table then you could add any character you like at the start of the string and remove it during the select: ``` SELECT RIGHT(yourstring, LEN(yourstring) - 1) FROM yourtable ORDER BY yourstring ```
Could you you include something like: ``` "<SORT1>This is my string" "<SORT2>I'd like this to go second" ``` And remove them later? I think using invisible characters is fragile and hacky.
4,949,338
Is there any way to put a non printing or non obtrusive character at the beginning of a string of data in sqlserver. so that when an **order by** is performed, the string is sorted after the letter z alphabetically? I have used a space at the beginning of the string to get the string at the top of the sorted list, but I am looking to do something similar to put a string at the end of the list. I would rather not put another field such as "SortOrder" in the table to use to order the sort, and I would rather not have to sort the list in my code. Added: Yes I know this is a bad idea, thanks to all for mentioning it, but still, I am curious if what I am asking can be done
2011/02/09
[ "https://Stackoverflow.com/questions/4949338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105407/" ]
Could you you include something like: ``` "<SORT1>This is my string" "<SORT2>I'd like this to go second" ``` And remove them later? I think using invisible characters is fragile and hacky.
I'm with everyone else that the ideal way to do this is by adding an additional column for sort order. But if you don't want to add another column, and you already use a space for those items you want to appear at the top of the list, how do you feel about using a pipe (|) for items at the bottom of the list? [By default](http://msdn.microsoft.com/en-us/library/aa933426(v=sql.80).aspx), SQL Server uses a Unicode character set for its sorting. In [Unicode](http://en.wikipedia.org/wiki/List_of_Unicode_characters), the pipe and both curly brackets ({, }) come after z, so any of those three characters should work for you.
4,949,338
Is there any way to put a non printing or non obtrusive character at the beginning of a string of data in sqlserver. so that when an **order by** is performed, the string is sorted after the letter z alphabetically? I have used a space at the beginning of the string to get the string at the top of the sorted list, but I am looking to do something similar to put a string at the end of the list. I would rather not put another field such as "SortOrder" in the table to use to order the sort, and I would rather not have to sort the list in my code. Added: Yes I know this is a bad idea, thanks to all for mentioning it, but still, I am curious if what I am asking can be done
2011/02/09
[ "https://Stackoverflow.com/questions/4949338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105407/" ]
You should use another column in the database to help specify the ordering rather than modifying the string: ``` SELECT * FROM yourtable ORDER BY sortorder, yourstring ``` Where you data might look like this: ``` yourstring sortorder foo 0 bar 0 baz 1 qux 1 quux 2 ``` If you can't modify the table you might be able to put the sortorder column into a different table and join to get it: ``` SELECT * FROM yourtable AS T1 JOIN yourtablesorting AS T2 ON T1.id = T2.T1_id ORDER BY T2.sortorder, T1.yourstring ``` --- Alternative solution: If you really can't modify the database at all, not even adding a new table then you could add any character you like at the start of the string and remove it during the select: ``` SELECT RIGHT(yourstring, LEN(yourstring) - 1) FROM yourtable ORDER BY yourstring ```
You could put a sort order in the query and use unions (no guarantees on performance). ``` select 1 as SortOrder, * from table where ... --first tier union select 2, * from table where ... --second tier order by SortOrder ```
4,949,338
Is there any way to put a non printing or non obtrusive character at the beginning of a string of data in sqlserver. so that when an **order by** is performed, the string is sorted after the letter z alphabetically? I have used a space at the beginning of the string to get the string at the top of the sorted list, but I am looking to do something similar to put a string at the end of the list. I would rather not put another field such as "SortOrder" in the table to use to order the sort, and I would rather not have to sort the list in my code. Added: Yes I know this is a bad idea, thanks to all for mentioning it, but still, I am curious if what I am asking can be done
2011/02/09
[ "https://Stackoverflow.com/questions/4949338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105407/" ]
Could you you include something like: ``` "<SORT1>This is my string" "<SORT2>I'd like this to go second" ``` And remove them later? I think using invisible characters is fragile and hacky.
In my opinion, an invisible character for this purpose is a bad idea because it pollutes the data. I would do exactly what you would rather not do and add a new column. To modify the idea slightly, you could implement it not as a sort order, but a grouping order, defaults to 0, where a negative integer puts the group at top of the list and a positve integer at the bottom, and then "order by sort\_priority, foo"
4,949,338
Is there any way to put a non printing or non obtrusive character at the beginning of a string of data in sqlserver. so that when an **order by** is performed, the string is sorted after the letter z alphabetically? I have used a space at the beginning of the string to get the string at the top of the sorted list, but I am looking to do something similar to put a string at the end of the list. I would rather not put another field such as "SortOrder" in the table to use to order the sort, and I would rather not have to sort the list in my code. Added: Yes I know this is a bad idea, thanks to all for mentioning it, but still, I am curious if what I am asking can be done
2011/02/09
[ "https://Stackoverflow.com/questions/4949338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105407/" ]
You should use another column in the database to help specify the ordering rather than modifying the string: ``` SELECT * FROM yourtable ORDER BY sortorder, yourstring ``` Where you data might look like this: ``` yourstring sortorder foo 0 bar 0 baz 1 qux 1 quux 2 ``` If you can't modify the table you might be able to put the sortorder column into a different table and join to get it: ``` SELECT * FROM yourtable AS T1 JOIN yourtablesorting AS T2 ON T1.id = T2.T1_id ORDER BY T2.sortorder, T1.yourstring ``` --- Alternative solution: If you really can't modify the database at all, not even adding a new table then you could add any character you like at the start of the string and remove it during the select: ``` SELECT RIGHT(yourstring, LEN(yourstring) - 1) FROM yourtable ORDER BY yourstring ```
In my opinion, an invisible character for this purpose is a bad idea because it pollutes the data. I would do exactly what you would rather not do and add a new column. To modify the idea slightly, you could implement it not as a sort order, but a grouping order, defaults to 0, where a negative integer puts the group at top of the list and a positve integer at the bottom, and then "order by sort\_priority, foo"
36,701,729
I'm having trouble writing a MySQL subquery. The SALES table has the column names: ``` sales_date | staff_id | sales_amount ``` to record each individual employee's sales. What I'm trying to achieve with this query is a table that displays the average daily sales for a selected employee as well as the average daily sales for all employees. I only want to display days when the selected employee had any sales. ``` SELECT staff_id, sales_date, AVG( sales_amount ) AS avgsales, sales_amount FROM sales GROUP BY sales_date WHERE (SELECT sales_date FROM sales WHERE staff_id = $staff_id) // this subquery shows all the dates that staff has records in ``` I want it to display something like this: ``` Staff_id | Sales date | AverageSales | Employee_sales ---------+------------+--------------+---------------- 001 | 2016-04-18 | £2000 | £1800 ---------+------------+--------------+---------------- 001 | 2016-04-17 | £3405 | £4000 ---------+------------+--------------+---------------- 001 | 2016-04-16 | £1450 | £1400 ---------+------------+--------------+---------------- ```
2016/04/18
[ "https://Stackoverflow.com/questions/36701729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6214240/" ]
I use Oracle, so there will likely be a typo in this MySQL SQL. But, I hope it works properly... You have two concepts: Average sales for everyone per day and average sales per user per day. You want to join those two things together. You can easily. First, you have the average sales per day. ``` select sales_date, avg(sales_amount) as averagesales from sales group by sales_date ``` Now, you want the average sales per user per day. ``` select staff_id, sales_date, avg(sales_amount) as employeesales from sales group by sales_date, staff_id ``` You want those joined together. That is easy. ``` select * from ( select sales_date, avg(sales_amount) as averagesales from sales group by sales_date )a join ( select staff_id, sales_date, avg(sales_amount) as employeesales from sales group by sales_date, staff_id )b on a.sales_date=b.sales_date ``` That will give you staff\_id, sales\_date, average sales for the day, and employee average sales for the day in one query. You will likely want to order it just how you like, limit the dates, and other things.
You can join a table to itself in a query, rather than use a subquery. Try this: ``` SELECT sales.staff_id, sales.sales_date, AVG(sales.sales_amount), AVG(emp.sales_amount) FROM sales LEFT JOIN sales emp ON (emp.staff_id=$staff_id) WHERE sales.staff_id=$staff_id GROUP BY sales_date; ``` So essentially this creates a second table containing only the selected employee's sales, which you can then average.
16,140,415
I'm struggling to handle the back button and ask confirmation to the user, if app state is dirty. Closing tab and reload is already handled via the `onbeforeunload` hook. I've played with `$routeChangeStart`, `$beforeRouteChange`, etc. but can't handle it correctly. With `$routeChangeStart`, the route is effectively changed before my callback is called. What is the correct way to handle this situation? Thanks for your help.
2013/04/22
[ "https://Stackoverflow.com/questions/16140415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506051/" ]
you could use: ``` $scope.$on('$routeChangeStart', function(next, current) { //broadcasted before a route change // do something here }); ``` See more of it on : [$route](http://docs.angularjs.org/api/ng.%24route)
Keep a model of the dirty state in a parent controller, common to all views? An alert/confirm appears if a dirty state is detected by any view's controller, with a "Cancel" button that resets $location.path(...) to the dirty page.
16,140,415
I'm struggling to handle the back button and ask confirmation to the user, if app state is dirty. Closing tab and reload is already handled via the `onbeforeunload` hook. I've played with `$routeChangeStart`, `$beforeRouteChange`, etc. but can't handle it correctly. With `$routeChangeStart`, the route is effectively changed before my callback is called. What is the correct way to handle this situation? Thanks for your help.
2013/04/22
[ "https://Stackoverflow.com/questions/16140415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506051/" ]
I believe $locationChangeStart fires when you would like it to.
you could use: ``` $scope.$on('$routeChangeStart', function(next, current) { //broadcasted before a route change // do something here }); ``` See more of it on : [$route](http://docs.angularjs.org/api/ng.%24route)
16,140,415
I'm struggling to handle the back button and ask confirmation to the user, if app state is dirty. Closing tab and reload is already handled via the `onbeforeunload` hook. I've played with `$routeChangeStart`, `$beforeRouteChange`, etc. but can't handle it correctly. With `$routeChangeStart`, the route is effectively changed before my callback is called. What is the correct way to handle this situation? Thanks for your help.
2013/04/22
[ "https://Stackoverflow.com/questions/16140415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1506051/" ]
I believe $locationChangeStart fires when you would like it to.
Keep a model of the dirty state in a parent controller, common to all views? An alert/confirm appears if a dirty state is detected by any view's controller, with a "Cancel" button that resets $location.path(...) to the dirty page.
34,369,398
[![enter image description here](https://i.stack.imgur.com/hJUjp.png)](https://i.stack.imgur.com/hJUjp.png) Hi All, Does any of you face this problem before? My Android studio stuck on startup. I've tried restart/shut down. Btw, my android studio version is 1.5 on mac
2015/12/19
[ "https://Stackoverflow.com/questions/34369398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128070/" ]
If you experience system crash or system auto restart, then please be patient. It take sometime to startup and everything will back to normal :) cheer!
You should go to the %appdata% and delete InteliJ folder, after that run program as administrator. This is probably caused by: * No space on partition * No write permission in %appdata% * Bug If it does not work, try to reinstall. ... 1 more! * Slow write speed or compute speed so it takes much more time as usual.
28,882,907
I know I can get the first character of a line of standard input by using getchar(), but I *only* want the first character of each line. Is there a function I can use to get rid of the rest of the string entered into standard input (if it is more than one character)? if not, what methodology should I consider using to get rid of the rest of the standard input line?
2015/03/05
[ "https://Stackoverflow.com/questions/28882907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3735278/" ]
``` char buf[100]; while(fgets(buf,sizeof(buf),stdin) != NULL) { if(strlen(buf)>0) buf[1] = '\0'; printf("%s",buf); } ``` Read the whole line using `fgets()` and just nul terminate it after the first character.
``` #include <stdio.h> int main(void) { int ch; size_t len; for (len = 0; 1; ) { ch = getc(stdin); if (ch == EOF) break; if (!len++) putc(ch, stdout); /* the first character on a line */ if (ch == '\n') len = 0; /* the line has ended */ } return 0; } ``` Please note that the first character on a line can actually be a `'\n'` !!!
28,882,907
I know I can get the first character of a line of standard input by using getchar(), but I *only* want the first character of each line. Is there a function I can use to get rid of the rest of the string entered into standard input (if it is more than one character)? if not, what methodology should I consider using to get rid of the rest of the standard input line?
2015/03/05
[ "https://Stackoverflow.com/questions/28882907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3735278/" ]
``` char buf[100]; while(fgets(buf,sizeof(buf),stdin) != NULL) { if(strlen(buf)>0) buf[1] = '\0'; printf("%s",buf); } ``` Read the whole line using `fgets()` and just nul terminate it after the first character.
``` // Get the character you need char c = getchar(); // Skip the rest int a; while((a = getchar()) != '\n' && a != EOF); ``` If you know how many lines you'll have, you can put it in a loop.
11,584,745
I'm writing a shell script with `#!/bin/sh` as the first line so that the script exits on the first error. There are a few lines in the file that are in the form of `command || true` so that the script doesn't exit right there if the command fails. However, I still want to know know the exit code of the command. How would I get the exit code without having to use `set +e` to temporarily disable that behavior?
2012/07/20
[ "https://Stackoverflow.com/questions/11584745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381521/" ]
Your question appears to imply `set -e`. Assuming `set -e`: Instead of `command || true` you can use `command || exitCode=$?`. The script will continue and the exit status of `command` is captured in `exitCode`. `$?` is an internal variable that keeps the exit code of the last command. Since `||` short-circuits if `command` succeeds, set `exitCode=0` between tests or instead use: `command && exitCode=0 || exitCode=$?`. But prefer to avoid `set -e` style scripting altogether, and instead add explicit error handling to each command in your script.
If you want to know the status of the command, then presumably you take different actions depending on its value. In which case your code should look something like: ``` if command; then # do something when command succeeds else # do something when command fails fi ``` In that case you don't need to do anything special, since the shell will not abort when command fails. The only reasons `set -e` would give you any problems is if you write your code as: ``` command if test $? = 1; ... ``` So don't do that.
35,922,016
I have been struggling on how to get the quantity of distinct values from a collection in Eloquent. I have been trying several methods, such as unique(), values(), etc., found on the [docs](https://laravel.com/docs/5.2/collections). Even though there is indeed a count() method, there is no method to get the count of distinct values. For example, by applying the following query ``` $technicalshighestdegrees = Capsule::table('academicinfo AS fa') ->selectRaw('DISTINCT fa.academic_id AS Id,c.name AS Degree') ->leftJoin('academics AS a','fa.academic_id','=','a.id') ->leftJoin('cat_degree AS c','fa.level','=','c.id') ->whereIn('a.type',['Technical']) ->where('a.status','!=','Retired') ->where('c.degree',true) ->orderBy('a.id') ->orderBy('c.hierarchy','desc')/*http://stackoverflow.com/a/17006377/1883256*/ ->get(); ``` I get this collection: ``` Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => stdClass Object ( [Id] => 3 [Grado] => Master ) [1] => stdClass Object ( [Id] => 3 [Grado] => Bachelor ) [2] => stdClass Object ( [Id] => 4 [Grado] => Master ) [3] => stdClass Object ( [Id] => 4 [Grado] => Bachelor ) [4] => stdClass Object ( [Id] => 6 [Grado] => Master ) [5] => stdClass Object ( [Id] => 6 [Grado] => Bachelor ) [6] => stdClass Object ( [Id] => 18 [Grado] => Bachelor ) [7] => stdClass Object ( [Id] => 27 [Grado] => Bachelor ) [8] => stdClass Object ( [Id] => 34 [Grado] => Master ) [9] => stdClass Object ( [Id] => 34 [Grado] => Bachelor ) [10] => stdClass Object ( [Id] => 36 [Grado] => PhD ) [11] => stdClass Object ( [Id] => 36 [Grado] => Master ) [12] => stdClass Object ( [Id] => 36 [Grado] => Bachelor ) [13] => stdClass Object ( [Id] => 37 [Grado] => Bachelor ) [14] => stdClass Object ( [Id] => 42 [Grado] => PhD ) [15] => stdClass Object ( [Id] => 42 [Grado] => Master ) [16] => stdClass Object ( [Id] => 42 [Grado] => Bachelor ) [17] => stdClass Object ( [Id] => 50 [Grado] => Bachelor ) [18] => stdClass Object ( [Id] => 52 [Grado] => Bachelor ) [19] => stdClass Object ( [Id] => 53 [Grado] => Master ) [20] => stdClass Object ( [Id] => 53 [Grado] => Bachelor ) [21] => stdClass Object ( [Id] => 54 [Grado] => Master ) [22] => stdClass Object ( [Id] => 54 [Grado] => Bachelor ) [23] => stdClass Object ( [Id] => 55 [Grado] => Master ) [24] => stdClass Object ( [Id] => 55 [Grado] => Bachelor ) [25] => stdClass Object ( [Id] => 57 [Grado] => Bachelor ) [26] => stdClass Object ( [Id] => 68 [Grado] => Master ) [27] => stdClass Object ( [Id] => 68 [Grado] => Bachelor ) [28] => stdClass Object ( [Id] => 72 [Grado] => Master ) [29] => stdClass Object ( [Id] => 72 [Grado] => Bachelor ) [30] => stdClass Object ( [Id] => 77 [Grado] => Bachelor ) [31] => stdClass Object ( [Id] => 82 [Grado] => Bachelor ) [32] => stdClass Object ( [Id] => 85 [Grado] => PhD ) [33] => stdClass Object ( [Id] => 85 [Grado] => Master ) [34] => stdClass Object ( [Id] => 85 [Grado] => Bachelor ) [35] => stdClass Object ( [Id] => 92 [Grado] => Master ) [36] => stdClass Object ( [Id] => 92 [Grado] => Bachelor ) [37] => stdClass Object ( [Id] => 100 [Grado] => Master ) [38] => stdClass Object ( [Id] => 100 [Grado] => Bachelor ) [39] => stdClass Object ( [Id] => 111 [Grado] => Bachelor ) [40] => stdClass Object ( [Id] => 117 [Grado] => Master ) [41] => stdClass Object ( [Id] => 117 [Grado] => Bachelor ) [42] => stdClass Object ( [Id] => 123 [Grado] => Master ) [43] => stdClass Object ( [Id] => 123 [Grado] => Bachelor ) ) ) ``` Since, I just want to get the highest degrees (a user Id may have several historical degrees), I apply the unique() method, that according to the docs, it leaves only the first original value, in my case, I have already ordered them by hierarchy desc: ``` $technicalshighestdegrees = $technicalshighestdegrees->unique('Id'); ``` And now I get the following collection (reduced to 25 items, which is exactly the total number): ``` Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => stdClass Object ( [Id] => 3 [Degree] => Master ) [2] => stdClass Object ( [Id] => 4 [Degree] => Master ) [4] => stdClass Object ( [Id] => 6 [Degree] => Master ) [6] => stdClass Object ( [Id] => 18 [Degree] => Bachelor ) [7] => stdClass Object ( [Id] => 27 [Degree] => Bachelor ) [8] => stdClass Object ( [Id] => 34 [Degree] => Master ) [10] => stdClass Object ( [Id] => 36 [Degree] => PhD ) [13] => stdClass Object ( [Id] => 37 [Degree] => Bachelor ) [14] => stdClass Object ( [Id] => 42 [Degree] => PhD ) [17] => stdClass Object ( [Id] => 50 [Degree] => Bachelor ) [18] => stdClass Object ( [Id] => 52 [Degree] => Bachelor ) [19] => stdClass Object ( [Id] => 53 [Degree] => Master ) [21] => stdClass Object ( [Id] => 54 [Degree] => Master ) [23] => stdClass Object ( [Id] => 55 [Degree] => Master ) [25] => stdClass Object ( [Id] => 57 [Degree] => Bachelor ) [26] => stdClass Object ( [Id] => 68 [Degree] => Master ) [28] => stdClass Object ( [Id] => 72 [Degree] => Master ) [30] => stdClass Object ( [Id] => 77 [Degree] => Bachelor ) [31] => stdClass Object ( [Id] => 82 [Degree] => Bachelor ) [32] => stdClass Object ( [Id] => 85 [Degree] => PhD ) [35] => stdClass Object ( [Id] => 92 [Degree] => Master ) [37] => stdClass Object ( [Id] => 100 [Degree] => Master ) [39] => stdClass Object ( [Id] => 111 [Degree] => Bachelor ) [40] => stdClass Object ( [Id] => 117 [Degree] => Master ) [42] => stdClass Object ( [Id] => 123 [Degree] => Master ) ) ) ``` What I want is to get the quantities for each distinct degree value as follows: ``` Array ( [Master] => 13 [Bachelor] => 9 [PhD] => 3 ) ``` But in an Eloquent collection... How can I achieve this?
2016/03/10
[ "https://Stackoverflow.com/questions/35922016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1883256/" ]
Update for 2021/L6+ *thanks @JeremyWadhams* ```php $degrees->groupBy('Degree')->map(fn ($people) => $people->count()); // or using HigherOrder proxy on the collection $degrees->groupBy('Degree')->map->count(); ``` --- Using collection methods this would be it: ```php $degrees->groupBy('Degree')->map(function ($people) { return $people->count(); }); // Collection { // 'Master' => 13, // 'Bachelor' => 9, // 'PhD' => 3 // } ```
Could also do the following: ``` $master = $degrees->sum('Master'); return $master; $bachelor = $degrees->sum('Bachelor'); return $bachelor; $phD = $degrees->sum('PhD'); return $phD; ```
35,922,016
I have been struggling on how to get the quantity of distinct values from a collection in Eloquent. I have been trying several methods, such as unique(), values(), etc., found on the [docs](https://laravel.com/docs/5.2/collections). Even though there is indeed a count() method, there is no method to get the count of distinct values. For example, by applying the following query ``` $technicalshighestdegrees = Capsule::table('academicinfo AS fa') ->selectRaw('DISTINCT fa.academic_id AS Id,c.name AS Degree') ->leftJoin('academics AS a','fa.academic_id','=','a.id') ->leftJoin('cat_degree AS c','fa.level','=','c.id') ->whereIn('a.type',['Technical']) ->where('a.status','!=','Retired') ->where('c.degree',true) ->orderBy('a.id') ->orderBy('c.hierarchy','desc')/*http://stackoverflow.com/a/17006377/1883256*/ ->get(); ``` I get this collection: ``` Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => stdClass Object ( [Id] => 3 [Grado] => Master ) [1] => stdClass Object ( [Id] => 3 [Grado] => Bachelor ) [2] => stdClass Object ( [Id] => 4 [Grado] => Master ) [3] => stdClass Object ( [Id] => 4 [Grado] => Bachelor ) [4] => stdClass Object ( [Id] => 6 [Grado] => Master ) [5] => stdClass Object ( [Id] => 6 [Grado] => Bachelor ) [6] => stdClass Object ( [Id] => 18 [Grado] => Bachelor ) [7] => stdClass Object ( [Id] => 27 [Grado] => Bachelor ) [8] => stdClass Object ( [Id] => 34 [Grado] => Master ) [9] => stdClass Object ( [Id] => 34 [Grado] => Bachelor ) [10] => stdClass Object ( [Id] => 36 [Grado] => PhD ) [11] => stdClass Object ( [Id] => 36 [Grado] => Master ) [12] => stdClass Object ( [Id] => 36 [Grado] => Bachelor ) [13] => stdClass Object ( [Id] => 37 [Grado] => Bachelor ) [14] => stdClass Object ( [Id] => 42 [Grado] => PhD ) [15] => stdClass Object ( [Id] => 42 [Grado] => Master ) [16] => stdClass Object ( [Id] => 42 [Grado] => Bachelor ) [17] => stdClass Object ( [Id] => 50 [Grado] => Bachelor ) [18] => stdClass Object ( [Id] => 52 [Grado] => Bachelor ) [19] => stdClass Object ( [Id] => 53 [Grado] => Master ) [20] => stdClass Object ( [Id] => 53 [Grado] => Bachelor ) [21] => stdClass Object ( [Id] => 54 [Grado] => Master ) [22] => stdClass Object ( [Id] => 54 [Grado] => Bachelor ) [23] => stdClass Object ( [Id] => 55 [Grado] => Master ) [24] => stdClass Object ( [Id] => 55 [Grado] => Bachelor ) [25] => stdClass Object ( [Id] => 57 [Grado] => Bachelor ) [26] => stdClass Object ( [Id] => 68 [Grado] => Master ) [27] => stdClass Object ( [Id] => 68 [Grado] => Bachelor ) [28] => stdClass Object ( [Id] => 72 [Grado] => Master ) [29] => stdClass Object ( [Id] => 72 [Grado] => Bachelor ) [30] => stdClass Object ( [Id] => 77 [Grado] => Bachelor ) [31] => stdClass Object ( [Id] => 82 [Grado] => Bachelor ) [32] => stdClass Object ( [Id] => 85 [Grado] => PhD ) [33] => stdClass Object ( [Id] => 85 [Grado] => Master ) [34] => stdClass Object ( [Id] => 85 [Grado] => Bachelor ) [35] => stdClass Object ( [Id] => 92 [Grado] => Master ) [36] => stdClass Object ( [Id] => 92 [Grado] => Bachelor ) [37] => stdClass Object ( [Id] => 100 [Grado] => Master ) [38] => stdClass Object ( [Id] => 100 [Grado] => Bachelor ) [39] => stdClass Object ( [Id] => 111 [Grado] => Bachelor ) [40] => stdClass Object ( [Id] => 117 [Grado] => Master ) [41] => stdClass Object ( [Id] => 117 [Grado] => Bachelor ) [42] => stdClass Object ( [Id] => 123 [Grado] => Master ) [43] => stdClass Object ( [Id] => 123 [Grado] => Bachelor ) ) ) ``` Since, I just want to get the highest degrees (a user Id may have several historical degrees), I apply the unique() method, that according to the docs, it leaves only the first original value, in my case, I have already ordered them by hierarchy desc: ``` $technicalshighestdegrees = $technicalshighestdegrees->unique('Id'); ``` And now I get the following collection (reduced to 25 items, which is exactly the total number): ``` Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => stdClass Object ( [Id] => 3 [Degree] => Master ) [2] => stdClass Object ( [Id] => 4 [Degree] => Master ) [4] => stdClass Object ( [Id] => 6 [Degree] => Master ) [6] => stdClass Object ( [Id] => 18 [Degree] => Bachelor ) [7] => stdClass Object ( [Id] => 27 [Degree] => Bachelor ) [8] => stdClass Object ( [Id] => 34 [Degree] => Master ) [10] => stdClass Object ( [Id] => 36 [Degree] => PhD ) [13] => stdClass Object ( [Id] => 37 [Degree] => Bachelor ) [14] => stdClass Object ( [Id] => 42 [Degree] => PhD ) [17] => stdClass Object ( [Id] => 50 [Degree] => Bachelor ) [18] => stdClass Object ( [Id] => 52 [Degree] => Bachelor ) [19] => stdClass Object ( [Id] => 53 [Degree] => Master ) [21] => stdClass Object ( [Id] => 54 [Degree] => Master ) [23] => stdClass Object ( [Id] => 55 [Degree] => Master ) [25] => stdClass Object ( [Id] => 57 [Degree] => Bachelor ) [26] => stdClass Object ( [Id] => 68 [Degree] => Master ) [28] => stdClass Object ( [Id] => 72 [Degree] => Master ) [30] => stdClass Object ( [Id] => 77 [Degree] => Bachelor ) [31] => stdClass Object ( [Id] => 82 [Degree] => Bachelor ) [32] => stdClass Object ( [Id] => 85 [Degree] => PhD ) [35] => stdClass Object ( [Id] => 92 [Degree] => Master ) [37] => stdClass Object ( [Id] => 100 [Degree] => Master ) [39] => stdClass Object ( [Id] => 111 [Degree] => Bachelor ) [40] => stdClass Object ( [Id] => 117 [Degree] => Master ) [42] => stdClass Object ( [Id] => 123 [Degree] => Master ) ) ) ``` What I want is to get the quantities for each distinct degree value as follows: ``` Array ( [Master] => 13 [Bachelor] => 9 [PhD] => 3 ) ``` But in an Eloquent collection... How can I achieve this?
2016/03/10
[ "https://Stackoverflow.com/questions/35922016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1883256/" ]
Update for 2021/L6+ *thanks @JeremyWadhams* ```php $degrees->groupBy('Degree')->map(fn ($people) => $people->count()); // or using HigherOrder proxy on the collection $degrees->groupBy('Degree')->map->count(); ``` --- Using collection methods this would be it: ```php $degrees->groupBy('Degree')->map(function ($people) { return $people->count(); }); // Collection { // 'Master' => 13, // 'Bachelor' => 9, // 'PhD' => 3 // } ```
There is a Collection Helper called CountBy, does exactly what you need. [Collections CountBy](https://laravel.com/docs/8.x/collections#method-countBy) ``` $degrees->countBy('Degree'); ``` It will retourn as expected ``` Array ( [Master] => 13 [Bachelor] => 9 [PhD] => 3 ) ``` Simple :D
35,922,016
I have been struggling on how to get the quantity of distinct values from a collection in Eloquent. I have been trying several methods, such as unique(), values(), etc., found on the [docs](https://laravel.com/docs/5.2/collections). Even though there is indeed a count() method, there is no method to get the count of distinct values. For example, by applying the following query ``` $technicalshighestdegrees = Capsule::table('academicinfo AS fa') ->selectRaw('DISTINCT fa.academic_id AS Id,c.name AS Degree') ->leftJoin('academics AS a','fa.academic_id','=','a.id') ->leftJoin('cat_degree AS c','fa.level','=','c.id') ->whereIn('a.type',['Technical']) ->where('a.status','!=','Retired') ->where('c.degree',true) ->orderBy('a.id') ->orderBy('c.hierarchy','desc')/*http://stackoverflow.com/a/17006377/1883256*/ ->get(); ``` I get this collection: ``` Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => stdClass Object ( [Id] => 3 [Grado] => Master ) [1] => stdClass Object ( [Id] => 3 [Grado] => Bachelor ) [2] => stdClass Object ( [Id] => 4 [Grado] => Master ) [3] => stdClass Object ( [Id] => 4 [Grado] => Bachelor ) [4] => stdClass Object ( [Id] => 6 [Grado] => Master ) [5] => stdClass Object ( [Id] => 6 [Grado] => Bachelor ) [6] => stdClass Object ( [Id] => 18 [Grado] => Bachelor ) [7] => stdClass Object ( [Id] => 27 [Grado] => Bachelor ) [8] => stdClass Object ( [Id] => 34 [Grado] => Master ) [9] => stdClass Object ( [Id] => 34 [Grado] => Bachelor ) [10] => stdClass Object ( [Id] => 36 [Grado] => PhD ) [11] => stdClass Object ( [Id] => 36 [Grado] => Master ) [12] => stdClass Object ( [Id] => 36 [Grado] => Bachelor ) [13] => stdClass Object ( [Id] => 37 [Grado] => Bachelor ) [14] => stdClass Object ( [Id] => 42 [Grado] => PhD ) [15] => stdClass Object ( [Id] => 42 [Grado] => Master ) [16] => stdClass Object ( [Id] => 42 [Grado] => Bachelor ) [17] => stdClass Object ( [Id] => 50 [Grado] => Bachelor ) [18] => stdClass Object ( [Id] => 52 [Grado] => Bachelor ) [19] => stdClass Object ( [Id] => 53 [Grado] => Master ) [20] => stdClass Object ( [Id] => 53 [Grado] => Bachelor ) [21] => stdClass Object ( [Id] => 54 [Grado] => Master ) [22] => stdClass Object ( [Id] => 54 [Grado] => Bachelor ) [23] => stdClass Object ( [Id] => 55 [Grado] => Master ) [24] => stdClass Object ( [Id] => 55 [Grado] => Bachelor ) [25] => stdClass Object ( [Id] => 57 [Grado] => Bachelor ) [26] => stdClass Object ( [Id] => 68 [Grado] => Master ) [27] => stdClass Object ( [Id] => 68 [Grado] => Bachelor ) [28] => stdClass Object ( [Id] => 72 [Grado] => Master ) [29] => stdClass Object ( [Id] => 72 [Grado] => Bachelor ) [30] => stdClass Object ( [Id] => 77 [Grado] => Bachelor ) [31] => stdClass Object ( [Id] => 82 [Grado] => Bachelor ) [32] => stdClass Object ( [Id] => 85 [Grado] => PhD ) [33] => stdClass Object ( [Id] => 85 [Grado] => Master ) [34] => stdClass Object ( [Id] => 85 [Grado] => Bachelor ) [35] => stdClass Object ( [Id] => 92 [Grado] => Master ) [36] => stdClass Object ( [Id] => 92 [Grado] => Bachelor ) [37] => stdClass Object ( [Id] => 100 [Grado] => Master ) [38] => stdClass Object ( [Id] => 100 [Grado] => Bachelor ) [39] => stdClass Object ( [Id] => 111 [Grado] => Bachelor ) [40] => stdClass Object ( [Id] => 117 [Grado] => Master ) [41] => stdClass Object ( [Id] => 117 [Grado] => Bachelor ) [42] => stdClass Object ( [Id] => 123 [Grado] => Master ) [43] => stdClass Object ( [Id] => 123 [Grado] => Bachelor ) ) ) ``` Since, I just want to get the highest degrees (a user Id may have several historical degrees), I apply the unique() method, that according to the docs, it leaves only the first original value, in my case, I have already ordered them by hierarchy desc: ``` $technicalshighestdegrees = $technicalshighestdegrees->unique('Id'); ``` And now I get the following collection (reduced to 25 items, which is exactly the total number): ``` Illuminate\Support\Collection Object ( [items:protected] => Array ( [0] => stdClass Object ( [Id] => 3 [Degree] => Master ) [2] => stdClass Object ( [Id] => 4 [Degree] => Master ) [4] => stdClass Object ( [Id] => 6 [Degree] => Master ) [6] => stdClass Object ( [Id] => 18 [Degree] => Bachelor ) [7] => stdClass Object ( [Id] => 27 [Degree] => Bachelor ) [8] => stdClass Object ( [Id] => 34 [Degree] => Master ) [10] => stdClass Object ( [Id] => 36 [Degree] => PhD ) [13] => stdClass Object ( [Id] => 37 [Degree] => Bachelor ) [14] => stdClass Object ( [Id] => 42 [Degree] => PhD ) [17] => stdClass Object ( [Id] => 50 [Degree] => Bachelor ) [18] => stdClass Object ( [Id] => 52 [Degree] => Bachelor ) [19] => stdClass Object ( [Id] => 53 [Degree] => Master ) [21] => stdClass Object ( [Id] => 54 [Degree] => Master ) [23] => stdClass Object ( [Id] => 55 [Degree] => Master ) [25] => stdClass Object ( [Id] => 57 [Degree] => Bachelor ) [26] => stdClass Object ( [Id] => 68 [Degree] => Master ) [28] => stdClass Object ( [Id] => 72 [Degree] => Master ) [30] => stdClass Object ( [Id] => 77 [Degree] => Bachelor ) [31] => stdClass Object ( [Id] => 82 [Degree] => Bachelor ) [32] => stdClass Object ( [Id] => 85 [Degree] => PhD ) [35] => stdClass Object ( [Id] => 92 [Degree] => Master ) [37] => stdClass Object ( [Id] => 100 [Degree] => Master ) [39] => stdClass Object ( [Id] => 111 [Degree] => Bachelor ) [40] => stdClass Object ( [Id] => 117 [Degree] => Master ) [42] => stdClass Object ( [Id] => 123 [Degree] => Master ) ) ) ``` What I want is to get the quantities for each distinct degree value as follows: ``` Array ( [Master] => 13 [Bachelor] => 9 [PhD] => 3 ) ``` But in an Eloquent collection... How can I achieve this?
2016/03/10
[ "https://Stackoverflow.com/questions/35922016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1883256/" ]
There is a Collection Helper called CountBy, does exactly what you need. [Collections CountBy](https://laravel.com/docs/8.x/collections#method-countBy) ``` $degrees->countBy('Degree'); ``` It will retourn as expected ``` Array ( [Master] => 13 [Bachelor] => 9 [PhD] => 3 ) ``` Simple :D
Could also do the following: ``` $master = $degrees->sum('Master'); return $master; $bachelor = $degrees->sum('Bachelor'); return $bachelor; $phD = $degrees->sum('PhD'); return $phD; ```
38,162,681
I want the user to input the coordinates of 4 points such as (xa,ya),(xb,yb),(xc,yc),(xd,yd) but all of it at once. I used this code: > > xa=input("Enter x-coordinate for node 1:") > > > ya=input("Enter y-coordinate for node 1:") > > > xb=input("Enter x-coordinate for node 2:") > > > yb=input("Enter y-coordinate for node 2:") > > > xc=input("Enter x-coordinate for node 3:") > > > yc=input("Enter y-coordinate for node 3:") > > > xd=input("Enter x-coordinate for node 4:") > > > yd=input("Enter y-coordinate for node 4:") > > > but in this case I am able to give input value for yd only. How can I make the user input all the values at once?
2016/07/02
[ "https://Stackoverflow.com/questions/38162681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6542071/" ]
You can do that using the [jQuery - insertBefore](http://api.jquery.com/insertbefore/) method. I have updated your [jsFiddle](https://jsfiddle.net/sjncgaLf/10/) ``` $(document).ready(function() { // create elements var test = $('<div class = "test">test</div>'); var el = $('<div class = "el">el</div>'); // add the first element $("body").append(test); // insert the second element el.insertBefore(test); }); ```
Based on your update, you just need to edit your variable, not worry about appending data in order. So for your $markup variable, if it already has data and you want to add your month label at the beginning, just use: ``` $temp = $label + $markup; $markup = $temp; ``` To add weeks or day data to the end of your $markup variable, just use: ``` $markup = $markup + $day; ``` Once you've got the entire variable built the way you like you can use jQuery to append it where you want.
38,162,681
I want the user to input the coordinates of 4 points such as (xa,ya),(xb,yb),(xc,yc),(xd,yd) but all of it at once. I used this code: > > xa=input("Enter x-coordinate for node 1:") > > > ya=input("Enter y-coordinate for node 1:") > > > xb=input("Enter x-coordinate for node 2:") > > > yb=input("Enter y-coordinate for node 2:") > > > xc=input("Enter x-coordinate for node 3:") > > > yc=input("Enter y-coordinate for node 3:") > > > xd=input("Enter x-coordinate for node 4:") > > > yd=input("Enter y-coordinate for node 4:") > > > but in this case I am able to give input value for yd only. How can I make the user input all the values at once?
2016/07/02
[ "https://Stackoverflow.com/questions/38162681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6542071/" ]
try like this. ``` $("body").append(el,test); ``` the updated fiddle : <https://jsfiddle.net/sjncgaLf/14/>
Based on your update, you just need to edit your variable, not worry about appending data in order. So for your $markup variable, if it already has data and you want to add your month label at the beginning, just use: ``` $temp = $label + $markup; $markup = $temp; ``` To add weeks or day data to the end of your $markup variable, just use: ``` $markup = $markup + $day; ``` Once you've got the entire variable built the way you like you can use jQuery to append it where you want.
31,741,744
I am struggling with debugging my WatchKit Extension/App on a real Apple Watch. Debugging both the iPhone App and the WatchKit Extension using the simulator the simulator is not problem: 1. Select the WatchKit App Profile and run in Simulator ==> App is launched on in Watch Simulator and I can use breakpoints in the **Extension code** to debug. 2. To debug the iPhone app as well I launch the app in the simulator and attach the debugger manually ==> I can use breakpoints in the **iPhone Code** to debug. It is no problem to observe both the work of the iPhone app and the watch app. At least not in the simulator. I would like to do the same thing on a **real Apple Watch**. But when I select the WatchKit App Profile and my real iPhone (instead of the Simulator) and click on "Run" nothing happens. This means Xcode seems to build and start the app but nothing happens on the devices. The status field in Xcode shows: > > Building MyApp WatchKit App: MyApp WatchKit Extension > > > Building MyApp WatchKit App: Finishing... > > > Running MyApp on My iPhone 6 > > > This is all. No debug Window, breakpoints are ignored or do not work and the app is not launched neither on the iPhone or on the Apple Watch. I found other questions about problems with debugging on real devices (e.g. [here](https://stackoverflow.com/questions/29854314/debug-on-real-apple-watch-application-verification-failed)) but they all deal with installation and signing issues. In my case both the iPhone App and the WatchKit App are installed without any problem. When I click the app icon on the Watch I can start and use the app. **Problem is that I cannot debug this process.** **Why do I need to debug the process on real devices?** Well there is one thing I cannot test using the simulator: What happens when the Watch App tries to contact the iPhone app using `openParentApplication:reply:` when the iPhone app is not already running? This works perfectly in the simulator but on real devices the Watch Apps seems to get no reply from the iPhone app and simply waits forever. I already found [hints](https://stackoverflow.com/questions/30137019/watchkit-return-reply-inside-a-block-in-handlewatchkitextensionrequest) to solve this but without being able to debug the Watch App and to see how the code is executed I cannot be sure what is going on...
2015/07/31
[ "https://Stackoverflow.com/questions/31741744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/777861/" ]
I am having the same kind of issue but to improve a little bit the debugging experience I usually restart my devices a few times. Try to restart your Apple Watch or your iPhone. Before launching your app from Xcode, make sure that the app is completely closed on your Apple Watch (not stuck in the loading screen for example). To do that, you have to force close the app: enter your app, keep the side button pressed until the menu to turn off the watch appears, then press the same side button for a few more seconds until the watch will go back to the homescreen and force close your app. Now you can try to build and run the app from Xcode and it should work more reliably. **watchOS 3+:** The force quit is done by pressing and holding the side button (the button just below the Digital Crown) until the shutdown screen appears, and then let go of the side button, then press and hold the Digital Crown.
Here's a technique that seems to be be the most reliable for me, even though it still only works about 25% of the time (Xcode 7 beta 4, 7A165t): 1. Run the phone target in debug (on your actual iPhone of course) 2. While the iPhone app is still running, switch to the watch target and run that in debug. 3. Keep an eye on your watch homescreen as the app installs. Once the app has installed, tap it to open it. This will sometimes "kickstart" the watch app and allow the debugger to catch it. At this point you should be able to debug both your iPhone app and watchOS app together.
31,741,744
I am struggling with debugging my WatchKit Extension/App on a real Apple Watch. Debugging both the iPhone App and the WatchKit Extension using the simulator the simulator is not problem: 1. Select the WatchKit App Profile and run in Simulator ==> App is launched on in Watch Simulator and I can use breakpoints in the **Extension code** to debug. 2. To debug the iPhone app as well I launch the app in the simulator and attach the debugger manually ==> I can use breakpoints in the **iPhone Code** to debug. It is no problem to observe both the work of the iPhone app and the watch app. At least not in the simulator. I would like to do the same thing on a **real Apple Watch**. But when I select the WatchKit App Profile and my real iPhone (instead of the Simulator) and click on "Run" nothing happens. This means Xcode seems to build and start the app but nothing happens on the devices. The status field in Xcode shows: > > Building MyApp WatchKit App: MyApp WatchKit Extension > > > Building MyApp WatchKit App: Finishing... > > > Running MyApp on My iPhone 6 > > > This is all. No debug Window, breakpoints are ignored or do not work and the app is not launched neither on the iPhone or on the Apple Watch. I found other questions about problems with debugging on real devices (e.g. [here](https://stackoverflow.com/questions/29854314/debug-on-real-apple-watch-application-verification-failed)) but they all deal with installation and signing issues. In my case both the iPhone App and the WatchKit App are installed without any problem. When I click the app icon on the Watch I can start and use the app. **Problem is that I cannot debug this process.** **Why do I need to debug the process on real devices?** Well there is one thing I cannot test using the simulator: What happens when the Watch App tries to contact the iPhone app using `openParentApplication:reply:` when the iPhone app is not already running? This works perfectly in the simulator but on real devices the Watch Apps seems to get no reply from the iPhone app and simply waits forever. I already found [hints](https://stackoverflow.com/questions/30137019/watchkit-return-reply-inside-a-block-in-handlewatchkitextensionrequest) to solve this but without being able to debug the Watch App and to see how the code is executed I cannot be sure what is going on...
2015/07/31
[ "https://Stackoverflow.com/questions/31741744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/777861/" ]
thank you for your answers. I finally managed to get the debugging running (most of the time) on my real Apple Watch. However it is quite cumbersome and not very reliable. There is not enough space in the comments so I will use this answer to describe my solution. Maybe it is help full to other: 1. Make sure, the App on your Watch is not running (as BalestraPatrick described). Launch the app and hold the side button a few seconds to bring up the "Turn off your Watch" dialog. Hold the side button for another few seconds to close the app and to return to the Watch homescreen. 2. Make sure the iPhone is not locked. 3. Select the `WatchKit App` target and your real iPhone and run the project. 4. Running the Watch App resulted quite often in an error `SPErrorInvalidBundleNoGizmoBinaryMessage`. Re-starting Xcode and cleaning both the Watch App and the App target solved this. 5. If the build of the Watch App succeed there will be a short message in Xcode but nothing on your iPhone or Watch. If you have made changes to the Watch App it will take a few seconds to refresh the app on the Watch. This is indicated by the progress-circle overlay over the app icon. If you made no changes ore once the app has been transfered: **Launch the watch app manually by tapping the icon**. There will be no automatic launch. 6. In most cases Xcode will recognize the app launch and attach its debugger to it. This will allow to use breakpoints, inspect the code, etc. In my case I whanted to inspect how the iPhone App handles the `application:handleWatchKitExtensionRequest:reply:` call when the app **was not active before**. This is important because this cannot be done using the simulator. If the app takes to long to handle the request the Watch will receive no valid response. After following the steps described above Xcode is only attached the watch app and will not hold on breakpoints in the iPhone app code. To do this, one has to manually attach the Debugger to the iPhone app process that is started when the watch app sends its call. To be able to attach the debugger I added a delay to the apps main function: `[NSThread sleepForTimeInterval:5]`: 1. Select function in Watch App that will start the call to the iPhone App 2. The iPhone App will be launched in background. The delays gives you 5 seconds to attach the debugger. 3. Choose `Debug\Attach To Process\Likely Targes\Your iPhone App`in Xcode to attach the debugger. 4. After the 5 seconds delay the process will continue and you will be able to use breakpoints in your iPhone app code as well. 5. **Do not forget do remove the delay code when you finished testing :-)** **NOTE:** You will not be able to see `NSLog` output (or any console output at all) from the iPhone App since attaching the debugger does NOT re-route the console output. Happy testing with this awesome new Apple product :-P
I am having the same kind of issue but to improve a little bit the debugging experience I usually restart my devices a few times. Try to restart your Apple Watch or your iPhone. Before launching your app from Xcode, make sure that the app is completely closed on your Apple Watch (not stuck in the loading screen for example). To do that, you have to force close the app: enter your app, keep the side button pressed until the menu to turn off the watch appears, then press the same side button for a few more seconds until the watch will go back to the homescreen and force close your app. Now you can try to build and run the app from Xcode and it should work more reliably. **watchOS 3+:** The force quit is done by pressing and holding the side button (the button just below the Digital Crown) until the shutdown screen appears, and then let go of the side button, then press and hold the Digital Crown.
31,741,744
I am struggling with debugging my WatchKit Extension/App on a real Apple Watch. Debugging both the iPhone App and the WatchKit Extension using the simulator the simulator is not problem: 1. Select the WatchKit App Profile and run in Simulator ==> App is launched on in Watch Simulator and I can use breakpoints in the **Extension code** to debug. 2. To debug the iPhone app as well I launch the app in the simulator and attach the debugger manually ==> I can use breakpoints in the **iPhone Code** to debug. It is no problem to observe both the work of the iPhone app and the watch app. At least not in the simulator. I would like to do the same thing on a **real Apple Watch**. But when I select the WatchKit App Profile and my real iPhone (instead of the Simulator) and click on "Run" nothing happens. This means Xcode seems to build and start the app but nothing happens on the devices. The status field in Xcode shows: > > Building MyApp WatchKit App: MyApp WatchKit Extension > > > Building MyApp WatchKit App: Finishing... > > > Running MyApp on My iPhone 6 > > > This is all. No debug Window, breakpoints are ignored or do not work and the app is not launched neither on the iPhone or on the Apple Watch. I found other questions about problems with debugging on real devices (e.g. [here](https://stackoverflow.com/questions/29854314/debug-on-real-apple-watch-application-verification-failed)) but they all deal with installation and signing issues. In my case both the iPhone App and the WatchKit App are installed without any problem. When I click the app icon on the Watch I can start and use the app. **Problem is that I cannot debug this process.** **Why do I need to debug the process on real devices?** Well there is one thing I cannot test using the simulator: What happens when the Watch App tries to contact the iPhone app using `openParentApplication:reply:` when the iPhone app is not already running? This works perfectly in the simulator but on real devices the Watch Apps seems to get no reply from the iPhone app and simply waits forever. I already found [hints](https://stackoverflow.com/questions/30137019/watchkit-return-reply-inside-a-block-in-handlewatchkitextensionrequest) to solve this but without being able to debug the Watch App and to see how the code is executed I cannot be sure what is going on...
2015/07/31
[ "https://Stackoverflow.com/questions/31741744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/777861/" ]
I am having the same kind of issue but to improve a little bit the debugging experience I usually restart my devices a few times. Try to restart your Apple Watch or your iPhone. Before launching your app from Xcode, make sure that the app is completely closed on your Apple Watch (not stuck in the loading screen for example). To do that, you have to force close the app: enter your app, keep the side button pressed until the menu to turn off the watch appears, then press the same side button for a few more seconds until the watch will go back to the homescreen and force close your app. Now you can try to build and run the app from Xcode and it should work more reliably. **watchOS 3+:** The force quit is done by pressing and holding the side button (the button just below the Digital Crown) until the shutdown screen appears, and then let go of the side button, then press and hold the Digital Crown.
This question has different answers. All are good. The reason is: in my experience there are at least two different problems that prevent debugging on a real watch. Both require a different strategy. This answer tries to help you to decide when to use which strategy. 1. XCode installs, tells you it is running for a short time and then stops showing "running...". * start with the answer of BalestraPatrick: * restart your devices. * Do not forget to restart your iPhone. This did the trick the first time I had this problem. 2. XCode installs, tells you it is running for a longer period of time: "running <projectName> on Apple Watch of <yourname>. * start with the answer of Jay Hickey or Andrei Herford * starting the watch app manually probably does the trick. I also had times when XCode was able to start my watch app without any help from me. Bonus: Starting with XCode 7.1 it seems XCode doesn't always compile all necessary Swift files (more often than before). This is not watch specific, it also applies to iOS apps. The symptoms can look similar to those of this question. -> clean your project and then restart XCode.
31,741,744
I am struggling with debugging my WatchKit Extension/App on a real Apple Watch. Debugging both the iPhone App and the WatchKit Extension using the simulator the simulator is not problem: 1. Select the WatchKit App Profile and run in Simulator ==> App is launched on in Watch Simulator and I can use breakpoints in the **Extension code** to debug. 2. To debug the iPhone app as well I launch the app in the simulator and attach the debugger manually ==> I can use breakpoints in the **iPhone Code** to debug. It is no problem to observe both the work of the iPhone app and the watch app. At least not in the simulator. I would like to do the same thing on a **real Apple Watch**. But when I select the WatchKit App Profile and my real iPhone (instead of the Simulator) and click on "Run" nothing happens. This means Xcode seems to build and start the app but nothing happens on the devices. The status field in Xcode shows: > > Building MyApp WatchKit App: MyApp WatchKit Extension > > > Building MyApp WatchKit App: Finishing... > > > Running MyApp on My iPhone 6 > > > This is all. No debug Window, breakpoints are ignored or do not work and the app is not launched neither on the iPhone or on the Apple Watch. I found other questions about problems with debugging on real devices (e.g. [here](https://stackoverflow.com/questions/29854314/debug-on-real-apple-watch-application-verification-failed)) but they all deal with installation and signing issues. In my case both the iPhone App and the WatchKit App are installed without any problem. When I click the app icon on the Watch I can start and use the app. **Problem is that I cannot debug this process.** **Why do I need to debug the process on real devices?** Well there is one thing I cannot test using the simulator: What happens when the Watch App tries to contact the iPhone app using `openParentApplication:reply:` when the iPhone app is not already running? This works perfectly in the simulator but on real devices the Watch Apps seems to get no reply from the iPhone app and simply waits forever. I already found [hints](https://stackoverflow.com/questions/30137019/watchkit-return-reply-inside-a-block-in-handlewatchkitextensionrequest) to solve this but without being able to debug the Watch App and to see how the code is executed I cannot be sure what is going on...
2015/07/31
[ "https://Stackoverflow.com/questions/31741744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/777861/" ]
thank you for your answers. I finally managed to get the debugging running (most of the time) on my real Apple Watch. However it is quite cumbersome and not very reliable. There is not enough space in the comments so I will use this answer to describe my solution. Maybe it is help full to other: 1. Make sure, the App on your Watch is not running (as BalestraPatrick described). Launch the app and hold the side button a few seconds to bring up the "Turn off your Watch" dialog. Hold the side button for another few seconds to close the app and to return to the Watch homescreen. 2. Make sure the iPhone is not locked. 3. Select the `WatchKit App` target and your real iPhone and run the project. 4. Running the Watch App resulted quite often in an error `SPErrorInvalidBundleNoGizmoBinaryMessage`. Re-starting Xcode and cleaning both the Watch App and the App target solved this. 5. If the build of the Watch App succeed there will be a short message in Xcode but nothing on your iPhone or Watch. If you have made changes to the Watch App it will take a few seconds to refresh the app on the Watch. This is indicated by the progress-circle overlay over the app icon. If you made no changes ore once the app has been transfered: **Launch the watch app manually by tapping the icon**. There will be no automatic launch. 6. In most cases Xcode will recognize the app launch and attach its debugger to it. This will allow to use breakpoints, inspect the code, etc. In my case I whanted to inspect how the iPhone App handles the `application:handleWatchKitExtensionRequest:reply:` call when the app **was not active before**. This is important because this cannot be done using the simulator. If the app takes to long to handle the request the Watch will receive no valid response. After following the steps described above Xcode is only attached the watch app and will not hold on breakpoints in the iPhone app code. To do this, one has to manually attach the Debugger to the iPhone app process that is started when the watch app sends its call. To be able to attach the debugger I added a delay to the apps main function: `[NSThread sleepForTimeInterval:5]`: 1. Select function in Watch App that will start the call to the iPhone App 2. The iPhone App will be launched in background. The delays gives you 5 seconds to attach the debugger. 3. Choose `Debug\Attach To Process\Likely Targes\Your iPhone App`in Xcode to attach the debugger. 4. After the 5 seconds delay the process will continue and you will be able to use breakpoints in your iPhone app code as well. 5. **Do not forget do remove the delay code when you finished testing :-)** **NOTE:** You will not be able to see `NSLog` output (or any console output at all) from the iPhone App since attaching the debugger does NOT re-route the console output. Happy testing with this awesome new Apple product :-P
Here's a technique that seems to be be the most reliable for me, even though it still only works about 25% of the time (Xcode 7 beta 4, 7A165t): 1. Run the phone target in debug (on your actual iPhone of course) 2. While the iPhone app is still running, switch to the watch target and run that in debug. 3. Keep an eye on your watch homescreen as the app installs. Once the app has installed, tap it to open it. This will sometimes "kickstart" the watch app and allow the debugger to catch it. At this point you should be able to debug both your iPhone app and watchOS app together.
31,741,744
I am struggling with debugging my WatchKit Extension/App on a real Apple Watch. Debugging both the iPhone App and the WatchKit Extension using the simulator the simulator is not problem: 1. Select the WatchKit App Profile and run in Simulator ==> App is launched on in Watch Simulator and I can use breakpoints in the **Extension code** to debug. 2. To debug the iPhone app as well I launch the app in the simulator and attach the debugger manually ==> I can use breakpoints in the **iPhone Code** to debug. It is no problem to observe both the work of the iPhone app and the watch app. At least not in the simulator. I would like to do the same thing on a **real Apple Watch**. But when I select the WatchKit App Profile and my real iPhone (instead of the Simulator) and click on "Run" nothing happens. This means Xcode seems to build and start the app but nothing happens on the devices. The status field in Xcode shows: > > Building MyApp WatchKit App: MyApp WatchKit Extension > > > Building MyApp WatchKit App: Finishing... > > > Running MyApp on My iPhone 6 > > > This is all. No debug Window, breakpoints are ignored or do not work and the app is not launched neither on the iPhone or on the Apple Watch. I found other questions about problems with debugging on real devices (e.g. [here](https://stackoverflow.com/questions/29854314/debug-on-real-apple-watch-application-verification-failed)) but they all deal with installation and signing issues. In my case both the iPhone App and the WatchKit App are installed without any problem. When I click the app icon on the Watch I can start and use the app. **Problem is that I cannot debug this process.** **Why do I need to debug the process on real devices?** Well there is one thing I cannot test using the simulator: What happens when the Watch App tries to contact the iPhone app using `openParentApplication:reply:` when the iPhone app is not already running? This works perfectly in the simulator but on real devices the Watch Apps seems to get no reply from the iPhone app and simply waits forever. I already found [hints](https://stackoverflow.com/questions/30137019/watchkit-return-reply-inside-a-block-in-handlewatchkitextensionrequest) to solve this but without being able to debug the Watch App and to see how the code is executed I cannot be sure what is going on...
2015/07/31
[ "https://Stackoverflow.com/questions/31741744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/777861/" ]
thank you for your answers. I finally managed to get the debugging running (most of the time) on my real Apple Watch. However it is quite cumbersome and not very reliable. There is not enough space in the comments so I will use this answer to describe my solution. Maybe it is help full to other: 1. Make sure, the App on your Watch is not running (as BalestraPatrick described). Launch the app and hold the side button a few seconds to bring up the "Turn off your Watch" dialog. Hold the side button for another few seconds to close the app and to return to the Watch homescreen. 2. Make sure the iPhone is not locked. 3. Select the `WatchKit App` target and your real iPhone and run the project. 4. Running the Watch App resulted quite often in an error `SPErrorInvalidBundleNoGizmoBinaryMessage`. Re-starting Xcode and cleaning both the Watch App and the App target solved this. 5. If the build of the Watch App succeed there will be a short message in Xcode but nothing on your iPhone or Watch. If you have made changes to the Watch App it will take a few seconds to refresh the app on the Watch. This is indicated by the progress-circle overlay over the app icon. If you made no changes ore once the app has been transfered: **Launch the watch app manually by tapping the icon**. There will be no automatic launch. 6. In most cases Xcode will recognize the app launch and attach its debugger to it. This will allow to use breakpoints, inspect the code, etc. In my case I whanted to inspect how the iPhone App handles the `application:handleWatchKitExtensionRequest:reply:` call when the app **was not active before**. This is important because this cannot be done using the simulator. If the app takes to long to handle the request the Watch will receive no valid response. After following the steps described above Xcode is only attached the watch app and will not hold on breakpoints in the iPhone app code. To do this, one has to manually attach the Debugger to the iPhone app process that is started when the watch app sends its call. To be able to attach the debugger I added a delay to the apps main function: `[NSThread sleepForTimeInterval:5]`: 1. Select function in Watch App that will start the call to the iPhone App 2. The iPhone App will be launched in background. The delays gives you 5 seconds to attach the debugger. 3. Choose `Debug\Attach To Process\Likely Targes\Your iPhone App`in Xcode to attach the debugger. 4. After the 5 seconds delay the process will continue and you will be able to use breakpoints in your iPhone app code as well. 5. **Do not forget do remove the delay code when you finished testing :-)** **NOTE:** You will not be able to see `NSLog` output (or any console output at all) from the iPhone App since attaching the debugger does NOT re-route the console output. Happy testing with this awesome new Apple product :-P
This question has different answers. All are good. The reason is: in my experience there are at least two different problems that prevent debugging on a real watch. Both require a different strategy. This answer tries to help you to decide when to use which strategy. 1. XCode installs, tells you it is running for a short time and then stops showing "running...". * start with the answer of BalestraPatrick: * restart your devices. * Do not forget to restart your iPhone. This did the trick the first time I had this problem. 2. XCode installs, tells you it is running for a longer period of time: "running <projectName> on Apple Watch of <yourname>. * start with the answer of Jay Hickey or Andrei Herford * starting the watch app manually probably does the trick. I also had times when XCode was able to start my watch app without any help from me. Bonus: Starting with XCode 7.1 it seems XCode doesn't always compile all necessary Swift files (more often than before). This is not watch specific, it also applies to iOS apps. The symptoms can look similar to those of this question. -> clean your project and then restart XCode.
548,196
I would like to get an auto-updating version of Firefox Developer Edition rather than a [once-off installation](https://askubuntu.com/questions/548003). From [comments on the announcement](https://hacks.mozilla.org/2014/11/mozilla-introduces-the-first-browser-built-for-developers-firefox-developer-edition/comment-page-1/) and [this Mozilla ticket](https://bugzilla.mozilla.org/show_bug.cgi?id=1072181) it appears that Firefox Developer Edition is a rebranding of Aurora (a stable pre-release channel). In that case, can I just install [the Firefox Aurora PPA](https://launchpad.net/~ubuntu-mozilla-daily/+archive/ubuntu/firefox-aurora) which is maintained by the Ubuntu Mozilla Daily Build Team?
2014/11/11
[ "https://askubuntu.com/questions/548196", "https://askubuntu.com", "https://askubuntu.com/users/7146/" ]
The [OMG! Ubuntu! post covering the announcement](http://www.omgubuntu.co.uk/2014/11/mozilla-releases-firefox-developer-edition) notes that the version released is [Aurora 35.0a2](https://www.mozilla.org/en-US/firefox/35.0a2/auroranotes/) which matches [the version in the PPA](https://launchpad.net/~ubuntu-mozilla-daily/+archive/ubuntu/firefox-aurora), so it looks like this is the way to do it :) Note that this method will replace your current Firefox installation. If you want to run "regular" Firefox and Developer Edition side-by-side you will have to [install DE separately](https://askubuntu.com/questions/548003). I don't know of a PPA for this. (Unless you have a specific requirement to run them side-by-side, this shouldn't be necessary.)
You can actually get firefox's built-in auto-update to work if you have manually installed it. Just set the ownership and permissions so your regular user can write to the install directory. Assuming your user belongs to the `sudo` group and firefox has been installed in `/opt/firefox-dev`: ``` sudo chown -R root:sudo /opt/firefox-dev sudo chmod -R g+rwX /opt/firefox-dev ``` You may have to restart it.
169,360
**Plot Details/Summary** Another one where I have only sketchy memories of the tale, I fear. The setting for this one is the near future (from the writer's perspective, which I think was the 1970s). Man's reached a point where bloodshed and loss of life are no longer necessary to settle conflicts. Instead, all disputes are settled through an annual combat held on the surface of the moon, using the best combat machines each nation can come up with. The protagonist, as I recall, is an engineer for the Americans. He recollects past conflicts, and the circumstances for this years fracas. Much of the combat is told from his observers' perspective. The actual conflict is a rather clever affair, with a description of each team's designs and all the tricks and gee-whiz things they built into them. The protagonist's team manages to prevail, when they managed to use an attack as a feint, with the real attack being a swarm of microscopic machines (they did not use the term nanites) that destroyed the opposing machine from the inside. **Timeframe/Other Details** I think this one dates from the 1970s. I don't think it more recent, given my recollections of when I read it, and also the technology descriptions they used in it. There is an outside chance that the combat is not between rival nations, but rival corporations. That would change the premise of "man evolving beyond bloodshed", of course. I think it's nations fighting, though. I am almost 100% certain this was in a sci-fi magazine, not an anthology.
2017/09/10
[ "https://scifi.stackexchange.com/questions/169360", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/69621/" ]
["A Short History of World War LXXVIII"](https://www.isfdb.org/cgi-bin/title.cgi?50251), a short story by [Roy L. Prosterman](https://www.isfdb.org/cgi-bin/ea.cgi?12378) in [*Analog Science Fiction/Science Fact*, April 1977](https://www.isfdb.org/cgi-bin/pl.cgi?57054+c). **Man's reached a point where bloodshed and loss of life are no longer necessary to settle conflicts. Instead, all disputes are settled through an annual combat held on the surface of the moon, using the best combat machines each nation can come up with.** > > "But, after the indescribable ravages of World War III, it had become clear that human survival demanded a wholly different approach to conflict. Fortunately, perhaps essentially, this realization coincided with the development of machines that were far superior in every way to human operators in carrying out acts of destruction. Even two hundred years ago"—here sections from an ancient communication called "Newsweek" and made, apparently, of cloth or some similar substance, flashed upon the screen—"technicians were talking about the possibility of an 'Automated Battlefield'." Here, computer animation took over, showing a series of still rather primitive machines confronting one another on a field. There were explosions, grindings, and tearings. Drones hummed through the air. Many of the machines disappeared. There were no humans present. > > > [. . . .] > > > > **The protagonist's team manages to prevail, when they managed to use an attack as a feint, with the real attack being a swarm of microscopic machines (they did not use the term nanites) that destroyed the opposing machine from the inside.** > > What won it for the Usa, as we later discovered, were the "brain eaters." > > > > **I am almost 100% certain this was in a sci-fi magazine, not an anthology.** As far as the ISFDB knows, the story has never been reprinted.
I read this one or something a whole lot like it, I think in a 1970s edition of Analog. The version I read was a "war" between "Usa" (that one I remember) and Arabia (although I don't think it was called that). Two robots fight it out on the moon, Usa wins (of course). The kicker line was that oil prices would remain lower for a while as a result. I believe the title was something along the lines of "World War 23", although my attempts to track it down in Google for all numbers between 18 and 25 always returned something about WWII.
47,307,950
I'm completely new to Assembly and looking to confirm where, in the following statements, I have a misunderstanding and need to be corrected. **The stack pointer** (`ESP`) refers to the top (lowest memory address) of the stack. **The base Pointer** (`EBP`) is used for temporarily storing various memory addresses when building a stack frame. It normally holds the highest memory address of the current stack frame. **The instruction pointer** (`EIP`) refers to the memory address of a line of code in the text (code) segment of memory Once something has been pushed to the stack, it can't be changed in-place. ie. If we `PUSH EBP` to the stack, we are pushing the current value of `EBP`, not some kind of reference or pointer to it. We can't then change that value in-place. Arguments being passed into a function are generally moved into an address space which is an offset of the stack pointer. ie. `[ESP-12]`. When a function is called (using `CALL`), the following occurs: 1. The return address is added to the stack (the memory of the address immediately following the current `EIP` so we know where to return to after the called function has completed 2. The saved frame pointer is added to the stack, which is normally the stack pointer of the stack frame of the calling function 3. We would then move into the prologue of the called function Thanks. I'm trying to get my head around this stuff.
2017/11/15
[ "https://Stackoverflow.com/questions/47307950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2386745/" ]
> > Arguments being passed into a function are generally moved into an address space which is an offset of the stack pointer. ie. [ESP-12]. > > > Often arguments are pushed on the stack, **before** the call. ``` push paramA ; ( some 32bit value, register, whatever ) push paramB call myFunct ``` This leads to the following stack content: ``` --------------- | paramA | --------------- | paramB | --------------- | return addr | <-- ESP --------------- ``` Since the return address (pushed by the `call` ) is 4 bytes, the parameters for the function are at `[ESP+4]` and `[ESP+8]`. If your function adds a stack frame, usually you do ``` myFunct: push EBP mov EBP, ESP ``` Now the stack looks like this: ``` --------------- | paramA | --------------- | paramB | --------------- | return addr | --------------- | saved EBP | <-- EBP, ESP --------------- ``` and the parameters are at `[EBP+8]` and `[EBP+12]`, even if you push more values (or add some place for local variables) since `EBP` is not changing anymore: ``` myFunct: push EBP mov EBP, ESP sub ESP, 12 ; make room for 3 32bit local variables mov eax, [EBP+8] ; access one of the parameters mov [EBP-4], eax ; save it in local variable #1 rel | rel | to | to | ESP | EBP | ----|------|-------------- +24 | +12 | paramA | | |-------------- +20 | +8 | paramB | | |-------------- +16 | +4 | return addr | | |-------------- +12 | | saved EBP | <-- EBP (is fixed here for now) | |--------------- +8 | -4 | local#1 | | |--------------- +4 | -8 | local#2 | | | --------------- 0 | -12 | local#3 | <--- ESP (keeps growing, by pushing, calling etc) --------------- ``` The local variables are at `[EBP-4]`, `[EBP-8]`, `[EBP-12]` etc. The return Address is at `[EBP+4]` Note: As you can see, it is possible * to access by `ESP` (then you do **not** need a frame-pointer, but then you need to keep track of how much data you pushed, to "find" the parameters and variables ) * or by `EBP` (which ofc adds some overhead). In many functions, the frame pointer is not needed at all, and optimized away by compilers.
> > Once something has been pushed to the stack, it can't be changed in-place. ie. If we PUSH EBP to the stack, we are pushing the current value of EBP, not some kind of reference or pointer to it. **We can't then change that value in-place.** > > > Sure you can. Stack is ordinary computer memory, there's nothing special about it, except that 99% of code expects valid (read+write access) memory address in `esp` and some reserved space, so it can push some local things to it, as needed. ``` push ebp ; store current value in ebp to stack ``` Is almost equivalent to: ``` sub esp,4 mov [esp],ebp ``` (but the second variant will also modify flags and it is somewhat less atomic) Now you can overwrite it with anything else, like: ``` mov [esp],eax ; overwrite the old_ebp value with current_eax value ``` > > reference or pointer to it > > > Well, there's no way to have some kind of reference or pointer to the `ebp` register, it's a register in CPU, only 32 bits (32x 0 or 1 value) and it has no address, you can work with it only by its name `ebp` in instructions, which allow usage of it in their encoding. Upon `push ebp` those 32 bits (and no other info) are copied into memory (which is then holding those 0/1 values copied in its own 32 bits = 4 bytes). There's no information where the value in memory was written from, when and by what instruction, only value bits are stored.
248,580
I'm having a problem, creating a fixed-size overall panel for a touchscreen GUI application that has to take up the entire screen. In a nutshell, the touchscreen is 800 x 600 pixels, and therefore I want the main GUI panel to be that size. When I start a new GUI project in NetBeans, I set the properties of the main panel for min/max/preferred size to 800 x 600, and the panel within the 'Design' view changes size. However, when I launch the app, it is resized to the original default size. Adding this code after initComponents() does not help: ``` this.mainPanel.setSize(new Dimension(800,600)); this.mainPanel.setMaximumSize(new Dimension(800,600)); this.mainPanel.setMinimumSize(new Dimension(800,600)); this.mainPanel.repaint(); ``` I've peeked into all of the resource files and cannot seem to find values that would override these (which seems somewhat impossible anyway, given that I'm setting them after initComponents() does its work). I'm using the FreeDesign layout, because I wanted complete control over where I put things. I suspect the layout manager is resizing things based upon how many widgets I have on the screen, because different prototyped screens come in at differing sizes. Help is appreciated!
2008/10/29
[ "https://Stackoverflow.com/questions/248580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Have you tried [java full screen mode](http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html)?
I use this method to complete the task, not sure if its the best and you need to wait calling it until the frame is actually on the screen. ``` protected void growBig() { int screenWidth = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width; int screenHeight = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height; Rectangle rectangle = getFrame().getBounds(); rectangle.setSize(screenWidth, screenHeight); getFrame().setBounds(0, 0, screenWidth, screenHeight); getFrame().setSize(screenWidth, screenHeight); getFrame().doLayout(); getFrame().validate(); updateUI(); } ```
248,580
I'm having a problem, creating a fixed-size overall panel for a touchscreen GUI application that has to take up the entire screen. In a nutshell, the touchscreen is 800 x 600 pixels, and therefore I want the main GUI panel to be that size. When I start a new GUI project in NetBeans, I set the properties of the main panel for min/max/preferred size to 800 x 600, and the panel within the 'Design' view changes size. However, when I launch the app, it is resized to the original default size. Adding this code after initComponents() does not help: ``` this.mainPanel.setSize(new Dimension(800,600)); this.mainPanel.setMaximumSize(new Dimension(800,600)); this.mainPanel.setMinimumSize(new Dimension(800,600)); this.mainPanel.repaint(); ``` I've peeked into all of the resource files and cannot seem to find values that would override these (which seems somewhat impossible anyway, given that I'm setting them after initComponents() does its work). I'm using the FreeDesign layout, because I wanted complete control over where I put things. I suspect the layout manager is resizing things based upon how many widgets I have on the screen, because different prototyped screens come in at differing sizes. Help is appreciated!
2008/10/29
[ "https://Stackoverflow.com/questions/248580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Have you tried [java full screen mode](http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html)?
I'm not sure how your touchscreen device works. But if you use Netbeans preview your panel is put in some outer container like JFrame/JWindow. And just maybe you set the frame to 800x600. If so, then the problem might be that the frame eats a few pixels for its own border, leaving your panel size < 800x600. And in that case your panel will be unable to use your min/max settings and revert to default sizes.
20,407,906
I'm trying to get objects to "slide in" from the bottom of the screen, but since I can't get the screen height as a unit in CSS, I'm trying to do this with media queries, like so: ``` @media(max-height:500px) { @keyframe slideUp { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } } @media(max-height:750px) { @keyframe slideUp { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } } /* etc. */ ``` This doesn't work (it uses the first version of `slideUp` regardless of height), so I assume keyframes, once defined, cannot be overwritten or reassigned based on media queries? Is there any way to achieve this effect (short of having many different keyframe setups and using a media query to assign the appropriate one to the class)?
2013/12/05
[ "https://Stackoverflow.com/questions/20407906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/221814/" ]
A way of doing a slide up animation regardless of screen or element height is to use `position: fixed`: ``` .box { position: fixed; animation: slideUp 1s forwards; } @keyframes slideUp { from { top: 100%; } to { top: 0; } } ``` **Demo:** <http://jsfiddle.net/myajouri/Kvtd2/> If you want to slide relative to a parent element and not the viewport, use `position: absolute` instead.
If you have to use `translate3d` to get hardware acceleration on mobile devices (as you mentioned), and given that you can't use at-rules inside `@media`: You could define one `@keyframes` with large `translateX` (say `5000px`) and change the `animation-duration` based on the screen height to ensure the speed is more or less the same across the different heights. I would also define height ranges (`max-height` and `min-height`) as opposed to upper limits (`max-height` only) to prevent unwanted style overrides. ``` @keyframes slideUp { from { transform: translate3d(0,5000px,0); } to { transform: translate3d(0,0,0); } } .box { animation: slideUp 5s forwards; } @media (min-height: 0) and (max-height: 500px) { .box { animation-duration: 0.5s; } } @media (min-height: 501px) and (max-height: 750px) { .box { animation-duration: 0.75s; } } @media (min-height: 751px) and (max-height: 1000px) { .box { animation-duration: 1s; } } ``` **DEMO:** <http://jsfiddle.net/myajouri/9xLyf/>
20,407,906
I'm trying to get objects to "slide in" from the bottom of the screen, but since I can't get the screen height as a unit in CSS, I'm trying to do this with media queries, like so: ``` @media(max-height:500px) { @keyframe slideUp { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } } @media(max-height:750px) { @keyframe slideUp { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } } /* etc. */ ``` This doesn't work (it uses the first version of `slideUp` regardless of height), so I assume keyframes, once defined, cannot be overwritten or reassigned based on media queries? Is there any way to achieve this effect (short of having many different keyframe setups and using a media query to assign the appropriate one to the class)?
2013/12/05
[ "https://Stackoverflow.com/questions/20407906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/221814/" ]
I don't know why no one else has suggested this, but instead of setting the keyframes in the media query you can set the animation in the media query. ``` @media(max-height:500px) { #selectorGroup { animation: slideUp500 1s forwards; } } @media(max-height:750px) { #selectorGroup { animation: slideUp750 1s forwards; } } @keyframes slideUp500 { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } @keyframes slideUp750 { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } ```
A way of doing a slide up animation regardless of screen or element height is to use `position: fixed`: ``` .box { position: fixed; animation: slideUp 1s forwards; } @keyframes slideUp { from { top: 100%; } to { top: 0; } } ``` **Demo:** <http://jsfiddle.net/myajouri/Kvtd2/> If you want to slide relative to a parent element and not the viewport, use `position: absolute` instead.
20,407,906
I'm trying to get objects to "slide in" from the bottom of the screen, but since I can't get the screen height as a unit in CSS, I'm trying to do this with media queries, like so: ``` @media(max-height:500px) { @keyframe slideUp { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } } @media(max-height:750px) { @keyframe slideUp { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } } /* etc. */ ``` This doesn't work (it uses the first version of `slideUp` regardless of height), so I assume keyframes, once defined, cannot be overwritten or reassigned based on media queries? Is there any way to achieve this effect (short of having many different keyframe setups and using a media query to assign the appropriate one to the class)?
2013/12/05
[ "https://Stackoverflow.com/questions/20407906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/221814/" ]
Nowadays you can solve this using native CSS variables. In your case: ``` @media(max-height:500px) { :root { --slide-up-y: 500px } } @media(max-height:750px) { :root { --slide-up-y: 750px } } @keyframes slideUp { 0% { transform: translate3d(0,var(--slide-up-y),0); } 100% { transform: translate3d(0,0,0); } } } ```
A way of doing a slide up animation regardless of screen or element height is to use `position: fixed`: ``` .box { position: fixed; animation: slideUp 1s forwards; } @keyframes slideUp { from { top: 100%; } to { top: 0; } } ``` **Demo:** <http://jsfiddle.net/myajouri/Kvtd2/> If you want to slide relative to a parent element and not the viewport, use `position: absolute` instead.
20,407,906
I'm trying to get objects to "slide in" from the bottom of the screen, but since I can't get the screen height as a unit in CSS, I'm trying to do this with media queries, like so: ``` @media(max-height:500px) { @keyframe slideUp { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } } @media(max-height:750px) { @keyframe slideUp { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } } /* etc. */ ``` This doesn't work (it uses the first version of `slideUp` regardless of height), so I assume keyframes, once defined, cannot be overwritten or reassigned based on media queries? Is there any way to achieve this effect (short of having many different keyframe setups and using a media query to assign the appropriate one to the class)?
2013/12/05
[ "https://Stackoverflow.com/questions/20407906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/221814/" ]
I don't know why no one else has suggested this, but instead of setting the keyframes in the media query you can set the animation in the media query. ``` @media(max-height:500px) { #selectorGroup { animation: slideUp500 1s forwards; } } @media(max-height:750px) { #selectorGroup { animation: slideUp750 1s forwards; } } @keyframes slideUp500 { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } @keyframes slideUp750 { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } ```
If you have to use `translate3d` to get hardware acceleration on mobile devices (as you mentioned), and given that you can't use at-rules inside `@media`: You could define one `@keyframes` with large `translateX` (say `5000px`) and change the `animation-duration` based on the screen height to ensure the speed is more or less the same across the different heights. I would also define height ranges (`max-height` and `min-height`) as opposed to upper limits (`max-height` only) to prevent unwanted style overrides. ``` @keyframes slideUp { from { transform: translate3d(0,5000px,0); } to { transform: translate3d(0,0,0); } } .box { animation: slideUp 5s forwards; } @media (min-height: 0) and (max-height: 500px) { .box { animation-duration: 0.5s; } } @media (min-height: 501px) and (max-height: 750px) { .box { animation-duration: 0.75s; } } @media (min-height: 751px) and (max-height: 1000px) { .box { animation-duration: 1s; } } ``` **DEMO:** <http://jsfiddle.net/myajouri/9xLyf/>
20,407,906
I'm trying to get objects to "slide in" from the bottom of the screen, but since I can't get the screen height as a unit in CSS, I'm trying to do this with media queries, like so: ``` @media(max-height:500px) { @keyframe slideUp { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } } @media(max-height:750px) { @keyframe slideUp { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } } /* etc. */ ``` This doesn't work (it uses the first version of `slideUp` regardless of height), so I assume keyframes, once defined, cannot be overwritten or reassigned based on media queries? Is there any way to achieve this effect (short of having many different keyframe setups and using a media query to assign the appropriate one to the class)?
2013/12/05
[ "https://Stackoverflow.com/questions/20407906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/221814/" ]
Long time since this question was asked. But I'm seeing that nobody has answered the solution that I'll give you, and this one, in my opinion, is easier than creating different `media-queries` for different screen sizes. @myajouri proposed you to use a `fixed` position and you discarded this solution because you need to use 3d transforms to get hardware acceleration. But you can still use 3d transforms with a fixed position. With `CSS` transformations, if you use percentages, they will be relative to the size of the element itself. This will allow you to move the element from outside the screen no matter what size it has, so, only one keyframe animation is needed. Check the next snippet: ```css body { margin: 0; padding: 0; } .element { animation: slideUp 1s ease-in-out infinite alternate; background: #CCC; border: 5px solid gray; box-sizing: border-box; height: 100%; position: fixed; width: 100%; } @keyframes slideUp { from { transform: translate3d(0, 100%, 0); } to { transform: translate3d(0, 0, 0); } } ``` ```html <div class="element" /> ```
If you have to use `translate3d` to get hardware acceleration on mobile devices (as you mentioned), and given that you can't use at-rules inside `@media`: You could define one `@keyframes` with large `translateX` (say `5000px`) and change the `animation-duration` based on the screen height to ensure the speed is more or less the same across the different heights. I would also define height ranges (`max-height` and `min-height`) as opposed to upper limits (`max-height` only) to prevent unwanted style overrides. ``` @keyframes slideUp { from { transform: translate3d(0,5000px,0); } to { transform: translate3d(0,0,0); } } .box { animation: slideUp 5s forwards; } @media (min-height: 0) and (max-height: 500px) { .box { animation-duration: 0.5s; } } @media (min-height: 501px) and (max-height: 750px) { .box { animation-duration: 0.75s; } } @media (min-height: 751px) and (max-height: 1000px) { .box { animation-duration: 1s; } } ``` **DEMO:** <http://jsfiddle.net/myajouri/9xLyf/>
20,407,906
I'm trying to get objects to "slide in" from the bottom of the screen, but since I can't get the screen height as a unit in CSS, I'm trying to do this with media queries, like so: ``` @media(max-height:500px) { @keyframe slideUp { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } } @media(max-height:750px) { @keyframe slideUp { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } } /* etc. */ ``` This doesn't work (it uses the first version of `slideUp` regardless of height), so I assume keyframes, once defined, cannot be overwritten or reassigned based on media queries? Is there any way to achieve this effect (short of having many different keyframe setups and using a media query to assign the appropriate one to the class)?
2013/12/05
[ "https://Stackoverflow.com/questions/20407906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/221814/" ]
Nowadays you can solve this using native CSS variables. In your case: ``` @media(max-height:500px) { :root { --slide-up-y: 500px } } @media(max-height:750px) { :root { --slide-up-y: 750px } } @keyframes slideUp { 0% { transform: translate3d(0,var(--slide-up-y),0); } 100% { transform: translate3d(0,0,0); } } } ```
If you have to use `translate3d` to get hardware acceleration on mobile devices (as you mentioned), and given that you can't use at-rules inside `@media`: You could define one `@keyframes` with large `translateX` (say `5000px`) and change the `animation-duration` based on the screen height to ensure the speed is more or less the same across the different heights. I would also define height ranges (`max-height` and `min-height`) as opposed to upper limits (`max-height` only) to prevent unwanted style overrides. ``` @keyframes slideUp { from { transform: translate3d(0,5000px,0); } to { transform: translate3d(0,0,0); } } .box { animation: slideUp 5s forwards; } @media (min-height: 0) and (max-height: 500px) { .box { animation-duration: 0.5s; } } @media (min-height: 501px) and (max-height: 750px) { .box { animation-duration: 0.75s; } } @media (min-height: 751px) and (max-height: 1000px) { .box { animation-duration: 1s; } } ``` **DEMO:** <http://jsfiddle.net/myajouri/9xLyf/>
20,407,906
I'm trying to get objects to "slide in" from the bottom of the screen, but since I can't get the screen height as a unit in CSS, I'm trying to do this with media queries, like so: ``` @media(max-height:500px) { @keyframe slideUp { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } } @media(max-height:750px) { @keyframe slideUp { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } } /* etc. */ ``` This doesn't work (it uses the first version of `slideUp` regardless of height), so I assume keyframes, once defined, cannot be overwritten or reassigned based on media queries? Is there any way to achieve this effect (short of having many different keyframe setups and using a media query to assign the appropriate one to the class)?
2013/12/05
[ "https://Stackoverflow.com/questions/20407906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/221814/" ]
I don't know why no one else has suggested this, but instead of setting the keyframes in the media query you can set the animation in the media query. ``` @media(max-height:500px) { #selectorGroup { animation: slideUp500 1s forwards; } } @media(max-height:750px) { #selectorGroup { animation: slideUp750 1s forwards; } } @keyframes slideUp500 { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } @keyframes slideUp750 { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } ```
Long time since this question was asked. But I'm seeing that nobody has answered the solution that I'll give you, and this one, in my opinion, is easier than creating different `media-queries` for different screen sizes. @myajouri proposed you to use a `fixed` position and you discarded this solution because you need to use 3d transforms to get hardware acceleration. But you can still use 3d transforms with a fixed position. With `CSS` transformations, if you use percentages, they will be relative to the size of the element itself. This will allow you to move the element from outside the screen no matter what size it has, so, only one keyframe animation is needed. Check the next snippet: ```css body { margin: 0; padding: 0; } .element { animation: slideUp 1s ease-in-out infinite alternate; background: #CCC; border: 5px solid gray; box-sizing: border-box; height: 100%; position: fixed; width: 100%; } @keyframes slideUp { from { transform: translate3d(0, 100%, 0); } to { transform: translate3d(0, 0, 0); } } ``` ```html <div class="element" /> ```
20,407,906
I'm trying to get objects to "slide in" from the bottom of the screen, but since I can't get the screen height as a unit in CSS, I'm trying to do this with media queries, like so: ``` @media(max-height:500px) { @keyframe slideUp { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } } @media(max-height:750px) { @keyframe slideUp { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } } /* etc. */ ``` This doesn't work (it uses the first version of `slideUp` regardless of height), so I assume keyframes, once defined, cannot be overwritten or reassigned based on media queries? Is there any way to achieve this effect (short of having many different keyframe setups and using a media query to assign the appropriate one to the class)?
2013/12/05
[ "https://Stackoverflow.com/questions/20407906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/221814/" ]
I don't know why no one else has suggested this, but instead of setting the keyframes in the media query you can set the animation in the media query. ``` @media(max-height:500px) { #selectorGroup { animation: slideUp500 1s forwards; } } @media(max-height:750px) { #selectorGroup { animation: slideUp750 1s forwards; } } @keyframes slideUp500 { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } @keyframes slideUp750 { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } ```
Nowadays you can solve this using native CSS variables. In your case: ``` @media(max-height:500px) { :root { --slide-up-y: 500px } } @media(max-height:750px) { :root { --slide-up-y: 750px } } @keyframes slideUp { 0% { transform: translate3d(0,var(--slide-up-y),0); } 100% { transform: translate3d(0,0,0); } } } ```
20,407,906
I'm trying to get objects to "slide in" from the bottom of the screen, but since I can't get the screen height as a unit in CSS, I'm trying to do this with media queries, like so: ``` @media(max-height:500px) { @keyframe slideUp { 0% { transform: translate3d(0,500px,0); } 100% { transform: translate3d(0,0,0); } } } @media(max-height:750px) { @keyframe slideUp { 0% { transform: translate3d(0,750px,0); } 100% { transform: translate3d(0,0,0); } } } /* etc. */ ``` This doesn't work (it uses the first version of `slideUp` regardless of height), so I assume keyframes, once defined, cannot be overwritten or reassigned based on media queries? Is there any way to achieve this effect (short of having many different keyframe setups and using a media query to assign the appropriate one to the class)?
2013/12/05
[ "https://Stackoverflow.com/questions/20407906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/221814/" ]
Nowadays you can solve this using native CSS variables. In your case: ``` @media(max-height:500px) { :root { --slide-up-y: 500px } } @media(max-height:750px) { :root { --slide-up-y: 750px } } @keyframes slideUp { 0% { transform: translate3d(0,var(--slide-up-y),0); } 100% { transform: translate3d(0,0,0); } } } ```
Long time since this question was asked. But I'm seeing that nobody has answered the solution that I'll give you, and this one, in my opinion, is easier than creating different `media-queries` for different screen sizes. @myajouri proposed you to use a `fixed` position and you discarded this solution because you need to use 3d transforms to get hardware acceleration. But you can still use 3d transforms with a fixed position. With `CSS` transformations, if you use percentages, they will be relative to the size of the element itself. This will allow you to move the element from outside the screen no matter what size it has, so, only one keyframe animation is needed. Check the next snippet: ```css body { margin: 0; padding: 0; } .element { animation: slideUp 1s ease-in-out infinite alternate; background: #CCC; border: 5px solid gray; box-sizing: border-box; height: 100%; position: fixed; width: 100%; } @keyframes slideUp { from { transform: translate3d(0, 100%, 0); } to { transform: translate3d(0, 0, 0); } } ``` ```html <div class="element" /> ```
42,289,896
How do I get the text of a richtextbox? I've searched for so long and I can't find an answer! Why isn't there something like `richTextBox1.getText()`?
2017/02/17
[ "https://Stackoverflow.com/questions/42289896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6911249/" ]
You can write directly `richTextBox1.Text`
Please try this: ``` string text = richTextBox1.Text().Trim(); ```
8,496,086
Background Schema: ``` class Checkpoint(db.Model): id = db.Column(db.Integer, primary_key=True) creator = db.Column(db.Integer, db.ForeignKey('user.id')) name = db.Column(db.String(255)) description = db.Column(db.String(255), nullable=True) price = db.Column(db.Float, nullable=True) expiry = db.Column(db.DateTime, nullable=True) date_created = db.Column(db.DateTime) type = db.Column(db.String(255)) image = db.Column(db.String(255)) longitude = db.Column(db.Float) latitude = db.Column(db.Float) class UserCheckpoint(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship("User") checkpoint_id = db.Column(db.Integer, db.ForeignKey('checkpoint.id')) checkpoint = db.relationship("Checkpoint") class User(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255)) facebook_info = db.Column(db.String(255), db.ForeignKey('facebook_user.id')) facebook_user = db.relationship("FacebookUser") class FriendConnection(db.Model): id = db.Column(db.Integer, primary_key=True) fb_user_from = db.Column(db.String(255), db.ForeignKey('facebook_user.id')) fb_user_to = db.Column(db.String(255), db.ForeignKey('facebook_user.id')) class FacebookUser(db.Model): id = db.Column(db.String(255), primary_key=True) name = db.Column(db.String(255)) first_name = db.Column(db.String(255), nullable=True) middle_name = db.Column(db.String(255), nullable=True) last_name = db.Column(db.String(255), nullable=True) gender = db.Column(db.String(255), nullable=True) username = db.Column(db.String(255), nullable=True) link = db.Column(db.String(255), nullable=True) ``` I have a user, and as you can see, each user has a Facebook profile, as well as a table depicting inter-facebook-profile friendships. So given the user, the user would have a list of Facebook friends. I would like to get all UserCheckpoints that belong either to the user or his friends, with a given Checkpoint condition: ``` coord_conditions = and_(Checkpoint.longitude <= longitude + exp_no, Checkpoint.longitude >= longitude - exp_no, Checkpoint.latitude <= latitude + exp_no, Checkpoint.latitude >= latitude - exp_no, ) ``` How can I do this using the ORM from SQLAlchemy? Thanks! Summary: How to select UserCheckpoints given that the user\_id belong to a list of friends/self; while UserCheckpoint.checkpoint has a set of conditions to fulfill.
2011/12/13
[ "https://Stackoverflow.com/questions/8496086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/118644/" ]
Each relation has two methods to defined conditions on related objects: `.has()` for single referred object and `.any()` for collections. These methods allow straightforward translation of your task to SQLAlchemy expression. Let's add missing relations to `FacebookUser`: ``` class FacebookUser(Model): # Definitions from question are here user = relationship(User, uselist=False) friends = relationship('FacebookUser', secondary=FriendConnection.__table__, primaryjoin=(id==FriendConnection.fb_user_from), secondaryjoin=(FriendConnection.fb_user_to==id)) ``` I've defined `FacebookUser.user` assuming one-to-one relation (which is usually supplemented with unique constraint on the foreign key column). Just remove `uselist=False` and adjust name if you allow several users being connected to one facebook account. A shorter definition of your condition for coordinates: ``` coord_conditions = Checkpoint.longitude.between(longitude - exp_no, longitude + exp_no) & \ Checkpoint.latitude.between(latitude - exp_no, latitude + exp_no) ``` This condition is definitely wrong even for approximation (-179.9° and 179.9° are very close, while the difference is huge), but this is not main topic of the question. A condition for users of interest (user with id equal to `user_id` and his friends): ``` user_cond = (User.id==user_id) | \ User.facebook_user.has( FacebookUser.friends.any(FacebookUser.user.has(id=user_id))) ``` Now the query is quite simple: ``` session.query(UserCheckpoint).filter( UserCheckpoint.checkpoint.has(coord_conditions) & \ UserCheckpoint.user.has(user_cond)) ``` Unless you have (or expect) performance issues, I'd suggest avoid optimizing it at the cost of readability.
Basically your query can be split in two parts: 1. Given the `user_id`, create a list of users which will contain the user herself as well as all direct friends 2. Given the list of users from 1., get all `UserCheckpoint` whose `Checkpoint` would satisfy the criteria. **Not tested code:** ``` # get direct user for given user_id u1 = (session.query(User.id.label("user_1_id"), User.id.label("user_id")) ) # get friends of the user in one direction (from other user to this one) User2 = aliased(User) FacebookUser2 = aliased(FacebookUser) u2 = (session.query(User2.id.label("user_1_id"), User.id.label("user_id")). join(FacebookUser2, User2.facebook_info == FacebookUser2.id). join(FriendConnection, FacebookUser2.id == FriendConnection.fb_user_from). join(FacebookUser, FacebookUser.id == FriendConnection.fb_user_to). join(User, User.facebook_info == FacebookUser.id) ) # get friends of the user in other direction (from this user to the other) User2 = aliased(User) FacebookUser2 = aliased(FacebookUser) u3 = (session.query(User2.id.label("user_1_id"), User.id.label("user_id")). join(FacebookUser2, User2.facebook_info == FacebookUser2.id). join(FriendConnection, FacebookUser2.id == FriendConnection.fb_user_to). join(FacebookUser, FacebookUser.id == FriendConnection.fb_user_from). join(User, User.facebook_info == FacebookUser.id) ) # create a union to have all pairs (me_or_friend_id, user_id) u_all = union_all(u1, u2, u3) # **edit-1: added alias ** u_all = u_all.alias("user_list_view") # final query which adds filters requirested (by user_id and the checkpoint condition) q = (session.query(UserCheckpoint). join(Checkpoint).filter(coord_conditions). join(u_all, UserCheckpoint.user_id == u_all.c.user_1_id). filter(u_all.c.user_id == user_id) ) for u_cp in q.all(): print u_cp ``` --- **Note**, that you could simplify the query somewhat if you defined more `relationships` in your model and then can remove some `primaryjoin` conditions from `join` clauses.
20,390,148
I've been trying to search for an alternative for browsers that have disabled cookies in their browser and forms that require the antiforgerytoken for validation. How should a case like this be handled? Any suggestions or alternatives to preventing CSRF in ASP.Net MVC forms would be greatly appreciated. Thanks you!
2013/12/05
[ "https://Stackoverflow.com/questions/20390148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1930778/" ]
You can create your own CUSTOM ANTIFORGERYTOKEN FILTER for more details check the links... <http://forums.asp.net/t/1938599.aspx> <http://www.prideparrot.com/blog/archive/2012/7/securing_all_forms_using_antiforgerytoken>
There are a number of alternatives to using AntiForgeryTokens stored in session as part of the Synchroniser Token Pattern. One method gaining traction is the [Encrypted Token Pattern](http://insidethecpu.wordpress.com/2013/09/23/encrypted-token-pattern/), implemented by a Framework called ARMOR. The premise here is that you need neither Session nor cookies in order to maintain CSRF protection in a stateless manner, which won't be interrupted by browser settings, particularly the disabling of cookies.
62,087,540
**I'm working with SQL queries in Snowflake.** I'm able to work in the browser (chrome), or on SQLWorkbenchJ. I'm comfortable with both, but prefer the browser. I'm working with moderately large numbers, up into the hundreds of billions (10^8), so it would be really helpful if I could **make the program print my numbers with comma separation** for the thousands (e.g. 12,345,678,901.00 vs. 12345678901.00). I've looked into the documentation on format models here <https://docs.snowflake.com/en/sql-reference/sql-format-models.html> but I can't see an option to output in the style I'm looking for. Even besides that, I would really prefer to **implement this as a configuration to the interface** itself rather than code I apply to my queries.
2020/05/29
[ "https://Stackoverflow.com/questions/62087540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13641962/" ]
The [numeric format models](https://docs.snowflake.com/en/sql-reference/sql-format-models.html#numeric-format-models) appears to cover your need via the `9` (nine), `,` (comma), and `.` (period) symbols. Quoting some relevant portions from the documentation: > > `9`: Position for a digit; leading/trailing zeros are replaced with blank spaces. > > > `0`: Position for a digit; leading/trailing zeros are explicitly printed. > > > `.` (period): Decimal fraction separator; always printed as a period. > > > `,` (comma): Digit group separator; printed as a comma or blank space. > > > [...] > > > The digit group separator `,` (comma) or `G` results in the corresponding group separator character being printed if the number is big enough so the digits are on the both sides of group separator. An example of a format model useful for printing currency sums would be 999,999.00. > > > Here are some adapted examples demonstrating the required format: ```sql SELECT to_varchar(123.21, '999,999,999,999.00'); SELECT to_varchar(12345.00, '999,999,999,999.00'); SELECT to_varchar(12345678, '999,999,999,999.00'); SELECT to_varchar(12345678901, '999,999,999,999.00'); SELECT to_varchar(12345678901.59, '999,999,999,999.00'); ```
Looks like your wish has been partially granted! In Snowflake's new web interface (they call it [Snowsight](https://docs.snowflake.com/en/user-guide/ui-snowsight.html)), you can choose to display numbers using commas as the separator for thousands. It only affects the display in the UI though - it doesn't work for exporting data (which shouldn't be a problem, because exported data shouldn't be formatted - that's something excel or other can take care of). [![enter image description here](https://i.stack.imgur.com/rbVqM.png)](https://i.stack.imgur.com/rbVqM.png)
7,887,865
When I try to send a HTTP request like `GET /` I can't reach to index.html or index.php. The host brings the page `/cgi-sys/defaultwebpage.cgi`. When I try `GET /index.html` This time i get a 404 not found error. It says `(none)/index.html` not found. What could be the reason?
2011/10/25
[ "https://Stackoverflow.com/questions/7887865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/663229/" ]
There is no `index.html` in the web root. The server has been configured to redirect requests for `/` to `/cgi-sys/defaultwebpage.cgi` instead, and you should honor that.
If you are using apache, check if you set your [DirectoryIndex](http://httpd.apache.org/docs/2.0/mod/mod_dir.html) value in `httpd.conf` correct. For example: ``` DirectoryIndex index.html ```
7,887,865
When I try to send a HTTP request like `GET /` I can't reach to index.html or index.php. The host brings the page `/cgi-sys/defaultwebpage.cgi`. When I try `GET /index.html` This time i get a 404 not found error. It says `(none)/index.html` not found. What could be the reason?
2011/10/25
[ "https://Stackoverflow.com/questions/7887865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/663229/" ]
There is no `index.html` in the web root. The server has been configured to redirect requests for `/` to `/cgi-sys/defaultwebpage.cgi` instead, and you should honor that.
I thought I had the same problem until looked at my page via anonymous access service (like [this](http://eu.amnotseen.com/)). Actually the problem was with my DNS cache.
7,887,865
When I try to send a HTTP request like `GET /` I can't reach to index.html or index.php. The host brings the page `/cgi-sys/defaultwebpage.cgi`. When I try `GET /index.html` This time i get a 404 not found error. It says `(none)/index.html` not found. What could be the reason?
2011/10/25
[ "https://Stackoverflow.com/questions/7887865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/663229/" ]
Looks like that `DocumentRoot` in the `httpd.conf` file is pointing to a different directory instead of where your `index.html` is.
If you are using apache, check if you set your [DirectoryIndex](http://httpd.apache.org/docs/2.0/mod/mod_dir.html) value in `httpd.conf` correct. For example: ``` DirectoryIndex index.html ```
7,887,865
When I try to send a HTTP request like `GET /` I can't reach to index.html or index.php. The host brings the page `/cgi-sys/defaultwebpage.cgi`. When I try `GET /index.html` This time i get a 404 not found error. It says `(none)/index.html` not found. What could be the reason?
2011/10/25
[ "https://Stackoverflow.com/questions/7887865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/663229/" ]
Looks like that `DocumentRoot` in the `httpd.conf` file is pointing to a different directory instead of where your `index.html` is.
I thought I had the same problem until looked at my page via anonymous access service (like [this](http://eu.amnotseen.com/)). Actually the problem was with my DNS cache.
34,122,747
I am making a browser-based video game. In the game, objects have a graphic and a title bar. The title bar holds their name, the spell they are currently casting, cast completion %, and spell icon. Objects have a size (dimensions) as determined by the server. I want to attach the title bar to the object. I want the title bar to show the icon, with the spell name inline with it. If spell icon width + spell name width > object width, i want to stretch the title bar horizontally (and preferably center it over the object) The behavior I am currently seeing is that the spell name will stay inline UNTIL the spell name width + spell icon width > object width, at which point the name will appear on the next line, instead of stretching the title bar (and I can't try to center it if it's not larger). The solution may include javascript, as the game loop will update the object, including the position, size, graphic, spell icon, spell name, and cast completion % using javascript. "supercontainer" is the object. "container" is the title bar. So I want "container" to expand larger than "supercontainer" width when "first" and "second" are big enough. The size of "first" is fixed because all spell icons are the same size. ``` <div class="supercontainer"> <div class="container"> <div class="first"></div> <div class="second">Words are long</div> </div> </div> ``` the css ``` .supercontainer { position: absolute; left: 10px; /* example */ top: 10px; /* example */ width: 64px; height: 64px; background-color: black; } .container { min-width:100px; background-color: red; } .first { height: 20px; width: 20px; background-color: blue; display: inline-block; } .second { background-color: green; display: inline-block; } ``` Here is a link to a JSFiddle: <http://jsfiddle.net/ch901rL2/3/>
2015/12/06
[ "https://Stackoverflow.com/questions/34122747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2626428/" ]
Here's an older answer which hopefully answers your question and solves your problem. Is seems indeed to be a bug. <https://stackoverflow.com/a/19115950/543224>
I guess that you update UI on from background. If you want update UI you have to update in main queue. If you don't do it, some strange issue will come. So you can change your code to: ``` dispatch_async(dispatch_get_main_queue()) { () -> Void in if let object = currentObject.objectForKey("postText") as? String { postTextView.text = "the text field has some text added" } } ```
34,122,747
I am making a browser-based video game. In the game, objects have a graphic and a title bar. The title bar holds their name, the spell they are currently casting, cast completion %, and spell icon. Objects have a size (dimensions) as determined by the server. I want to attach the title bar to the object. I want the title bar to show the icon, with the spell name inline with it. If spell icon width + spell name width > object width, i want to stretch the title bar horizontally (and preferably center it over the object) The behavior I am currently seeing is that the spell name will stay inline UNTIL the spell name width + spell icon width > object width, at which point the name will appear on the next line, instead of stretching the title bar (and I can't try to center it if it's not larger). The solution may include javascript, as the game loop will update the object, including the position, size, graphic, spell icon, spell name, and cast completion % using javascript. "supercontainer" is the object. "container" is the title bar. So I want "container" to expand larger than "supercontainer" width when "first" and "second" are big enough. The size of "first" is fixed because all spell icons are the same size. ``` <div class="supercontainer"> <div class="container"> <div class="first"></div> <div class="second">Words are long</div> </div> </div> ``` the css ``` .supercontainer { position: absolute; left: 10px; /* example */ top: 10px; /* example */ width: 64px; height: 64px; background-color: black; } .container { min-width:100px; background-color: red; } .first { height: 20px; width: 20px; background-color: blue; display: inline-block; } .second { background-color: green; display: inline-block; } ``` Here is a link to a JSFiddle: <http://jsfiddle.net/ch901rL2/3/>
2015/12/06
[ "https://Stackoverflow.com/questions/34122747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2626428/" ]
Did you set the attributes on the text view itself (i.e. the text view text is "plain", and not "attributed")? Or did you use attributed text? If the latter, it's quite normal that if you replace the attributed text with plain text with no attributes, it reverts to the attributes of the text view itself. Make sure the type is set to "plain", and that you set the attributes on the text view itself, not on the text inside it. Or use the `attributedText` and not the `text` property of your text view, with appropriate attributes.
I guess that you update UI on from background. If you want update UI you have to update in main queue. If you don't do it, some strange issue will come. So you can change your code to: ``` dispatch_async(dispatch_get_main_queue()) { () -> Void in if let object = currentObject.objectForKey("postText") as? String { postTextView.text = "the text field has some text added" } } ```
24,713,282
I want to open an app chooser that will list of the installed apps on the phone. When clicking on an app in the chooser I don't need to open it but get it's package name. I know that I can create a specific intent for example with Intent.ACTION\_SEND and the ``` Intent.createChooser() ``` I also know that I can list the installed packages using the package manager. Is there a way to combine the 2 methods and create an app chooser with all of the installed apps?
2014/07/12
[ "https://Stackoverflow.com/questions/24713282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/826235/" ]
**Chooser.java** ``` public class Chooser extends ListActivity { AppAdapter adapter=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.chooser_layout); PackageManager pm=getPackageManager(); Intent main=new Intent(Intent.ACTION_MAIN, null); main.addCategory(Intent.CATEGORY_LAUNCHER); List<ResolveInfo> launchables=pm.queryIntentActivities(main, 0); Collections.sort(launchables, new ResolveInfo.DisplayNameComparator(pm)); adapter=new AppAdapter(pm, launchables); setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { ResolveInfo launchable=adapter.getItem(position); ActivityInfo activity=launchable.activityInfo; ComponentName name=new ComponentName(activity.applicationInfo.packageName, activity.name); /* SetResult String pack_name = name.getPackageName(); Intent intentMessage=new Intent(); intentMessage.putExtra("MESSAGE_package_name", pack_name); setResult(1,intentMessage); finish(); */ } class AppAdapter extends ArrayAdapter<ResolveInfo> { private PackageManager pm=null; AppAdapter(PackageManager pm, List<ResolveInfo> apps) { super(Chooser.this, R.layout.row, apps); this.pm=pm; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView==null) { convertView=newView(parent); } bindView(position, convertView); return(convertView); } private View newView(ViewGroup parent) { return(getLayoutInflater().inflate(R.layout.row, parent, false)); } private void bindView(int position, View row) { TextView label=(TextView)row.findViewById(R.id.label); label.setText(getItem(position).loadLabel(pm)); ImageView icon=(ImageView)row.findViewById(R.id.icon); icon.setImageDrawable(getItem(position).loadIcon(pm)); } } } ``` **chooser\_layout.xml** ``` <?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` **row.xml** ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" > <ImageView android:id="@+id/icon" android:drawable="@drawable/ic_launcher" android:layout_width="45dp" android:layout_height="45dp" android:layout_alignParentLeft="true" android:paddingLeft="2px" android:paddingTop="3px" android:paddingBottom="3px" android:paddingRight="3px" /> <TextView android:id="@+id/label" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toRightOf="@id/icon" android:textSize="18sp" android:text="Test App will here bla bla" android:paddingTop="2px" android:paddingBottom="2px" /> </RelativeLayout> ``` **You can choose app like this:** ``` Intent appIntent; ... appIntent=new Intent(this,Chooser.class); startActivityForResult(appIntent, 1); ... @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(null!=data){ if(requestCode==1){ //Do something String message=data.getStringExtra("MESSAGE_package_name"); package_Name.SetText(message); } } ``` **This will work for you.**
Use the results of `PackageManager` and `queryIntentActivities()` to populate your own UI that lists them. [This sample application](https://github.com/commonsguy/cw-omnibus/tree/master/Introspection/Launchalot) loads them into a `ListView`. While that sample application turns around and launches the selected activity in `onListItemClick()`, you could do something else instead.
9,656,867
I was trying to create a linked list with structs. The idea is to use 2 different stucts, one which is a node, and another which is a pointer to the nodes (so, I can link the nodes together). But I wanted to initialize the pointer to the first node as NULL, and create subsequent nodes later: I am having an error in the 2 constructor methods (List and Polynomial), I can't use the operator = like the way I am. But I can't understand why. ``` struct List { //Data members to hold an array of pointers, pointing to a specific node Node *list[100]; //Default constructor List(); }; List::List() { *list[0] = NULL; } class Polynomial { public: [...] private: List *poly; //Store the pointer links in an array Node first_node; int val; }; Polynomial::Polynomial() { poly = new List(); } /*******************************************************************************************************************************/ // Method : initialize() // Description : This function creates the linked nodes /*******************************************************************************************************************************/ Polynomial::void initialize(ifstream &file) { int y[20]; double x[20]; int i = 0, j = 0; //Read from the file file >> x[j]; file >> y[j]; first_node(x[j], y[j++]); //Create the first node with coef, and pwr *poly->list[i] = &first_node; //Link to the fist node //Creat a linked list while(y[j] != 0) { file >> x[j]; file >> y[j]; *poly->list[++i] = new Node(x[j], y[j++]); } val = i+1; //Keeps track of the number of nodes } ``` I have been getting errors in the Polynomial constructor and the List constructor.
2012/03/11
[ "https://Stackoverflow.com/questions/9656867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989359/" ]
You can use `SoundPool`. It fits what you want to do perfectly. You'll just need a way to store the sound effect IDs corresponding to each image (or button). Perhaps extend Button to store associated sound effect ID. And use a common SoundPool to play the sound effect associated to the id when the button is touched. [You can read more about SoundPool here](http://developer.android.com/reference/android/media/SoundPool.html).
@Rikonator is on the right track there with Soundpool. It's much more suited to the kind of functionality you are after. If you decide to go with the mediaplayer anyway, though, don't forget the prepareAsync () method to prevent it from hanging the UI thread. You can read more about playing media [here](http://developer.android.com/guide/topics/media/mediaplayer.html).
9,656,867
I was trying to create a linked list with structs. The idea is to use 2 different stucts, one which is a node, and another which is a pointer to the nodes (so, I can link the nodes together). But I wanted to initialize the pointer to the first node as NULL, and create subsequent nodes later: I am having an error in the 2 constructor methods (List and Polynomial), I can't use the operator = like the way I am. But I can't understand why. ``` struct List { //Data members to hold an array of pointers, pointing to a specific node Node *list[100]; //Default constructor List(); }; List::List() { *list[0] = NULL; } class Polynomial { public: [...] private: List *poly; //Store the pointer links in an array Node first_node; int val; }; Polynomial::Polynomial() { poly = new List(); } /*******************************************************************************************************************************/ // Method : initialize() // Description : This function creates the linked nodes /*******************************************************************************************************************************/ Polynomial::void initialize(ifstream &file) { int y[20]; double x[20]; int i = 0, j = 0; //Read from the file file >> x[j]; file >> y[j]; first_node(x[j], y[j++]); //Create the first node with coef, and pwr *poly->list[i] = &first_node; //Link to the fist node //Creat a linked list while(y[j] != 0) { file >> x[j]; file >> y[j]; *poly->list[++i] = new Node(x[j], y[j++]); } val = i+1; //Keeps track of the number of nodes } ``` I have been getting errors in the Polynomial constructor and the List constructor.
2012/03/11
[ "https://Stackoverflow.com/questions/9656867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989359/" ]
You can use `SoundPool`. It fits what you want to do perfectly. You'll just need a way to store the sound effect IDs corresponding to each image (or button). Perhaps extend Button to store associated sound effect ID. And use a common SoundPool to play the sound effect associated to the id when the button is touched. [You can read more about SoundPool here](http://developer.android.com/reference/android/media/SoundPool.html).
``` MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sound); try { if (mp.isPlaying()) { mp.stop(); mp.release(); mp = MediaPlayer.create(getApplicationContext(), R.raw.sound); } mp.start(); } catch (Exception e) { e.printStackTrace(); } ```