qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
256,964
Inspired by a challenge from the [OUCC 2022 Seniors competition](https://challenge.bebras.uk/index.php?action=anon_join&grp_id=12427). ### Background Two teams are playing "capture the flag". They take turns invading each other's base and capturing their opposing team's flag in the shortest amount of time. The attacking players each have one soft ball they can throw at the defenders. Teams get to reduce the time they took to capture the flag by 3 seconds for each of the defenders team that gets hit with a ball. ### Your Task Write a program that calculates which team won based on who had the smallest accumulated time. ### Clarifications * There are two teams. * There will be an even number of rounds played. * Both teams will attack an equal number of times but it could be in any order. ### Example Let's say we have the input `[['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]]`. We go through each inner list: * `['A', 20, 0]`: The `A` tells us we need to add to team A. To get the number we need to add, we use `time - 3*hits`. In this case, it is `20-3*0` = 20. * `['A', 30, 1]`: We again need to add to team A. This time it's `30-3*1` = 27. Team A is now on 47. * `['B', 40, 6]`: This time it's 22 * `['B', 20, 2]`: 14. B is now at 36. Now we get the team with the lower score, in this case B, and output. ### Test cases ``` Input -> Output [['A', 100, 5], ['B', 95, 2]] -> A [['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]] -> B ['A', 50, 3], ['A', 70, 5], ['B', 35, 0], ['A', 25, 1], ['B', 60, 2], ['B', 40, 4] -> B [] -> Draw ``` ### Input / Output formats * You must take an arbitrary even number of inputs (these can all be in a list, or taken separately). * Each input must be a list of three items (in whatever order you prefer): + The team. You must choose two distinct values for this, e.g. `0` and `1`, `'A'` and `'B'`, etc. + The time taken for the team to get the flag (a positive integer of seconds) + The number of hits they got (a positive integer)Note: The number of hits will never exceed the time taken / 5, so the score will never be negative. * You must have three distinct output possibilities: + One for the first team winning + One for the second team winning + One for a draw * **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!**
2023/01/21
[ "https://codegolf.stackexchange.com/questions/256964", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/114446/" ]
[Charcoal](https://github.com/somebody1234/Charcoal), ~~28~~ 21 bytes ===================================================================== ``` ≔↨¹Eθ×⊟ι↨±³ιθI∧θ÷θ±↔θ ``` [Try it online!](https://tio.run/##PY65DsIwEER7vmLLtbSRckJBFaChAKWgs1KYxAqWgnPY5PeNYwWmem9HI23zEnMziN650hjVaTwJIzEhuIkRJ4KHekuD1TCiYgShvMtOWImZd8V8CCZ23FWz0hbPwlgsdbtOr9pe1KJauco2Kp9m6D8eJhZydI5znhEUMUGU1AS8IDj8xUPmD4H9U2nxK1KCfbwVOUEeuK5dtPRf "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of `[hits, time, team]` where `-1` is `A` and `1` is `B` and outputs the winning team or `0` for a tie. Explanation: ``` ≔↨¹Eθ×⊟ι↨±³ιθ ``` Calculate sum of the accumulated times for each round with `A`s times being negative and `B`'s times being positive. ``` I∧θ÷θ±↔θ ``` Output the negated sign of the result. No actual "base conversion" going on here - base `-3` is used to calculate accumulated time and base `1` is used to take the sum of a list in case it's empty.
[05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ============================================================================================================================ ``` ε`3*-*}O.± ``` Port of almost any other answer, with input-triplets in the order `[team, time, hits]` and using `1` and `-1` for teams \$A\$ and \$B\$ respectively, with an output of `-1`, `1`, or `0` for Team \$B\$ wins; Team \$A\$ wins; and draw respectively. [Try it online](https://tio.run/##yy9OTMpM/f//3NYEYy1drVp/vUMb//@PjjbUMTLQMYjVATKMDXQMgQxdQx0TAx0zCAssGQsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1sTjLV0tWr99Q5t/K/zPzo62lDH0MBAxzRWJ1rXUMfSVMcoNlZHASRsZKBjABQ11DE20DGESJsY6JhBWGBJqEJTAx1jsEJzuDnGplC9RqYwvWYGQKNhppiA9cbGAgA). A port of [*@JonathanAllan*'s Jelly's answer](https://codegolf.stackexchange.com/a/256988/52210) is 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) as well: ``` εć*3(β}O.± ``` Takes the inputs in the order `[team, hits, time]` instead. The other I/O is the same. [Try it online](https://tio.run/##yy9OTMpM/f//3NYj7VrGGuc21frrHdr4/390tKGOgY6RQawOkGGoYwxi6BrqmOmYQFlGIMlYAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/c1uPtGsZa5zbVOuvd2jjf53/0dHRhjqmOoYGBrE60bqGOkY6lqaxsToKIGEDHSOQqKGOoY4xVNpMxwSuECgJVWisYwpRaKpjDpU20DE2heo1MoXpMINKmoBMAemNjQUA). **Explanation:** ```python ε # Map over the (implicit) input-list of triplets: ` # Pop and push all three values separately to the stack 3* # Multiply the top `hits` by 3 - # Subtract it from the `time` * # Multiply it to the `team` }O # After the map: sum the list together .± # Pop and output its sign # (which is output implicitly as result) ε # Map over the (implicit) input-list of triplets: ć # Extract head; pop and push remainder-list [hits,time] & head `team` separately * # Multiply `team` to the values in the pair: [hits*team,time*team] 3(β # Convert it from a base-(-3) list to an integer: team*(time-3*hits) }O.± # After the map: same as above (and also output implicitly) ```
256,964
Inspired by a challenge from the [OUCC 2022 Seniors competition](https://challenge.bebras.uk/index.php?action=anon_join&grp_id=12427). ### Background Two teams are playing "capture the flag". They take turns invading each other's base and capturing their opposing team's flag in the shortest amount of time. The attacking players each have one soft ball they can throw at the defenders. Teams get to reduce the time they took to capture the flag by 3 seconds for each of the defenders team that gets hit with a ball. ### Your Task Write a program that calculates which team won based on who had the smallest accumulated time. ### Clarifications * There are two teams. * There will be an even number of rounds played. * Both teams will attack an equal number of times but it could be in any order. ### Example Let's say we have the input `[['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]]`. We go through each inner list: * `['A', 20, 0]`: The `A` tells us we need to add to team A. To get the number we need to add, we use `time - 3*hits`. In this case, it is `20-3*0` = 20. * `['A', 30, 1]`: We again need to add to team A. This time it's `30-3*1` = 27. Team A is now on 47. * `['B', 40, 6]`: This time it's 22 * `['B', 20, 2]`: 14. B is now at 36. Now we get the team with the lower score, in this case B, and output. ### Test cases ``` Input -> Output [['A', 100, 5], ['B', 95, 2]] -> A [['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]] -> B ['A', 50, 3], ['A', 70, 5], ['B', 35, 0], ['A', 25, 1], ['B', 60, 2], ['B', 40, 4] -> B [] -> Draw ``` ### Input / Output formats * You must take an arbitrary even number of inputs (these can all be in a list, or taken separately). * Each input must be a list of three items (in whatever order you prefer): + The team. You must choose two distinct values for this, e.g. `0` and `1`, `'A'` and `'B'`, etc. + The time taken for the team to get the flag (a positive integer of seconds) + The number of hits they got (a positive integer)Note: The number of hits will never exceed the time taken / 5, so the score will never be negative. * You must have three distinct output possibilities: + One for the first team winning + One for the second team winning + One for a draw * **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!**
2023/01/21
[ "https://codegolf.stackexchange.com/questions/256964", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/114446/" ]
[Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) =================================================================================================================== Employs the team identification trick from [Arnauld's JavaScript ES6 answer](https://codegolf.stackexchange.com/a/256965/53748). ``` Ḣ×)ḅ-3SṠ ``` A monadic Link that accepts a list of triples, `[team, hits, time]` with teams represented as `-1` and `1`, and yields the losing team or `0` for a draw (i.e. `-1` if `1` won and vice versa). **[Try it online!](https://tio.run/##y0rNyan8///hjkWHp2s@3NGqaxz8cOeC////R0cb6igY6yiYGcTqKETrAjmWOgoWcI6pjoIJmANkgxQaxMYCAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjkWHp2s@3NGqaxz8cOeC/4fbHzWt@f8/Ojpa11BHwVRHwdDAIFZHIRrIMdJRsDSNjdXhUoBIGgCFwHIgDhAZwxSa6SiYIGkCKkJoMgYaCtcENN4cphBomrEpkmlGpggTzGCKTMAmg00DErEA "Jelly – Try It Online"). ### How? ``` Ḣ×)ḅ-3SṠ - Link: list of [team, hits, time] triples ) - for each triple: Ḣ - head -> removes team and yields it × - multiply by ([hits, time]) -> [team * hits, team * time] ḅ-3 - convert (each) from base -3 -> -3 ** 1 * team * hits + -3 ** 0 * team * time = team * (time - 3 * hits) S - sum Ṡ - sign ``` --- Equivalently, `Ḣ×ḅ-3)SṠ`. Similarly, `Ḣ)ḋḅ-3$Ṡ` (using a dot-product).
Julia,44 bytes ============== ``` a->sign(mapfoldl(i->i[1]*(i[2]-3*i[3]),+,a)) ``` I'm taking the strategy everyone else is using by using -1 for A and 1 for B, then multiplying that by the number of seconds after deductions. Outputting the sign of the output is the team who wins, and zero is a draw.
256,964
Inspired by a challenge from the [OUCC 2022 Seniors competition](https://challenge.bebras.uk/index.php?action=anon_join&grp_id=12427). ### Background Two teams are playing "capture the flag". They take turns invading each other's base and capturing their opposing team's flag in the shortest amount of time. The attacking players each have one soft ball they can throw at the defenders. Teams get to reduce the time they took to capture the flag by 3 seconds for each of the defenders team that gets hit with a ball. ### Your Task Write a program that calculates which team won based on who had the smallest accumulated time. ### Clarifications * There are two teams. * There will be an even number of rounds played. * Both teams will attack an equal number of times but it could be in any order. ### Example Let's say we have the input `[['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]]`. We go through each inner list: * `['A', 20, 0]`: The `A` tells us we need to add to team A. To get the number we need to add, we use `time - 3*hits`. In this case, it is `20-3*0` = 20. * `['A', 30, 1]`: We again need to add to team A. This time it's `30-3*1` = 27. Team A is now on 47. * `['B', 40, 6]`: This time it's 22 * `['B', 20, 2]`: 14. B is now at 36. Now we get the team with the lower score, in this case B, and output. ### Test cases ``` Input -> Output [['A', 100, 5], ['B', 95, 2]] -> A [['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]] -> B ['A', 50, 3], ['A', 70, 5], ['B', 35, 0], ['A', 25, 1], ['B', 60, 2], ['B', 40, 4] -> B [] -> Draw ``` ### Input / Output formats * You must take an arbitrary even number of inputs (these can all be in a list, or taken separately). * Each input must be a list of three items (in whatever order you prefer): + The team. You must choose two distinct values for this, e.g. `0` and `1`, `'A'` and `'B'`, etc. + The time taken for the team to get the flag (a positive integer of seconds) + The number of hits they got (a positive integer)Note: The number of hits will never exceed the time taken / 5, so the score will never be negative. * You must have three distinct output possibilities: + One for the first team winning + One for the second team winning + One for a draw * **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!**
2023/01/21
[ "https://codegolf.stackexchange.com/questions/256964", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/114446/" ]
[Nibbles](http://golfscript.com/nibbles/index.html), ~~6~~ 5.5 bytes ==================================================================== ``` `$+.$*-@*3 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWqxJUtPVUtHQdtIwhAlDxm9rRStEaBjpGBjqGmjoahjrGEIaZjomBji6IZQSSA7JilWKhegA) Takes a list of tuples `(hits,time,team)` with `1` and `-1` as the team names. Outputs the team with a bigger score, or `0` for a draw. Explanation ----------- ``` `$ Sign of + sum of . map $ input (x,y,z) => * multiply - subtract @ y *3 multiply by 3 x z ``` Nibbles' implicit tuple unpacking came in really handy here. -0.5 by using my freedom to choose the order of the tuple.
[Nim](https://nim-lang.org/), 77 bytes ====================================== ``` import math,sequtils proc c[S](s:S):int=sgn sum s.mapIt it[0]*(it[1]-3*it[2]) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m704LzN3wYKlpSVpuhY3fTNzC_KLShRyE0sydIpTC0tLMnOKuQqK8pMVkqODYzWKrYI1rTLzSmyL0_MUiktzFYr1chMLPEsUMkuiDWK1NICUYayusRaQNorVhBpqkJqcka-QrOEQrWGoY2SgY6CpA2QYG-gYAhm6hjomBjpmEBZQ0kgTpg_mKAA) Takes `1` and `-1` as the team names. Outputs the team with a bigger score, or `0` for a draw.
256,964
Inspired by a challenge from the [OUCC 2022 Seniors competition](https://challenge.bebras.uk/index.php?action=anon_join&grp_id=12427). ### Background Two teams are playing "capture the flag". They take turns invading each other's base and capturing their opposing team's flag in the shortest amount of time. The attacking players each have one soft ball they can throw at the defenders. Teams get to reduce the time they took to capture the flag by 3 seconds for each of the defenders team that gets hit with a ball. ### Your Task Write a program that calculates which team won based on who had the smallest accumulated time. ### Clarifications * There are two teams. * There will be an even number of rounds played. * Both teams will attack an equal number of times but it could be in any order. ### Example Let's say we have the input `[['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]]`. We go through each inner list: * `['A', 20, 0]`: The `A` tells us we need to add to team A. To get the number we need to add, we use `time - 3*hits`. In this case, it is `20-3*0` = 20. * `['A', 30, 1]`: We again need to add to team A. This time it's `30-3*1` = 27. Team A is now on 47. * `['B', 40, 6]`: This time it's 22 * `['B', 20, 2]`: 14. B is now at 36. Now we get the team with the lower score, in this case B, and output. ### Test cases ``` Input -> Output [['A', 100, 5], ['B', 95, 2]] -> A [['A', 20, 0], ['A', 30, 1], ['B', 40, 6], ['B', 20, 2]] -> B ['A', 50, 3], ['A', 70, 5], ['B', 35, 0], ['A', 25, 1], ['B', 60, 2], ['B', 40, 4] -> B [] -> Draw ``` ### Input / Output formats * You must take an arbitrary even number of inputs (these can all be in a list, or taken separately). * Each input must be a list of three items (in whatever order you prefer): + The team. You must choose two distinct values for this, e.g. `0` and `1`, `'A'` and `'B'`, etc. + The time taken for the team to get the flag (a positive integer of seconds) + The number of hits they got (a positive integer)Note: The number of hits will never exceed the time taken / 5, so the score will never be negative. * You must have three distinct output possibilities: + One for the first team winning + One for the second team winning + One for a draw * **This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins!**
2023/01/21
[ "https://codegolf.stackexchange.com/questions/256964", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/114446/" ]
[Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ================================================================================================================================================================= Port of [Jonathan's Jelly solution](https://codegolf.stackexchange.com/a/256988/58974). ``` xÈm*Xv)ì3n ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=eMhtKlh2Kewzbg&input=W1sxLCAzLCA2MF0sIFstMSwgOSwgODBdLCBbLTEsIDUsIDQwXSwgWzEsIDEsIDMwXV0) ``` xÈm*Xv)ì3n :Implicit input of 2D array x :Reduce by addition after È :Passing each X through the following function m* : Map & multiply by Xv : Remove & return the first element, mutating the original array ) : End map ì : Convert from base 3n : -3 :Implicit output of sign of result ```
[Thunno](https://github.com/Thunno/Thunno), \$ 11 \log\_{256}(96) \approx \$ 9.05 bytes ======================================================================================= ``` eAu3*-*ESza ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuharUx1LjbV0tVyDqxIhIlCJBTe9o6N1DXUUTA10FIxjdRTAHHMgxxTEAbKNTXUUDGASRkCOIVTCDKjICMo2AbJNYmMhZgIA) or [verify all test cases](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wSLP6qWlJWm6FqtTHUuNtXS1XIOrEiEii6K8IYyl0UopSrE350RH6xrqKBgaGOgomMbqKEQDOZamOgpGsbFcECkjoIwBSAbEMQZyDKHKTIBsMygbpAihxRTIM4ZpMUcy2dgUySwjU4RZZmD9CHNNQGbFQlwKAA). Port of AndrovT's Vyxal answer #### Explanation ```python eAu3*-*ESza # Implicit input e E # Map over the input: Au # Dump the contents onto the stack 3* # Triple (the hits) - # Subtract (from the time) * # Multiply (by the team) S # Sum za # Sign # Implicit output ```
23,097,418
however I am not sure where I am supposed to enter the whoWins() method. Do I enter this method in the actionperformed Method of the buttons or do i need to something different. Please help. ``` public class TTT extends JFrame implements ActionListener { private JButton buttons[] = new JButton[9]; private JButton exitButton; public JLabel title; public JPanel titlePanel, panel; private int count = 0; int symbolCount = 0; private boolean win = false; public TTT() { title = new JLabel("Welcome to my Tic Tac Toe Game!"); titlePanel = new JPanel(); title.setFont(new Font(Font.SERIF, 0, 30)); titlePanel.add(title); this.add(titlePanel, BorderLayout.NORTH); panel = new JPanel(new GridLayout(3, 3)); for (int i = 0; i < buttons.length; i++) { buttons[i] = new JButton(); panel.add(buttons[i]); buttons[i].setEnabled(true); buttons[i].addActionListener(this); } this.add(panel, BorderLayout.CENTER); JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER)); exitButton = new JButton("Quit"); panel1.add(exitButton); this.add(panel1, BorderLayout.SOUTH); exitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(WIDTH); } }); } public void whoWins() { //Determines who wins using for the horizontal rows. if (buttons[0].getText() == buttons[1].getText() && buttons[1].getText() == buttons[2].getText() && buttons[0].getText() != "") { win = true; } else if (buttons[3].getText() == buttons[4].getText() && buttons[4].getText() == buttons[5].getText() && buttons[3].getText() != "") { win = true; } else if (buttons[6].getText() == buttons[7].getText() && buttons[7].getText() == buttons[8].getText() && buttons[6].getText() != "") { win = true; } //Determines the verticles wins else if (buttons[0].getText() == buttons[3].getText() && buttons[3].getText() == buttons[6].getText() && buttons[0].getText() != "") { win = true; } else if (buttons[1].getText() == buttons[4].getText() && buttons[4].getText() == buttons[7].getText() && buttons[1].getText() != "") { win = true; } else if (buttons[2].getText() == buttons[5].getText() && buttons[5].getText() == buttons[8].getText() && buttons[2].getText() != "") { win = true; } // Diagnol Wins else if (buttons[0].getText()==buttons[4].getText()&&buttons[4].getText()==buttons[8].getText()&& buttons[0].getText()!= "") { win = true; }else if (buttons[2].getText()==buttons[4].getText()&&buttons[4].getText()==buttons[6].getText()&& buttons[1].getText()!= "") { win = true; }else { win = false; } //who won if (win = true) { JOptionPane.showMessageDialog(null, "wins"); }else if (count == 9 && win == false) { JOptionPane.showMessageDialog(null, "Tie game"); } } public static void main(String[] args) { TTT ref1 = new TTT(); ref1.setTitle("Tic Tac Toe"); ref1.setVisible(true); ref1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ref1.setSize(500, 500); ref1.setLocationRelativeTo(null); // ref1.whoWins(); } @Override public void actionPerformed(ActionEvent e) { count++; for (JButton button : buttons) { if (button == e.getSource()) { if (symbolCount % 2 == 0) { button.setText("X"); button.setEnabled(false); } else { button.setText("O"); button.setEnabled(false); } } } if (count >= buttons.length) { JOptionPane.showMessageDialog(null, "End"); } symbolCount++; } } ```
2014/04/16
[ "https://Stackoverflow.com/questions/23097418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3285009/" ]
If you really want to do this right, then I suggest making some big changes, some M-V-C type changes: * First and foremost, separate out the logic of the game from the game GUI. This would mean that the code that determines who wins should not be in any code that contains GUI type code. This will be your "model" * Next you should never have GUI code implement listener interfaces, so try to get that out of the GUI and possibly have it go into its own class, the "Control" class. * Finally the GUI or "View" class will concern itself with displaying the model's state and getting input from the user and transmitting this input to the control. --- For example,... ``` import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import java.awt.Window; import java.awt.event.*; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.EnumMap; import java.util.Map; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.event.SwingPropertyChangeSupport; public class TicTacToeMain { private static void createAndShowGui() { TttView view = null; try { view = new TttView(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } TttModel model = new TttModel(); new TttControl(model, view); JFrame frame = new JFrame("Tic Tac Toe"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.getContentPane().add(view.getMainPanel()); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGui(); } }); } } enum TttPiece { EMPTY, X, O } class TttView { public static final String IMAGE = "/imgFolder/TicTacToe.png"; private static final int GAP = 5; private JPanel mainPanel = new JPanel(); private JPanel tttPanel = new JPanel(); private Map<TttPiece, Icon> iconMap = new EnumMap<>(TttPiece.class); private JLabel[][] grid = new JLabel[TttModel.ROWS][TttModel.COLS]; private TttControl control; public TttView() throws IOException { BufferedImage img = ImageIO.read(getClass().getResourceAsStream(IMAGE)); Icon[] imgIcons = splitImg(img); iconMap.put(TttPiece.X, imgIcons[0]); iconMap.put(TttPiece.O, imgIcons[1]); iconMap.put(TttPiece.EMPTY, createEmptyIcon(imgIcons[0])); tttPanel.setLayout(new GridLayout(grid.length, grid[0].length, GAP, GAP)); tttPanel.setBackground(Color.black); MyMouseAdapter mouseAdapter = new MyMouseAdapter(); for (int row = 0; row < grid.length; row++) { for (int col = 0; col < grid[row].length; col++) { grid[row][col] = new JLabel(iconMap.get(TttPiece.EMPTY)); grid[row][col].setOpaque(true); grid[row][col].setBackground(Color.LIGHT_GRAY); grid[row][col].addMouseListener(mouseAdapter); tttPanel.add(grid[row][col]); } } JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0)); btnPanel.add(new JButton(new ClearAction("Clear", KeyEvent.VK_C))); btnPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X))); int blGap = 2; mainPanel.setLayout(new BorderLayout(blGap, blGap)); mainPanel.setBorder(BorderFactory.createEmptyBorder(blGap, blGap, blGap, blGap)); mainPanel.add(tttPanel, BorderLayout.CENTER); mainPanel.add(btnPanel, BorderLayout.SOUTH); } public void setControl(TttControl control) { this.control = control; } public JComponent getMainPanel() { return mainPanel; } private Icon createEmptyIcon(Icon icon) { int width = icon.getIconWidth(); int height = icon.getIconHeight(); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); return new ImageIcon(img); } private Icon[] splitImg(BufferedImage img) { int w = img.getWidth(); int h = img.getHeight(); int gap = 5; Icon[] icons = new ImageIcon[2]; icons[0] = new ImageIcon(img.getSubimage(0, 0, w / 2 - gap, h / 2 - gap)); icons[1] = new ImageIcon(img.getSubimage(w / 2 + gap, 0, w / 2 - gap, h / 2 - gap)); return icons; } private class MyMouseAdapter extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { if (control == null) { return; } for (int row = 0; row < grid.length; row++) { for (int col = 0; col < grid[row].length; col++) { if (grid[row][col] == e.getSource()) { control.gridPress(row, col); } } } } } private class ClearAction extends AbstractAction { public ClearAction(String name, int mnemonic) { super(name); putValue(MNEMONIC_KEY, mnemonic); } @Override public void actionPerformed(ActionEvent evt) { if (control != null) { control.clear(); } } } private class ExitAction extends AbstractAction { public ExitAction(String name, int mnemonic) { super(name); putValue(MNEMONIC_KEY, mnemonic); } @Override public void actionPerformed(ActionEvent evt) { if (control != null) { control.exit(evt); } } } public void setGridIcon(int row, int col, TttPiece tttPiece) { grid[row][col].setIcon(iconMap.get(tttPiece)); } } class TttControl { private TttModel model; private TttView view; public TttControl(TttModel model, TttView view) { this.model = model; this.view = view; view.setControl(this); model.addPropertyChangeListener(new ModelListener()); } public void exit(ActionEvent evt) { Window win = SwingUtilities .getWindowAncestor((Component) evt.getSource()); win.dispose(); } public void gridPress(int row, int col) { try { model.gridPress(row, col); } catch (TttException e) { // TODO: notify user // e.printStackTrace(); } } public void clear() { model.clear(); } private class ModelListener implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { if (TttModel.GRID_POSITION.equals(evt.getPropertyName())) { TttPiece[][] tttGrid = model.getTttGrid(); for (int row = 0; row < tttGrid.length; row++) { for (int col = 0; col < tttGrid[row].length; col++) { view.setGridIcon(row, col, tttGrid[row][col]); } } } } } } class TttModel { public static final int ROWS = 3; public static final int COLS = ROWS; public static final String GRID_POSITION = "grid position"; private SwingPropertyChangeSupport pcSupport = new SwingPropertyChangeSupport( this); private TttPiece[][] tttGrid = new TttPiece[ROWS][COLS]; private TttPiece player = TttPiece.X; private boolean gameOver; public TttModel() { clear(); } public void setGridPosition(int row, int col, TttPiece piece) throws TttException { if (gameOver) { return; } if (tttGrid[row][col] == TttPiece.EMPTY) { tttGrid[row][col] = piece; checkForWin(row, col, piece); nextPlayer(); pcSupport.firePropertyChange(GRID_POSITION, null, tttGrid); } else { String message = "Invalid setGridPosition for row: %d, col: %d, piece: %s. " + "Spot already occupied by piece: %s"; message = String.format(message, row, col, piece, tttGrid[row][col]); throw new TttException(message); } } public TttPiece[][] getTttGrid() { return tttGrid; } public void gridPress(int row, int col) throws TttException { setGridPosition(row, col, player); } public void nextPlayer() { player = player == TttPiece.X ? TttPiece.O : TttPiece.X; } private void checkForWin(int row, int col, TttPiece piece) { // TODO finish } public void clear() { for (int row = 0; row < tttGrid.length; row++) { for (int col = 0; col < tttGrid[row].length; col++) { tttGrid[row][col] = TttPiece.EMPTY; } } player = TttPiece.X; pcSupport.firePropertyChange(GRID_POSITION, null, tttGrid); } public void addPropertyChangeListener(PropertyChangeListener listener) { pcSupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { pcSupport.removePropertyChangeListener(listener); } } @SuppressWarnings("serial") class TttException extends Exception { public TttException() { super(); } public TttException(String message) { super(message); } } ``` Using for my images: ![enter image description here](https://i.stack.imgur.com/mwfLB.png) With GUI looking like: ![enter image description here](https://i.stack.imgur.com/XnKZG.jpg)
I am also interested in writing a Tic Tac Toe game, so I copied your code, and did a little modification, and it passed test, check following: ``` package eric.j2se.swing; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; /** * <p> * Simple game of Tic Tac Toe. * </p> * * @author eric * @date Apr 16, 2014 11:03:48 AM */ @SuppressWarnings("serial") public class TicTacToe extends JFrame implements ActionListener { // 2 players public static final char playerX = 'X'; public static final char playerO = 'O'; // null player public static final char playerN = 'N'; // the winer, init to null player private Character winner = playerN; // indicate whether game over private boolean gameOver = false; // count of button used, private int count = 0; private Character buttonPlayers[] = new Character[9]; private JButton buttons[] = new JButton[9]; private JButton exitButton; public JLabel title; public JPanel titlePanel, panel; public TicTacToe() { // init buttonPlayers for (int i = 0; i < 9; i++) { buttonPlayers[i] = playerN; } // init title title = new JLabel("Welcome to Tic Tac Toe!"); titlePanel = new JPanel(); title.setFont(new Font(Font.SERIF, 0, 30)); titlePanel.add(title); this.add(titlePanel, BorderLayout.NORTH); // init 9 button panel = new JPanel(new GridLayout(3, 3)); for (int i = 0; i < buttons.length; i++) { buttons[i] = new JButton(); panel.add(buttons[i]); buttons[i].setEnabled(true); buttons[i].addActionListener(this); } // init exit button this.add(panel, BorderLayout.CENTER); JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER)); exitButton = new JButton("Quit"); panel1.add(exitButton); this.add(panel1, BorderLayout.SOUTH); exitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(WIDTH); } }); } public void whoWins() { // determine winner - horizontal rows if (!gameOver) { for (int i = 0; i < 3; i++) { if ((buttonPlayers[0 + i * 3] != playerN) && (buttonPlayers[0 + i * 3].equals(buttonPlayers[1 + i * 3])) && buttonPlayers[1 + i * 3].equals(buttonPlayers[2 + i * 3])) { winner = buttonPlayers[0 + i * 3]; gameOver = true; break; } } } // determine winner - vertical rows if (!gameOver) { for (int i = 0; i < 3; i++) { if ((buttonPlayers[i + 0 * 3] != playerN) && (buttonPlayers[i + 0 * 3].equals(buttonPlayers[i + 1 * 3])) && buttonPlayers[i + 1 * 3].equals(buttonPlayers[i + 2 * 3])) { winner = buttonPlayers[i + 0 * 3]; gameOver = true; break; } } } // determine winner - diagonal rows if (!gameOver) { int winButtonIndex = -1; if ((buttonPlayers[0] != playerN) && (buttonPlayers[0].equals(buttonPlayers[4])) && buttonPlayers[4].equals(buttonPlayers[8])) { winButtonIndex = 0; } else if ((buttonPlayers[2] != playerN) && (buttonPlayers[2].equals(buttonPlayers[4])) && buttonPlayers[4].equals(buttonPlayers[6])) { winButtonIndex = 2; } if (winButtonIndex >= 0) { winner = buttonPlayers[winButtonIndex]; gameOver = true; } } // full if (count == 9) { gameOver = true; } if (gameOver) { String tip = ""; switch (winner) { case playerO: tip = "Player O win!"; break; case playerX: tip = "Player X win!"; break; default: tip = "Draw game!"; break; } JOptionPane.showMessageDialog(null, tip); } } @Override public void actionPerformed(ActionEvent e) { for (int i = 0; i < buttons.length; i++) { JButton button = buttons[i]; if (button == e.getSource()) { Character currentPlayer = (count % 2 == 1 ? playerX : playerO); button.setText(String.valueOf(currentPlayer)); buttonPlayers[i] = currentPlayer; button.setEnabled(false); break; } } count++; whoWins(); } public static void main(String[] args) { TicTacToe ref1 = new TicTacToe(); ref1.setTitle("Tic Tac Toe"); ref1.setVisible(true); ref1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ref1.setSize(500, 500); ref1.setLocationRelativeTo(null); } } ``` about when to call the win check: > > check each time you click 1 of the 9 buttons, > > > about the flag: > > I use 2 flag instead of 1 flag to indicate game over & winner, because in TTT game, draw game is very usual, after play several times, you always get draw game ... > > > a little suggestion to your code: * when compare string, use equals(), not ==, * define const values in variable, not write it in logic, e.g. 'O' 'X', * don't repeat code, try use logic control to make it short & easy to read & easy to maintain,
11,560
In DBZ, we see that the Elder Kai fully awakens the dormant power of Gohan. In this state Gohan can match Buu in his unfused form. But after Buu absorbs Piccolo and Gotenks, why doesn't Gohan go Super? Is there any reason that Gohan couldn't transform to Super Saiyan form after the awakening? Edit 1: Removed the transformation in GT from consideration because DBZ and GT are seperate canons. Edit 2: Dragon Ball Super has canon continuity to DBZ and I've heard talks of Ultimate Gohan in it. Has more information been provided on Gohan's transformation in DBS? Please Note: Yet to see DBS beyond the intial movies.
2014/06/30
[ "https://anime.stackexchange.com/questions/11560", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/6368/" ]
I think I found a possible answer, because I had a similar question. In [Gohan](http://dragonball.wikia.com/wiki/Gohan) article on Dragon Ball Wiki. > > However, amazed at realizing that > some of his power really was unlocked, Gohan apologizes to Old Kai, > and resumes the ritual. **After some time, the ritual is finally > completed and Gohan is told to power up like he does for the Super > Saiyan transformation; however, when he does, his appearance does not > change, but his power and strength gain an awesome increase.** > > > So it seems when Gohan got "Mystic Gohan", even though he increased his power, his appearance didn't change. So he couldn't transform in any other Saiyan form than the normal form, but he was still getting stronger. I'm not sure if he is able to change, but the fact is, there would be no difference. He already got all his power in his normal form, without a change.
In Dragon Ball Super when training with Piccolo Gohan powered up to super saiyan 2, and then he made a final effort and transformed into mystic form , passing from super saiyan 2 to mystic form in a gradual change, as a next stage, so no, now with Dragon Ball Super the answer is clear, he can't transform into super saiyan when in mystic form because it's another stage of power. You can see it here: <https://www.youtube.com/watch?v=8G4shXF9bo0>
11,560
In DBZ, we see that the Elder Kai fully awakens the dormant power of Gohan. In this state Gohan can match Buu in his unfused form. But after Buu absorbs Piccolo and Gotenks, why doesn't Gohan go Super? Is there any reason that Gohan couldn't transform to Super Saiyan form after the awakening? Edit 1: Removed the transformation in GT from consideration because DBZ and GT are seperate canons. Edit 2: Dragon Ball Super has canon continuity to DBZ and I've heard talks of Ultimate Gohan in it. Has more information been provided on Gohan's transformation in DBS? Please Note: Yet to see DBS beyond the intial movies.
2014/06/30
[ "https://anime.stackexchange.com/questions/11560", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/6368/" ]
I think I found a possible answer, because I had a similar question. In [Gohan](http://dragonball.wikia.com/wiki/Gohan) article on Dragon Ball Wiki. > > However, amazed at realizing that > some of his power really was unlocked, Gohan apologizes to Old Kai, > and resumes the ritual. **After some time, the ritual is finally > completed and Gohan is told to power up like he does for the Super > Saiyan transformation; however, when he does, his appearance does not > change, but his power and strength gain an awesome increase.** > > > So it seems when Gohan got "Mystic Gohan", even though he increased his power, his appearance didn't change. So he couldn't transform in any other Saiyan form than the normal form, but he was still getting stronger. I'm not sure if he is able to change, but the fact is, there would be no difference. He already got all his power in his normal form, without a change.
According to Dragon Ball Wiki, Daizenshuu 2 commented on the possibility of [Gohan](http://dragonball.wikia.com/wiki/Gohan#Power) becoming a Super Saiyan: > > Daizenshuu 2 states that Ultimate Gohan is still capable of becoming a Super Saiyan, but even without utilising the form he surpasses Super Saiyan 3 Gotenks in power, if Ultimate Gohan was to become a Super Saiyan his power would likely rise to levels above even Super Buu (Gohan, Piccolo, Goten, and Trunks absorbed). > > >
11,560
In DBZ, we see that the Elder Kai fully awakens the dormant power of Gohan. In this state Gohan can match Buu in his unfused form. But after Buu absorbs Piccolo and Gotenks, why doesn't Gohan go Super? Is there any reason that Gohan couldn't transform to Super Saiyan form after the awakening? Edit 1: Removed the transformation in GT from consideration because DBZ and GT are seperate canons. Edit 2: Dragon Ball Super has canon continuity to DBZ and I've heard talks of Ultimate Gohan in it. Has more information been provided on Gohan's transformation in DBS? Please Note: Yet to see DBS beyond the intial movies.
2014/06/30
[ "https://anime.stackexchange.com/questions/11560", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/6368/" ]
I think I found a possible answer, because I had a similar question. In [Gohan](http://dragonball.wikia.com/wiki/Gohan) article on Dragon Ball Wiki. > > However, amazed at realizing that > some of his power really was unlocked, Gohan apologizes to Old Kai, > and resumes the ritual. **After some time, the ritual is finally > completed and Gohan is told to power up like he does for the Super > Saiyan transformation; however, when he does, his appearance does not > change, but his power and strength gain an awesome increase.** > > > So it seems when Gohan got "Mystic Gohan", even though he increased his power, his appearance didn't change. So he couldn't transform in any other Saiyan form than the normal form, but he was still getting stronger. I'm not sure if he is able to change, but the fact is, there would be no difference. He already got all his power in his normal form, without a change.
The answer is yes. His power was fully awaken and so he had no need to transform into super Saiyan. He could go super but he didn't know that Buu could absorb people and their power level. When he is in mystic form his full power was awaken and he had the same power as he did as super Saiyan. so his base power was risen. He can still transform into a SS or SS2 at any point he wants to. Its just the fact that he has the same power level and so he doesn't see the point to. A good sight for you to look at the goes more in detail is [Dragonball wiki](http://dragonball.wikia.com/wiki/Forum:Why_can't_Ultimate_Gohan_go_ssj%3F)
11,560
In DBZ, we see that the Elder Kai fully awakens the dormant power of Gohan. In this state Gohan can match Buu in his unfused form. But after Buu absorbs Piccolo and Gotenks, why doesn't Gohan go Super? Is there any reason that Gohan couldn't transform to Super Saiyan form after the awakening? Edit 1: Removed the transformation in GT from consideration because DBZ and GT are seperate canons. Edit 2: Dragon Ball Super has canon continuity to DBZ and I've heard talks of Ultimate Gohan in it. Has more information been provided on Gohan's transformation in DBS? Please Note: Yet to see DBS beyond the intial movies.
2014/06/30
[ "https://anime.stackexchange.com/questions/11560", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/6368/" ]
I think I found a possible answer, because I had a similar question. In [Gohan](http://dragonball.wikia.com/wiki/Gohan) article on Dragon Ball Wiki. > > However, amazed at realizing that > some of his power really was unlocked, Gohan apologizes to Old Kai, > and resumes the ritual. **After some time, the ritual is finally > completed and Gohan is told to power up like he does for the Super > Saiyan transformation; however, when he does, his appearance does not > change, but his power and strength gain an awesome increase.** > > > So it seems when Gohan got "Mystic Gohan", even though he increased his power, his appearance didn't change. So he couldn't transform in any other Saiyan form than the normal form, but he was still getting stronger. I'm not sure if he is able to change, but the fact is, there would be no difference. He already got all his power in his normal form, without a change.
The answer is actually no. Gohan's Mystic Powerup IS his Super Saiyan transformation which is why elder Kai tells him to powerup as if he were transforming.
11,560
In DBZ, we see that the Elder Kai fully awakens the dormant power of Gohan. In this state Gohan can match Buu in his unfused form. But after Buu absorbs Piccolo and Gotenks, why doesn't Gohan go Super? Is there any reason that Gohan couldn't transform to Super Saiyan form after the awakening? Edit 1: Removed the transformation in GT from consideration because DBZ and GT are seperate canons. Edit 2: Dragon Ball Super has canon continuity to DBZ and I've heard talks of Ultimate Gohan in it. Has more information been provided on Gohan's transformation in DBS? Please Note: Yet to see DBS beyond the intial movies.
2014/06/30
[ "https://anime.stackexchange.com/questions/11560", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/6368/" ]
In Dragon Ball Super when training with Piccolo Gohan powered up to super saiyan 2, and then he made a final effort and transformed into mystic form , passing from super saiyan 2 to mystic form in a gradual change, as a next stage, so no, now with Dragon Ball Super the answer is clear, he can't transform into super saiyan when in mystic form because it's another stage of power. You can see it here: <https://www.youtube.com/watch?v=8G4shXF9bo0>
Actually, Gohan's Mystic Power-Up actually made it so his ki transformed to that of a Kai, but doing so made it so that his appearance doesn't change when he goes Super Saiyan. When he fought Super Buu, he was actually a Super Saiyan 2 charged by Kai energy, but the Kai powers he got from his Mystic training made his Super Saiyan lose the aura and hair and eye color. Apparently that Kai training has worn off by the events of Battle of the Gods, Resurrection F and Dragon Ball Super because he went back to not training.
11,560
In DBZ, we see that the Elder Kai fully awakens the dormant power of Gohan. In this state Gohan can match Buu in his unfused form. But after Buu absorbs Piccolo and Gotenks, why doesn't Gohan go Super? Is there any reason that Gohan couldn't transform to Super Saiyan form after the awakening? Edit 1: Removed the transformation in GT from consideration because DBZ and GT are seperate canons. Edit 2: Dragon Ball Super has canon continuity to DBZ and I've heard talks of Ultimate Gohan in it. Has more information been provided on Gohan's transformation in DBS? Please Note: Yet to see DBS beyond the intial movies.
2014/06/30
[ "https://anime.stackexchange.com/questions/11560", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/6368/" ]
The answer is yes. His power was fully awaken and so he had no need to transform into super Saiyan. He could go super but he didn't know that Buu could absorb people and their power level. When he is in mystic form his full power was awaken and he had the same power as he did as super Saiyan. so his base power was risen. He can still transform into a SS or SS2 at any point he wants to. Its just the fact that he has the same power level and so he doesn't see the point to. A good sight for you to look at the goes more in detail is [Dragonball wiki](http://dragonball.wikia.com/wiki/Forum:Why_can't_Ultimate_Gohan_go_ssj%3F)
It makes perfect sense that Ultimate Gohan (the official name for the "form") can go Super Saiyan. Whenever Gohan had sudden outburst of rage and power he utilized and unleashed very small portions of his full power, the greatest example of this was him transforming into and SSJ2 against Perfect Cell. The Super Saiyan forms are only multipliers, and are NOT set levels of power. Ultimate Gohan is just Gohan with his potential unlocked, he can't get stronger than that naturally, but utilizing forms and skills like the Kaio-ken, and Super Saiyan forms would multiply his power. For further proof, the Daizenshuu 2 clearly states that Ultimate Gohan can go Super Saiyan, and doing that would make him even stronger that Buuhan.
11,560
In DBZ, we see that the Elder Kai fully awakens the dormant power of Gohan. In this state Gohan can match Buu in his unfused form. But after Buu absorbs Piccolo and Gotenks, why doesn't Gohan go Super? Is there any reason that Gohan couldn't transform to Super Saiyan form after the awakening? Edit 1: Removed the transformation in GT from consideration because DBZ and GT are seperate canons. Edit 2: Dragon Ball Super has canon continuity to DBZ and I've heard talks of Ultimate Gohan in it. Has more information been provided on Gohan's transformation in DBS? Please Note: Yet to see DBS beyond the intial movies.
2014/06/30
[ "https://anime.stackexchange.com/questions/11560", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/6368/" ]
In Dragon Ball Super when training with Piccolo Gohan powered up to super saiyan 2, and then he made a final effort and transformed into mystic form , passing from super saiyan 2 to mystic form in a gradual change, as a next stage, so no, now with Dragon Ball Super the answer is clear, he can't transform into super saiyan when in mystic form because it's another stage of power. You can see it here: <https://www.youtube.com/watch?v=8G4shXF9bo0>
It makes perfect sense that Ultimate Gohan (the official name for the "form") can go Super Saiyan. Whenever Gohan had sudden outburst of rage and power he utilized and unleashed very small portions of his full power, the greatest example of this was him transforming into and SSJ2 against Perfect Cell. The Super Saiyan forms are only multipliers, and are NOT set levels of power. Ultimate Gohan is just Gohan with his potential unlocked, he can't get stronger than that naturally, but utilizing forms and skills like the Kaio-ken, and Super Saiyan forms would multiply his power. For further proof, the Daizenshuu 2 clearly states that Ultimate Gohan can go Super Saiyan, and doing that would make him even stronger that Buuhan.
11,560
In DBZ, we see that the Elder Kai fully awakens the dormant power of Gohan. In this state Gohan can match Buu in his unfused form. But after Buu absorbs Piccolo and Gotenks, why doesn't Gohan go Super? Is there any reason that Gohan couldn't transform to Super Saiyan form after the awakening? Edit 1: Removed the transformation in GT from consideration because DBZ and GT are seperate canons. Edit 2: Dragon Ball Super has canon continuity to DBZ and I've heard talks of Ultimate Gohan in it. Has more information been provided on Gohan's transformation in DBS? Please Note: Yet to see DBS beyond the intial movies.
2014/06/30
[ "https://anime.stackexchange.com/questions/11560", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/6368/" ]
The answer is yes. His power was fully awaken and so he had no need to transform into super Saiyan. He could go super but he didn't know that Buu could absorb people and their power level. When he is in mystic form his full power was awaken and he had the same power as he did as super Saiyan. so his base power was risen. He can still transform into a SS or SS2 at any point he wants to. Its just the fact that he has the same power level and so he doesn't see the point to. A good sight for you to look at the goes more in detail is [Dragonball wiki](http://dragonball.wikia.com/wiki/Forum:Why_can't_Ultimate_Gohan_go_ssj%3F)
According to Dragon Ball Wiki, Daizenshuu 2 commented on the possibility of [Gohan](http://dragonball.wikia.com/wiki/Gohan#Power) becoming a Super Saiyan: > > Daizenshuu 2 states that Ultimate Gohan is still capable of becoming a Super Saiyan, but even without utilising the form he surpasses Super Saiyan 3 Gotenks in power, if Ultimate Gohan was to become a Super Saiyan his power would likely rise to levels above even Super Buu (Gohan, Piccolo, Goten, and Trunks absorbed). > > >
11,560
In DBZ, we see that the Elder Kai fully awakens the dormant power of Gohan. In this state Gohan can match Buu in his unfused form. But after Buu absorbs Piccolo and Gotenks, why doesn't Gohan go Super? Is there any reason that Gohan couldn't transform to Super Saiyan form after the awakening? Edit 1: Removed the transformation in GT from consideration because DBZ and GT are seperate canons. Edit 2: Dragon Ball Super has canon continuity to DBZ and I've heard talks of Ultimate Gohan in it. Has more information been provided on Gohan's transformation in DBS? Please Note: Yet to see DBS beyond the intial movies.
2014/06/30
[ "https://anime.stackexchange.com/questions/11560", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/6368/" ]
In Dragon Ball Super when training with Piccolo Gohan powered up to super saiyan 2, and then he made a final effort and transformed into mystic form , passing from super saiyan 2 to mystic form in a gradual change, as a next stage, so no, now with Dragon Ball Super the answer is clear, he can't transform into super saiyan when in mystic form because it's another stage of power. You can see it here: <https://www.youtube.com/watch?v=8G4shXF9bo0>
According to Dragon Ball Wiki, Daizenshuu 2 commented on the possibility of [Gohan](http://dragonball.wikia.com/wiki/Gohan#Power) becoming a Super Saiyan: > > Daizenshuu 2 states that Ultimate Gohan is still capable of becoming a Super Saiyan, but even without utilising the form he surpasses Super Saiyan 3 Gotenks in power, if Ultimate Gohan was to become a Super Saiyan his power would likely rise to levels above even Super Buu (Gohan, Piccolo, Goten, and Trunks absorbed). > > >
11,560
In DBZ, we see that the Elder Kai fully awakens the dormant power of Gohan. In this state Gohan can match Buu in his unfused form. But after Buu absorbs Piccolo and Gotenks, why doesn't Gohan go Super? Is there any reason that Gohan couldn't transform to Super Saiyan form after the awakening? Edit 1: Removed the transformation in GT from consideration because DBZ and GT are seperate canons. Edit 2: Dragon Ball Super has canon continuity to DBZ and I've heard talks of Ultimate Gohan in it. Has more information been provided on Gohan's transformation in DBS? Please Note: Yet to see DBS beyond the intial movies.
2014/06/30
[ "https://anime.stackexchange.com/questions/11560", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/6368/" ]
I think I found a possible answer, because I had a similar question. In [Gohan](http://dragonball.wikia.com/wiki/Gohan) article on Dragon Ball Wiki. > > However, amazed at realizing that > some of his power really was unlocked, Gohan apologizes to Old Kai, > and resumes the ritual. **After some time, the ritual is finally > completed and Gohan is told to power up like he does for the Super > Saiyan transformation; however, when he does, his appearance does not > change, but his power and strength gain an awesome increase.** > > > So it seems when Gohan got "Mystic Gohan", even though he increased his power, his appearance didn't change. So he couldn't transform in any other Saiyan form than the normal form, but he was still getting stronger. I'm not sure if he is able to change, but the fact is, there would be no difference. He already got all his power in his normal form, without a change.
It makes perfect sense that Ultimate Gohan (the official name for the "form") can go Super Saiyan. Whenever Gohan had sudden outburst of rage and power he utilized and unleashed very small portions of his full power, the greatest example of this was him transforming into and SSJ2 against Perfect Cell. The Super Saiyan forms are only multipliers, and are NOT set levels of power. Ultimate Gohan is just Gohan with his potential unlocked, he can't get stronger than that naturally, but utilizing forms and skills like the Kaio-ken, and Super Saiyan forms would multiply his power. For further proof, the Daizenshuu 2 clearly states that Ultimate Gohan can go Super Saiyan, and doing that would make him even stronger that Buuhan.
777,896
I'm planning to record some tutorial videos. How do I make a mouse pointer/cursor with yellow circle around it on Ubuntu 16.04, so my students could see where I am?
2016/05/26
[ "https://askubuntu.com/questions/777896", "https://askubuntu.com", "https://askubuntu.com/users/548944/" ]
Yellow circle can be done by installing any one of the following software: 1. [Cam studio](https://sourceforge.net/projects/camstudio/): Is an open source windows software. Install it using wine then go to cursor settings. There is a cursor highlight. 2. RealWorld Cursor Editor: Also for Windows. Using this, you can directly edit your mouse properties. 3. [vokoscreen](https://packages.ubuntu.com/xenial/vokoscreen): To install `sudo apt-get install vokoscreen` 4. [cairo-dock](http://www.glx-dock.org/) there is a add on to highlight the mouse pointer. 5. Use [gnome-tweak-tool](https://packages.ubuntu.com/source/xenial/gnome-tweak-tool).
I have not tested this, but I think it's the right answer. * Open compiz config: `sudo apt install compizconfig-settings-manager && ccsm` * Look for plugin Show mouse, under Accessibility - ENABLE it.. * Play with it, to see if that's okay :) You'll need `compiz-plugins` package to have this option. [![screenshot](https://i.stack.imgur.com/Hdkug.png)](https://i.stack.imgur.com/Hdkug.png)
777,896
I'm planning to record some tutorial videos. How do I make a mouse pointer/cursor with yellow circle around it on Ubuntu 16.04, so my students could see where I am?
2016/05/26
[ "https://askubuntu.com/questions/777896", "https://askubuntu.com", "https://askubuntu.com/users/548944/" ]
There is no large, colored, or animated mouse cursor by default. To show the mouse position there is a gsetting key to allow showing the cursor position with orange circles upon pressing and releasing the `Ctrl` key: [![![enter image description here](https://i.stack.imgur.com/vBQuq.png)](https://i.stack.imgur.com/vBQuq.png) The key is located in `org.gnome.desktop.interface locate-pointer` accessible through [**dconf-editor**](https://manpages.ubuntu.com/dconf-editor) as shown above or in a terminal with ``` gsettings set org.gnome.desktop.interface locate-pointer true ```
I have not tested this, but I think it's the right answer. * Open compiz config: `sudo apt install compizconfig-settings-manager && ccsm` * Look for plugin Show mouse, under Accessibility - ENABLE it.. * Play with it, to see if that's okay :) You'll need `compiz-plugins` package to have this option. [![screenshot](https://i.stack.imgur.com/Hdkug.png)](https://i.stack.imgur.com/Hdkug.png)
777,896
I'm planning to record some tutorial videos. How do I make a mouse pointer/cursor with yellow circle around it on Ubuntu 16.04, so my students could see where I am?
2016/05/26
[ "https://askubuntu.com/questions/777896", "https://askubuntu.com", "https://askubuntu.com/users/548944/" ]
Highlight Pointer Using Cursor Themes ------------------------------------- I recently wanted to do this as well. I ended up at [this answer](https://unix.stackexchange.com/a/269538) which had some broken links and left me still in search of themes that someone else had surely created. I found one I liked. Here's an animated GIF of what I ended up with and how I got it working. **The end result** [![image.gif](https://s15.postimg.cc/5x197u25n/image.gif)](https://postimg.cc/image/xx5cs45lz/) **Finding a cursor theme** When I realized that this could be accomplished with a cursor theme (duh!), I went in search of some themes. I eventually ended up [here](https://www.gnome-look.org/browse/cat/107/ord/latest/), and after looking through a number of pages of different cursors, I settled on [this one](https://www.gnome-look.org/p/999801/). To download, click the files tab and then download the .tar.gz file for the cursor theme. **Installing and enabling the cursor for screencasting** With the cursor theme downloaded, I got to work on installing it. * The file I downloaded contains multiple themes (each a different color halo) so I first extracted the contents to a temp folder ``` tar -xzf /path/to/download/160115-bDMZT.tar.gz -C /tmp/ ``` * Then I copied the cyan theme to the proper directory, renaming it `screencast` ``` sudo cp -r /tmp/bDMZT/abDMZ/ /usr/share/icons/screencast/ ``` * Before enabling the new cursor theme, I made note of the current theme. ``` OLD_THEME=$(gsettings get org.gnome.desktop.interface cursor-theme) && echo $OLD_THEME ``` * At this point, all that was left to do was to enable the theme. ``` gsettings set org.gnome.desktop.interface cursor-theme screencast ``` If the new theme is active for some applications but not others or if it does not appear to be active at all, you may need to completely terminate all instances of the applications for which it is not active or log off entirely and log back in. **Changing back to the default cursor** Once you're finished your screencast, you may want to switch back to your previous theme (the system default is `DMZ-White`). To do this, run: ``` gsettings set org.gnome.desktop.interface cursor-theme "$OLD_THEME" ``` --- **Extra 2-cents** There are also programs available to [show mouse clicks and key presses](http://www.upubuntu.com/2011/10/show-keyboard-and-mouse-key-presses-and.html) which can be really helpful in screencasts.
I have not tested this, but I think it's the right answer. * Open compiz config: `sudo apt install compizconfig-settings-manager && ccsm` * Look for plugin Show mouse, under Accessibility - ENABLE it.. * Play with it, to see if that's okay :) You'll need `compiz-plugins` package to have this option. [![screenshot](https://i.stack.imgur.com/Hdkug.png)](https://i.stack.imgur.com/Hdkug.png)
17,228,364
I'm creating a .php file that will be uploaded to the root directory of a server. I need that .php file to then figure out the path to the public\_html folder or it's equivalent. I need to do this because I want my .php file to be able to be uploaded to the root and used on any hosting account. Because many hosting companies use different file paths to the public\_html folder or even call it something different, I'm trying to figure out how to detect it. Preferable there is a server variable or easy test to do this. If not, the public\_html folder will always contain a particular file so maybe I could search for this particular file and get the path that way. I'm just worried about a filename search being heavy on memory. The .php file that is being executed is located inside the ROOT directory and needs to locate the public\_html folder. Like this: **/home/user/file.php** needs to detect **/home/user/public\_html/** or **/home/user/var/www/** or **/home/user/website.com/html/** etc.
2013/06/21
[ "https://Stackoverflow.com/questions/17228364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2507749/" ]
The challenge with this is that a server can have very many public\_html's so outside of the context of a request there is no real way to find out what that is. One thing that you might be able to do to get this information from a php script (if you know the url to get to the host) is to create a php file called docroot.php that looks like this. ``` <?php if ($_SERVER["REMOTE_ADDR"] == '127.0.0.1'){ echo $_SERVER["DOCUMENT_ROOT"]; } ``` Then within your file.php your would do something like ``` $docRoot = trim(file_get_contents("http://www.mydomain.com/docroot.php")); ``` This makes the assumption that the server can resolve to itself via the local interface by name.
I found [this website](https://wp-mix.com/php-absolute-path-document-root-base-url/) which provided me with the only **good** solution I have found after scouring the web... ``` $root = preg_replace("!${_SERVER['SCRIPT_NAME']}$!", "", $_SERVER['SCRIPT_FILENAME']); ``` The way this works is by getting the full path of the file and then removing the relative path of the file from the full path.
3,591
I have gotten two videos of Chinese movies at Amazon and in fact both had Mandarin soundtracks with a choice of Chinese (simplified or traditional) or English subtitles. That is what I wanted. But in both cases I was buying blind. It seems impossible to get reliable information on the languages of a video either at Amazon or on IMDB (internet movie data base). Can anyone recommend a source that does provide such information?
2013/08/19
[ "https://chinese.stackexchange.com/questions/3591", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/2223/" ]
You can use some video software or website. Like PPS, PPTV, CNTVBOX, Youku, TuDou, Xunlei Kankan, Xunbo, etc etc, but you won't get English subtitle in most of them, although you can find lots of videos with English voiceover. It maybe troublesome if you want to watch movies since they ban IP address outside China accessing movies, but they don't do this on TV shows, so you can watch many of the good China's current TV Shows like 非诚勿扰,非你莫属,康熙来了,快乐大本营, etc etc. Douban (豆瓣), Mtime(时光网)or VeryCD is equivalent to IMDB in China, IMDB sucks at Asian movies database, so you can search the movie you wanted in these sites, then looking for the specific video/movies on the resource website above.
For a beginner of Chinese-learning, you can watch CCTV: 学说中国话,朋友遍天下 (Learning Chinese, full with friends):<http://english.cntv.cn/learnchinese/> Besides this, you can also see this **[Thread](https://chinese.stackexchange.com/questions/1120/resources-for-learning-mandarin-chinese)**.
3,591
I have gotten two videos of Chinese movies at Amazon and in fact both had Mandarin soundtracks with a choice of Chinese (simplified or traditional) or English subtitles. That is what I wanted. But in both cases I was buying blind. It seems impossible to get reliable information on the languages of a video either at Amazon or on IMDB (internet movie data base). Can anyone recommend a source that does provide such information?
2013/08/19
[ "https://chinese.stackexchange.com/questions/3591", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/2223/" ]
> > You see, I want to hear actual Chinese spoken at normal speed for the length of a movie or tv show. So 学说中国话 is run to hear but not really what I want. > > > Oh, it seems that you can find more and more Chinese news played in CCTV4 (Chinese International Channel), this is now standard Chinese news for you to listen to: **<http://cctv4asia.cntv.cn/>** And what's more, you can watch FREE Chinese movie here:<http://list.iqiyi.com/www/2/15------------5-1-1----.html>
You can use some video software or website. Like PPS, PPTV, CNTVBOX, Youku, TuDou, Xunlei Kankan, Xunbo, etc etc, but you won't get English subtitle in most of them, although you can find lots of videos with English voiceover. It maybe troublesome if you want to watch movies since they ban IP address outside China accessing movies, but they don't do this on TV shows, so you can watch many of the good China's current TV Shows like 非诚勿扰,非你莫属,康熙来了,快乐大本营, etc etc. Douban (豆瓣), Mtime(时光网)or VeryCD is equivalent to IMDB in China, IMDB sucks at Asian movies database, so you can search the movie you wanted in these sites, then looking for the specific video/movies on the resource website above.
3,591
I have gotten two videos of Chinese movies at Amazon and in fact both had Mandarin soundtracks with a choice of Chinese (simplified or traditional) or English subtitles. That is what I wanted. But in both cases I was buying blind. It seems impossible to get reliable information on the languages of a video either at Amazon or on IMDB (internet movie data base). Can anyone recommend a source that does provide such information?
2013/08/19
[ "https://chinese.stackexchange.com/questions/3591", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/2223/" ]
Maybe you can find something useful at www.shooter.cn. Good luck!
You can use some video software or website. Like PPS, PPTV, CNTVBOX, Youku, TuDou, Xunlei Kankan, Xunbo, etc etc, but you won't get English subtitle in most of them, although you can find lots of videos with English voiceover. It maybe troublesome if you want to watch movies since they ban IP address outside China accessing movies, but they don't do this on TV shows, so you can watch many of the good China's current TV Shows like 非诚勿扰,非你莫属,康熙来了,快乐大本营, etc etc. Douban (豆瓣), Mtime(时光网)or VeryCD is equivalent to IMDB in China, IMDB sucks at Asian movies database, so you can search the movie you wanted in these sites, then looking for the specific video/movies on the resource website above.
3,591
I have gotten two videos of Chinese movies at Amazon and in fact both had Mandarin soundtracks with a choice of Chinese (simplified or traditional) or English subtitles. That is what I wanted. But in both cases I was buying blind. It seems impossible to get reliable information on the languages of a video either at Amazon or on IMDB (internet movie data base). Can anyone recommend a source that does provide such information?
2013/08/19
[ "https://chinese.stackexchange.com/questions/3591", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/2223/" ]
> > You see, I want to hear actual Chinese spoken at normal speed for the length of a movie or tv show. So 学说中国话 is run to hear but not really what I want. > > > Oh, it seems that you can find more and more Chinese news played in CCTV4 (Chinese International Channel), this is now standard Chinese news for you to listen to: **<http://cctv4asia.cntv.cn/>** And what's more, you can watch FREE Chinese movie here:<http://list.iqiyi.com/www/2/15------------5-1-1----.html>
For a beginner of Chinese-learning, you can watch CCTV: 学说中国话,朋友遍天下 (Learning Chinese, full with friends):<http://english.cntv.cn/learnchinese/> Besides this, you can also see this **[Thread](https://chinese.stackexchange.com/questions/1120/resources-for-learning-mandarin-chinese)**.
3,591
I have gotten two videos of Chinese movies at Amazon and in fact both had Mandarin soundtracks with a choice of Chinese (simplified or traditional) or English subtitles. That is what I wanted. But in both cases I was buying blind. It seems impossible to get reliable information on the languages of a video either at Amazon or on IMDB (internet movie data base). Can anyone recommend a source that does provide such information?
2013/08/19
[ "https://chinese.stackexchange.com/questions/3591", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/2223/" ]
If you are / were a player of World of Warcraft, you may wanna check a Chinese cartoon name I'm MT 我叫MT. This cartoon series are recorded in Chinese but have English subtitles. As a cartoon, the charters are talking mostly in oral Chinese, without so many attention about grammar, but very closed to real Chinese conversations. The subject of this cartoon is based on that online game. If you are not familiar with that, this is not a good choice.
For a beginner of Chinese-learning, you can watch CCTV: 学说中国话,朋友遍天下 (Learning Chinese, full with friends):<http://english.cntv.cn/learnchinese/> Besides this, you can also see this **[Thread](https://chinese.stackexchange.com/questions/1120/resources-for-learning-mandarin-chinese)**.
3,591
I have gotten two videos of Chinese movies at Amazon and in fact both had Mandarin soundtracks with a choice of Chinese (simplified or traditional) or English subtitles. That is what I wanted. But in both cases I was buying blind. It seems impossible to get reliable information on the languages of a video either at Amazon or on IMDB (internet movie data base). Can anyone recommend a source that does provide such information?
2013/08/19
[ "https://chinese.stackexchange.com/questions/3591", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/2223/" ]
Maybe you can find something useful at www.shooter.cn. Good luck!
For a beginner of Chinese-learning, you can watch CCTV: 学说中国话,朋友遍天下 (Learning Chinese, full with friends):<http://english.cntv.cn/learnchinese/> Besides this, you can also see this **[Thread](https://chinese.stackexchange.com/questions/1120/resources-for-learning-mandarin-chinese)**.
3,591
I have gotten two videos of Chinese movies at Amazon and in fact both had Mandarin soundtracks with a choice of Chinese (simplified or traditional) or English subtitles. That is what I wanted. But in both cases I was buying blind. It seems impossible to get reliable information on the languages of a video either at Amazon or on IMDB (internet movie data base). Can anyone recommend a source that does provide such information?
2013/08/19
[ "https://chinese.stackexchange.com/questions/3591", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/2223/" ]
> > You see, I want to hear actual Chinese spoken at normal speed for the length of a movie or tv show. So 学说中国话 is run to hear but not really what I want. > > > Oh, it seems that you can find more and more Chinese news played in CCTV4 (Chinese International Channel), this is now standard Chinese news for you to listen to: **<http://cctv4asia.cntv.cn/>** And what's more, you can watch FREE Chinese movie here:<http://list.iqiyi.com/www/2/15------------5-1-1----.html>
If you are / were a player of World of Warcraft, you may wanna check a Chinese cartoon name I'm MT 我叫MT. This cartoon series are recorded in Chinese but have English subtitles. As a cartoon, the charters are talking mostly in oral Chinese, without so many attention about grammar, but very closed to real Chinese conversations. The subject of this cartoon is based on that online game. If you are not familiar with that, this is not a good choice.
3,591
I have gotten two videos of Chinese movies at Amazon and in fact both had Mandarin soundtracks with a choice of Chinese (simplified or traditional) or English subtitles. That is what I wanted. But in both cases I was buying blind. It seems impossible to get reliable information on the languages of a video either at Amazon or on IMDB (internet movie data base). Can anyone recommend a source that does provide such information?
2013/08/19
[ "https://chinese.stackexchange.com/questions/3591", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/2223/" ]
Maybe you can find something useful at www.shooter.cn. Good luck!
> > You see, I want to hear actual Chinese spoken at normal speed for the length of a movie or tv show. So 学说中国话 is run to hear but not really what I want. > > > Oh, it seems that you can find more and more Chinese news played in CCTV4 (Chinese International Channel), this is now standard Chinese news for you to listen to: **<http://cctv4asia.cntv.cn/>** And what's more, you can watch FREE Chinese movie here:<http://list.iqiyi.com/www/2/15------------5-1-1----.html>
3,591
I have gotten two videos of Chinese movies at Amazon and in fact both had Mandarin soundtracks with a choice of Chinese (simplified or traditional) or English subtitles. That is what I wanted. But in both cases I was buying blind. It seems impossible to get reliable information on the languages of a video either at Amazon or on IMDB (internet movie data base). Can anyone recommend a source that does provide such information?
2013/08/19
[ "https://chinese.stackexchange.com/questions/3591", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/2223/" ]
Maybe you can find something useful at www.shooter.cn. Good luck!
If you are / were a player of World of Warcraft, you may wanna check a Chinese cartoon name I'm MT 我叫MT. This cartoon series are recorded in Chinese but have English subtitles. As a cartoon, the charters are talking mostly in oral Chinese, without so many attention about grammar, but very closed to real Chinese conversations. The subject of this cartoon is based on that online game. If you are not familiar with that, this is not a good choice.
46,477,240
I am trying to find where "code" from df2 appears in any of the "code1,code2,code3" columns in df1 and return the rows from df2 where that match was successful. Here is my sample code: ``` df1 = pd.DataFrame( { 'terms' : ['term1','term2'], 'code1': ['1234x', '4321y'], 'code2': ['2345x','5432y'], 'code3': ['3456x','6543y'] } ) df1 = df1[['terms'] + df1.columns[:-1].tolist()] df2 = pd.DataFrame( { 'name': ['Dan','Sara'], 'rate': ['3','3.5'], 'location': ['FL','OH'], 'code': ['4444g','6543y'] }) df2 = df2[['name','rate','location','code']] #combining code1,code2,code3 into new column df1['allcodes'] df1['allcodes'] = df1[df1.columns[1:]].apply(lambda x: ','.join(x.dropna().astype(str)),axis=1) print(df2[df2['code'].isin(df1['allcodes'])]) ``` The desired result would be the row from df2 where the code was found in df1: ``` name rate location code 1 Sara 3.5 OH 6543y ``` The result is: ``` Empty DataFrame Columns: [name, rate, location, code] Index: [] ``` why is this returning an empty dataframe?
2017/09/28
[ "https://Stackoverflow.com/questions/46477240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3311213/" ]
**Option 1** `np.in1d` Indiscriminate check if a `df2.code` for a particular row is anywhere in `df1` ``` df2[np.in1d(df2.code, df1[['code1', 'code2', 'code3']])] name rate location code 1 Sara 3.5 OH 6543y ``` Speed it up ``` df2[np.in1d(df2.code.values, df1[['code1', 'code2', 'code3']].values)] ``` --- **Option 2** Check to see if `df2.loc[x, 'code']` is in `df1.loc[x]` We use the `pd.DataFrame.eq` method so we can pass the `axis=0` parameter which checks if a series is equal to each column. Basically, `axis=0` means, align the index (not columns). ``` df2[df1[['code1', 'code2', 'code3']].eq(df2.code, 0).any(1)] name rate location code 1 Sara 3.5 OH 6543y ``` Speed it up ``` df2[(df1[['code1', 'code2', 'code3']].values == df2['code'].values[:, None]).any(1)] ```
Use, `filter` and `stack` ``` In [4647]: df2[df2['code'].isin(df1.filter(like='code').stack())] Out[4647]: name rate location code 1 Sara 3.5 OH 6543y ``` Or, if you're use about `code*` columns to be after `1:` ``` In [4648]: df2[df2['code'].isin(df1[df1.columns[1:]].stack())] Out[4648]: name rate location code 1 Sara 3.5 OH 6543y ``` --- Details ``` In [4649]: df1.filter(like='code') Out[4649]: code1 code2 code3 0 1234x 2345x 3456x 1 4321y 5432y 6543y In [4650]: df1.filter(like='code').stack() Out[4650]: 0 code1 1234x code2 2345x code3 3456x 1 code1 4321y code2 5432y code3 6543y dtype: object In [4651]: df2['code'].isin(df1.filter(like='code').stack()) Out[4651]: 0 False 1 True Name: code, dtype: bool ```
44,498,073
I have a type and a JSON string that can be serialized into this type out of the box: ``` public class MyVar { public string Content { get; set; } public string Type { get; set; } } public class TypeA { public string Name { get; set; } public Dictionary<string, MyVar> Vars { get; set; } } ``` Is it possible to deserialize the same JSON string into a custom type that wraps the dictionary? ``` public class MyVars { private IDictionary<string, MyVar> _vars; public MyVar this[string key] { get { ... } set { ... } } ... } public class TypeA { public string Name { get; set; } public MyVars Vars { get; set; } } ```
2017/06/12
[ "https://Stackoverflow.com/questions/44498073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204688/" ]
Found it. I have to use a JsonConverter attribute. ``` [JsonConverter(typeof(MyVarsConverter))] public MyVars Vars { get; set; } ``` And the implementation of the converter has to do the transformation from dictionary to an MyVars instance: ``` public class MyVarsConverter : JsonConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var dictionary = serializer.Deserialize<Dictionary<string, MyVar>>(reader); var myVars = new MyVars(dictionary); return myVars; } ... } ```
You can do it using Jobject, extract the values using Jobject and set it to the property which you want to to. For eg I have a Jobject jo ``` var name jo.GetValue("Name ").ToString(); ``` You can loop through Jobject and extract and set value to your custom model.
42,897,701
I have an application installed in 20 linux servers. The application contains multiple configuration files such as. ``` /etc/config_1/config_1_1.cfg /etc/config_1/config_1_2.cfg /etc/config_2/config_2_1.cfg /etc/config_2/config_2_2.cfg /etc/config_3/config_3.cfg ``` I will have all these configuration files in all the servers. Now, I wanna compare and find the difference between the config files in all the servers. Eg: Compare `/etc/config_1/config_1_1.cfg` between server1, server2 and server3 etc..
2017/03/20
[ "https://Stackoverflow.com/questions/42897701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2982989/" ]
From command line: `vim -d /etc/config_1/config_1_1.cfg /etc/config_1/config_1_2.cfg /etc/config_2/config_2_1.cfg /etc/config_2/config_2_2.cfg /etc/config_3/config_3.cfg`
Using the file comparison tool.
42,897,701
I have an application installed in 20 linux servers. The application contains multiple configuration files such as. ``` /etc/config_1/config_1_1.cfg /etc/config_1/config_1_2.cfg /etc/config_2/config_2_1.cfg /etc/config_2/config_2_2.cfg /etc/config_3/config_3.cfg ``` I will have all these configuration files in all the servers. Now, I wanna compare and find the difference between the config files in all the servers. Eg: Compare `/etc/config_1/config_1_1.cfg` between server1, server2 and server3 etc..
2017/03/20
[ "https://Stackoverflow.com/questions/42897701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2982989/" ]
When you are only interested in the values, you can do something like ``` grep "." allfiles | sed 's/^\([^:]*\):\(.*\)/\2 : \1/' | sort ```
Using the file comparison tool.
42,897,701
I have an application installed in 20 linux servers. The application contains multiple configuration files such as. ``` /etc/config_1/config_1_1.cfg /etc/config_1/config_1_2.cfg /etc/config_2/config_2_1.cfg /etc/config_2/config_2_2.cfg /etc/config_3/config_3.cfg ``` I will have all these configuration files in all the servers. Now, I wanna compare and find the difference between the config files in all the servers. Eg: Compare `/etc/config_1/config_1_1.cfg` between server1, server2 and server3 etc..
2017/03/20
[ "https://Stackoverflow.com/questions/42897701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2982989/" ]
First, you need to collect the files in the same location to be easier and execute the following command: ``` diffuse x.cfg y.cfg ``` this will give you the ability to highlight the diffrence
Using the file comparison tool.
19,741,717
I have to create UI using the Gridview. The image are dynamic since it is coming from the webservice . I can define column number using the xml but the item at the zeroth index has to have one full image and then the rest should be divided into columns . Any Help is appreciated.
2013/11/02
[ "https://Stackoverflow.com/questions/19741717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1562755/" ]
You shoud use a [`TableLayout`](http://developer.android.com/reference/android/widget/TableLayout.html). `GridView` does not support spanning operations. > > A layout that arranges its children into rows and columns. A > TableLayout consists of a number of TableRow objects, each defining a > row (actually, you can have other children, which will be explained > below). TableLayout containers do not display border lines for their > rows, columns, or cells. Each row has zero or more cells; each cell > can hold one View object. The table has as many columns as the row > with the most cells. A table can leave cells empty. **Cells can span > columns**, as they can in HTML. > > > You can see an example [here](http://www.mkyong.com/android/android-tablelayout-example/).
you can use `GrideView` weight=1 and above of it add `ImageView` for example if you want to use `GrideView` this is full example Layout ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- Large Image --> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_weight="1" android:layout_height="0dip" android:layout_gravity="center_horizontal" android:scaleType="centerCrop" /> <!-- //Large Image --> <!-- Small Images --> <GridView android:id="@+id/list" android:numColumns="auto_fit" android:columnWidth="120dip" android:gravity="center" android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="0dip" > </GridView> <!-- Small Images --> </LinearLayout> ``` this layout will be exactly the same of your request ![enter image description here](https://i.stack.imgur.com/uhXFG.png)
19,741,717
I have to create UI using the Gridview. The image are dynamic since it is coming from the webservice . I can define column number using the xml but the item at the zeroth index has to have one full image and then the rest should be divided into columns . Any Help is appreciated.
2013/11/02
[ "https://Stackoverflow.com/questions/19741717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1562755/" ]
You shoud use a [`TableLayout`](http://developer.android.com/reference/android/widget/TableLayout.html). `GridView` does not support spanning operations. > > A layout that arranges its children into rows and columns. A > TableLayout consists of a number of TableRow objects, each defining a > row (actually, you can have other children, which will be explained > below). TableLayout containers do not display border lines for their > rows, columns, or cells. Each row has zero or more cells; each cell > can hold one View object. The table has as many columns as the row > with the most cells. A table can leave cells empty. **Cells can span > columns**, as they can in HTML. > > > You can see an example [here](http://www.mkyong.com/android/android-tablelayout-example/).
Based on Jack K Fouani. Some changes that will save entire image from cropping: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- Large Image --> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" /> <!-- //Large Image --> <!-- Small Images --> <GridView android:id="@+id/list" android:numColumns="auto_fit" android:columnWidth="120dip" android:gravity="center" android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="0dip" > </GridView> <!-- Small Images --> </LinearLayout> ``` A fast solution, others have a lot of work, try it. you may like it. ``` GridView gv = findViewById(R.id.list); gv.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub } @Override public void onScroll(AbsListView arg0, int firstVisibleItem, int arg2, int arg3) { // TODO Auto-generated method stub ImageView iView = findViewById(R.id.image); if (firstVisibleItem == 0) { iView.setVisibility(View.VISIBLE); } else { iView.setVisibility(View.Gone); } } }); ```
19,741,717
I have to create UI using the Gridview. The image are dynamic since it is coming from the webservice . I can define column number using the xml but the item at the zeroth index has to have one full image and then the rest should be divided into columns . Any Help is appreciated.
2013/11/02
[ "https://Stackoverflow.com/questions/19741717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1562755/" ]
You shoud use a [`TableLayout`](http://developer.android.com/reference/android/widget/TableLayout.html). `GridView` does not support spanning operations. > > A layout that arranges its children into rows and columns. A > TableLayout consists of a number of TableRow objects, each defining a > row (actually, you can have other children, which will be explained > below). TableLayout containers do not display border lines for their > rows, columns, or cells. Each row has zero or more cells; each cell > can hold one View object. The table has as many columns as the row > with the most cells. A table can leave cells empty. **Cells can span > columns**, as they can in HTML. > > > You can see an example [here](http://www.mkyong.com/android/android-tablelayout-example/).
I solved it by using ListView .Added a view to listView Header. Then inside the child for the list view I added two view .In the getView method of the custom adapter I incremented the position by one everytime. P.S: If you want to implement the above view using endless adapter you will have to find a better solution.
19,741,717
I have to create UI using the Gridview. The image are dynamic since it is coming from the webservice . I can define column number using the xml but the item at the zeroth index has to have one full image and then the rest should be divided into columns . Any Help is appreciated.
2013/11/02
[ "https://Stackoverflow.com/questions/19741717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1562755/" ]
Based on Jack K Fouani. Some changes that will save entire image from cropping: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- Large Image --> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" /> <!-- //Large Image --> <!-- Small Images --> <GridView android:id="@+id/list" android:numColumns="auto_fit" android:columnWidth="120dip" android:gravity="center" android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="0dip" > </GridView> <!-- Small Images --> </LinearLayout> ``` A fast solution, others have a lot of work, try it. you may like it. ``` GridView gv = findViewById(R.id.list); gv.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub } @Override public void onScroll(AbsListView arg0, int firstVisibleItem, int arg2, int arg3) { // TODO Auto-generated method stub ImageView iView = findViewById(R.id.image); if (firstVisibleItem == 0) { iView.setVisibility(View.VISIBLE); } else { iView.setVisibility(View.Gone); } } }); ```
you can use `GrideView` weight=1 and above of it add `ImageView` for example if you want to use `GrideView` this is full example Layout ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- Large Image --> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_weight="1" android:layout_height="0dip" android:layout_gravity="center_horizontal" android:scaleType="centerCrop" /> <!-- //Large Image --> <!-- Small Images --> <GridView android:id="@+id/list" android:numColumns="auto_fit" android:columnWidth="120dip" android:gravity="center" android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="0dip" > </GridView> <!-- Small Images --> </LinearLayout> ``` this layout will be exactly the same of your request ![enter image description here](https://i.stack.imgur.com/uhXFG.png)
19,741,717
I have to create UI using the Gridview. The image are dynamic since it is coming from the webservice . I can define column number using the xml but the item at the zeroth index has to have one full image and then the rest should be divided into columns . Any Help is appreciated.
2013/11/02
[ "https://Stackoverflow.com/questions/19741717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1562755/" ]
I solved it by using ListView .Added a view to listView Header. Then inside the child for the list view I added two view .In the getView method of the custom adapter I incremented the position by one everytime. P.S: If you want to implement the above view using endless adapter you will have to find a better solution.
you can use `GrideView` weight=1 and above of it add `ImageView` for example if you want to use `GrideView` this is full example Layout ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- Large Image --> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_weight="1" android:layout_height="0dip" android:layout_gravity="center_horizontal" android:scaleType="centerCrop" /> <!-- //Large Image --> <!-- Small Images --> <GridView android:id="@+id/list" android:numColumns="auto_fit" android:columnWidth="120dip" android:gravity="center" android:layout_width="fill_parent" android:layout_weight="1" android:layout_height="0dip" > </GridView> <!-- Small Images --> </LinearLayout> ``` this layout will be exactly the same of your request ![enter image description here](https://i.stack.imgur.com/uhXFG.png)
78,115
Can I use 0000 steel wool to make a better uniform finish?
2015/11/16
[ "https://diy.stackexchange.com/questions/78115", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/45664/" ]
I would use a dual action orbital sander and wet/dry paper @1200 grit a very wet sponge to dampen the area dont press down let the sander float and as the streaks are cut out the residue will turn milky, keep wiping and moving this high grit with water will leave a mirror finish, I have used 800 & 1000 to remove larger imperfections but the 1200 works best in my opinion. (agree with JPHIL dont use steel wool)
Once the urethane has dried, sanding will only fog up the surface. You could sand it to remove any large imperfections and then put on another coat. If you were getting streaks you may want to work in a slightly cooler area so it takes longer to dry and you have more time to work with it.
68,271,923
I have a docker container that internally starts a server. (I don't own this. I am just reusing it) Once the server starts, I am running some curl commands that hit this server. I am running the above steps in a script. Here's the issue: the docker container starts but internally I think it is taking some time to actually start the server in it. Before that server is up and running, it looks like the curl commands start executing and give an error that server could not be found. If I manually run this a few seconds later, it works fine though. Please let me know if there is a way to solve this. I don't think using entry point or CMD will work for similar reasons. Also, if that matters, the server I am using is kong. thanks, Om.
2021/07/06
[ "https://Stackoverflow.com/questions/68271923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593170/" ]
One way would be like this... ``` #calculate the sd for each row... sds <- apply(m, 1, sd) #generate all noise factors at once and just add to m... m <- m + rnorm(nrow(m) * ncol(m), mean = 0, sd = sds * 0.05) ``` This works because `sds` will be recycled for each column. In general these matrix operations are very fast in R.
This sould do the trick: ``` require(tidyverse) set.seed(1) m = matrix(rnorm(9), nrow = 3, ncol = 3) > m [,1] [,2] [,3] [1,] -0.6264538 1.5952808 0.4874291 [2,] 0.1836433 0.3295078 0.7383247 [3,] -0.8356286 -0.8204684 0.5757814 ``` Calculate `sd` by row ``` m_sd <- apply(m, 1, sd) ``` Calculate noise by row and put it in a matrix ``` m_noise <- map(m_sd, rnorm, n = nrow(m), mean = 0) %>% unlist %>% matrix(nrow = 3, ncol = 3, byrow = TRUE) ``` Add original and noise matrix ``` m + m_noise * 0.05 > m + m_noise * 0.05 [,1] [,2] [,3] [1,] -0.6434161 1.6792503 0.5090823 [2,] 0.1747117 0.2976669 0.7544979 [3,] -0.8374496 -0.8211245 0.6140321 ```
11,819,547
I think that both the question and the answer here shouldn't be very complicated. I have installed and configured the FOSUserBundle to use in a project with Symfony2. What I need to know is where I tell the Security which page it has to redirect the user when they try to access to a forbidden url. By default it is /login. But I'd like to change it to a more general /main. Thanks in advance
2012/08/05
[ "https://Stackoverflow.com/questions/11819547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/882150/" ]
It's not done by FOSUserBundle, but the Security system in Symfony2. You need to set the following in security.yml: ``` firewalls: main: form_login: default_target_path: /path/to/redirect/to ``` EDIT: Sorry, misread the question. Change login\_path to /admin like so: ``` firewalls: main: form_login: login_path: /admin ``` This will redirect you to the /admin page - make sure the path works and isn't protected by the firewall. More info [here](http://symfony.com/doc/current/reference/configuration/security.html#the-login-form-and-process).
Ok I got it! It was more like: ``` main: form_login: login_path: /path/to/redirect/to ``` Thanks again
2,337,767
Let $V$ be a Euclidean vector space with an even dimension and $f: V \to V$ an orthogonal mapping with $\det f= -1$. Is it right, that $f$ has eigenvalues $1$ and $-1$? because of $| \lambda |= 1$. The determinant is the product of the eigenvalues, therefore there must be at least one $-1$. Can you show me the proof that the eigenvalues of $f$ are $1$ and $-1$?
2017/06/27
[ "https://math.stackexchange.com/questions/2337767", "https://math.stackexchange.com", "https://math.stackexchange.com/users/446663/" ]
Yes, but your argument is broken(\*). That the eigenvalues can be nothing else than $1$ and $-1$ follows from the orthogonality of $f$ and **not** the determinant being $-1$. That it actually has these eigenvalues follows from the determinant and even dimension. Suppose that we have an eigenvector $u\ne0$ with eigenvalue $\lambda$, then we have since inner product is preserved $$\lambda^2 \langle u, u\rangle = \langle \lambda u,\lambda u\rangle = \langle fu, fu\rangle = \langle u, u\rangle$$ That is $\lambda^2 = 1$. One can also show that since $\det f=-1$ that there exists eigenvalues. This is because the degree of the characteristic polynomial $p(\lambda)$ must be the same as the dimension of the space. You also have that $\det f = p(0) = -1$. Also we have that the highest order term of the polynomial (of even exponent) has coefficient $1$ that is the polynomial is of the form: So we have that $\lim\_{\lambda\to\pm\infty} p(\lambda) = \infty$ so we have that $p(\lambda) has at least one positive and one negative root. Also we can always construct the case where the multiplicity of these eigenvalues are only $1$. We do this by using rotations in pairwise dimensions, that is: $$f = \begin{pmatrix} -1 & 0 & & & \cdots \\ 0 & 1 & & & \cdots \\ & & 0 & -1 & \\ & & 1 & 0 & \ddots \\ \vdots & \vdots & &\ddots & \ddots \end{pmatrix}$$ that is the second block repeats. One can see that the characteristic polynomial here is $(-1-\lambda)(1-\lambda)(\lambda^2+1)^{n-1}$. (\*) An example when your reason fails is the matrix $$\begin{pmatrix} 2 & 0 & 0 & 0\\ 0 & -2 & 0 &0 \\ 0 & 0 & 0 & -1/2 \\ 0 & 0 & 1/2 & 0 \\ \end{pmatrix}$$ which isn't orthogonal. It's characteristic polynomial is $(2-\lambda)(-2-\lambda)(\lambda^2+1/4)$ so the eigenvalues are $\lambda = \pm2$, but it's determinant is $1$ (which isn't the product of the eigenvalues).
It is not true that all the eigenvalues of $f$ are either $1$ or $-1$. The **real** eigenvalues are. For instance, the eigenvalues of the orthogonal matrix $$f=\begin{pmatrix}\cos\theta&-\sin\theta&0&0\\\sin\theta&\cos\theta&0&0\\0&0&1&0\\0&0&0&-1\\\end{pmatrix}$$ are: $\cos\theta+i\sin\theta,\ \cos\theta-i\sin\theta,\ 1,\ -1$. For a real matrix, though, a complex eigenvalue $z$ with $\Im z\ne 0$ appears with the same algebraic and geometric multiplicities of $\overline z$, thus $$\det f=\left(\prod\_{\omega\in\Bbb R\cap\operatorname{Eig}f} \omega^{m\_{\text{alg}}(\omega)}\right)\cdot\left(\prod\_{\omega\in\operatorname{Eig}f,\ \Im\omega>0} \lvert\omega\rvert^{2m\_{\text{alg}}(\omega)}\right)$$ So, indeed, a real matrix $f$ with $\det f<0$ must have *at least* one real negative eigenvalue.
2,337,767
Let $V$ be a Euclidean vector space with an even dimension and $f: V \to V$ an orthogonal mapping with $\det f= -1$. Is it right, that $f$ has eigenvalues $1$ and $-1$? because of $| \lambda |= 1$. The determinant is the product of the eigenvalues, therefore there must be at least one $-1$. Can you show me the proof that the eigenvalues of $f$ are $1$ and $-1$?
2017/06/27
[ "https://math.stackexchange.com/questions/2337767", "https://math.stackexchange.com", "https://math.stackexchange.com/users/446663/" ]
Yes, but your argument is broken(\*). That the eigenvalues can be nothing else than $1$ and $-1$ follows from the orthogonality of $f$ and **not** the determinant being $-1$. That it actually has these eigenvalues follows from the determinant and even dimension. Suppose that we have an eigenvector $u\ne0$ with eigenvalue $\lambda$, then we have since inner product is preserved $$\lambda^2 \langle u, u\rangle = \langle \lambda u,\lambda u\rangle = \langle fu, fu\rangle = \langle u, u\rangle$$ That is $\lambda^2 = 1$. One can also show that since $\det f=-1$ that there exists eigenvalues. This is because the degree of the characteristic polynomial $p(\lambda)$ must be the same as the dimension of the space. You also have that $\det f = p(0) = -1$. Also we have that the highest order term of the polynomial (of even exponent) has coefficient $1$ that is the polynomial is of the form: So we have that $\lim\_{\lambda\to\pm\infty} p(\lambda) = \infty$ so we have that $p(\lambda) has at least one positive and one negative root. Also we can always construct the case where the multiplicity of these eigenvalues are only $1$. We do this by using rotations in pairwise dimensions, that is: $$f = \begin{pmatrix} -1 & 0 & & & \cdots \\ 0 & 1 & & & \cdots \\ & & 0 & -1 & \\ & & 1 & 0 & \ddots \\ \vdots & \vdots & &\ddots & \ddots \end{pmatrix}$$ that is the second block repeats. One can see that the characteristic polynomial here is $(-1-\lambda)(1-\lambda)(\lambda^2+1)^{n-1}$. (\*) An example when your reason fails is the matrix $$\begin{pmatrix} 2 & 0 & 0 & 0\\ 0 & -2 & 0 &0 \\ 0 & 0 & 0 & -1/2 \\ 0 & 0 & 1/2 & 0 \\ \end{pmatrix}$$ which isn't orthogonal. It's characteristic polynomial is $(2-\lambda)(-2-\lambda)(\lambda^2+1/4)$ so the eigenvalues are $\lambda = \pm2$, but it's determinant is $1$ (which isn't the product of the eigenvalues).
No, real linear operators can have complex eigenvalues, and if you want to not consider those (which is reasonable because they don't have corresponding eigenvectors in your real vector space) then the determinant is not in general the product of all eigenvalues. (In case of a real orthogonal operator there is an additional condition that the eigenvalues (the multi-set of roots of the characteristic polynomial) are both concentrated on the unit circle (the $|\lambda|=1$ condition) and symmetric under complex conjugation, which means that non-real eigenvalues come in pairs whose product is $1$, so the determinant ends up also being the product of the *real* eigenvalues, all $1$ or $-1$. But just saying "the determinant is the product of the eigenvalues" strongly suggests you did not make this reasoning to arrive at the conclusion.) So for instance a plane rotation is real orthogonal but has no real eigenvalues at all. Add an orthogonal eigenvector with eigenvalue $-1$ (giving a roto-reflection) and you have determinant $-1$; you now have odd dimension, so if you want to have even dimension you must also add an eigenvector for $\lambda=1$. Returning to your question, I am not sure I answered it, because I'm not sure what is being asked.
2,337,767
Let $V$ be a Euclidean vector space with an even dimension and $f: V \to V$ an orthogonal mapping with $\det f= -1$. Is it right, that $f$ has eigenvalues $1$ and $-1$? because of $| \lambda |= 1$. The determinant is the product of the eigenvalues, therefore there must be at least one $-1$. Can you show me the proof that the eigenvalues of $f$ are $1$ and $-1$?
2017/06/27
[ "https://math.stackexchange.com/questions/2337767", "https://math.stackexchange.com", "https://math.stackexchange.com/users/446663/" ]
Yes, but your argument is broken(\*). That the eigenvalues can be nothing else than $1$ and $-1$ follows from the orthogonality of $f$ and **not** the determinant being $-1$. That it actually has these eigenvalues follows from the determinant and even dimension. Suppose that we have an eigenvector $u\ne0$ with eigenvalue $\lambda$, then we have since inner product is preserved $$\lambda^2 \langle u, u\rangle = \langle \lambda u,\lambda u\rangle = \langle fu, fu\rangle = \langle u, u\rangle$$ That is $\lambda^2 = 1$. One can also show that since $\det f=-1$ that there exists eigenvalues. This is because the degree of the characteristic polynomial $p(\lambda)$ must be the same as the dimension of the space. You also have that $\det f = p(0) = -1$. Also we have that the highest order term of the polynomial (of even exponent) has coefficient $1$ that is the polynomial is of the form: So we have that $\lim\_{\lambda\to\pm\infty} p(\lambda) = \infty$ so we have that $p(\lambda) has at least one positive and one negative root. Also we can always construct the case where the multiplicity of these eigenvalues are only $1$. We do this by using rotations in pairwise dimensions, that is: $$f = \begin{pmatrix} -1 & 0 & & & \cdots \\ 0 & 1 & & & \cdots \\ & & 0 & -1 & \\ & & 1 & 0 & \ddots \\ \vdots & \vdots & &\ddots & \ddots \end{pmatrix}$$ that is the second block repeats. One can see that the characteristic polynomial here is $(-1-\lambda)(1-\lambda)(\lambda^2+1)^{n-1}$. (\*) An example when your reason fails is the matrix $$\begin{pmatrix} 2 & 0 & 0 & 0\\ 0 & -2 & 0 &0 \\ 0 & 0 & 0 & -1/2 \\ 0 & 0 & 1/2 & 0 \\ \end{pmatrix}$$ which isn't orthogonal. It's characteristic polynomial is $(2-\lambda)(-2-\lambda)(\lambda^2+1/4)$ so the eigenvalues are $\lambda = \pm2$, but it's determinant is $1$ (which isn't the product of the eigenvalues).
The eigenvalues of a real matrix, when considered as complex matrix all of whose entries happen to be real, either are real themselves, or come in complex conjugated pairs. Since the determinant is the product of all eigenvalues, due to the conjugated pair property any complex eigenvalue $\lambda$ gives rise to the factor $\lambda\overline \lambda = \left|\lambda\right|^2>0$, this it in particular cannot change the sign of the determinant. Therefore any real matrix with negative determinant must have at least one negative real eigenvalue. Note that this is true independent of any other properties of the matrix. On the other hand, the eigenvalues of an orthogonal matrix have absolute value $1$. Now the only negative real number with absolute value $1$ is $-1$, therefore a real orthogonal matrix of negative determinant (and therefore determinant $-1$) always has at least one eigenvalue $-1$. Note that this is independent of dimension, that is, it holds both in even and odd dimensions.
6,000,812
What is the algorithm for drawing line on the plane (pointwise), if it is not horizontal or vertical?
2011/05/14
[ "https://Stackoverflow.com/questions/6000812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/603019/" ]
See [Bresenham's algorithm](http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm).
There is no 'pointwise' algorithm - points are infinitesimally small, so any algorithm based on points would take an infinite time to complete. Instead, lines are drawn based on a notional pen width and calculating how many and what intensity of pixels that stroking the line with a pen would cover. If you merely want to turn pixels on and off like it's the 1970s, then use one of the Brensenham's algorithm family. Most modern computer graphics use anti-aliasing algorithms - either stroking, sub-sampling or exact pixel coverage - and sometimes parallel algorithms in the GPU ( for example drawing a line by projecting a thin rectangle onto the plane, or performing coverage calculations per pixel in parallel ). Many graphics algorithms are based on Bezier curves; straight lines are just curves where the control points are in a line, so the algorithms for drawing them are the same, though may make a few optimisations.
53,798,288
I've been experimenting with Node JS recently and for some reason, my code does not continue onto the next step even though it is supposed to. Here is my code: ``` const request = require('request'); var jssoup = require('jssoup').default; const {Harvester} = require('captcha-manager'); const harvester = new Harvester(); async function run(){ // hostname sitekey global.response = await harvester.getResponse('adidas.com', '6LdC0iQUAAAAAOYmRv34KSLDe-7DmQrUSYJH8eB_'); console.log(response); } async function normalCheckout(size, style){ console.log('started'); if (size == 14.5){ var shoesize = style + '_740'; } if (size == 15){ var shoesize = style + '_750'; } if (size == 15.5){ var shoesize = style + '_760'; } if (size == 16){ var shoesize = style + '_770' } console.log(shoesize); var options = { url: 'https://www.adidas.com/us/optik_literally_takes_stock/' + style +'.html', headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' }, form: { "product_id":style, "quantity":1, "product_variation_sku":shoesize, "productId":shoesize, "size":str(size), "displaySize":str(size), "captchaResponse":response }, }; console.log('step finished'); run(); } normalCheckout(16, 'BD7730') ``` NOTE: The dictionary for `form` is formatted correctly in my actual code, for some reason I cannot format it correctly here. When I run it, `started` is logged and the variable `shoesize` is logged but `step finished` is not logged, even though it is supposed to be. Why is this happening and how can I fix this? Additionally, is there any way for me to condense all of my `if` statements?
2018/12/15
[ "https://Stackoverflow.com/questions/53798288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10355744/" ]
According to me the method you are following is correct. The core purpose of *202 Accepted* status is that 'Request is accepted and the server will process it'. Now the only problem I can see here is Until when? To answer that I recommend that you can add some calculation which will check the average time it takes to process a similar request and send them in 1st response. ``` { "id" : 1999283, "message" : "Hello SO friends!", "status" : "pending", "block" : null, "timestamp" : null, "estimatedTime" : 30 //// } ``` **This will have 2 advantages:** **1)** The user will know how much time it will take to process the request and will not poll for that much time saving few hits on the server. **2)** You can have a track of repeated failures for e.g If the same request is failing multiple times then you can increase the priority for that request based on business requirements. Apart from that, other process looks very neat.
An alternative way of looking at this, is maybe it's not a temporary resource. Maybe it's a regular resource that has a state that's incomplete. If you consider it a real resource that will change states later, you don't have to think as much about using `202 Accepted`. The transaction you're creating 'exists', it just hasn't been processed yet.
36,622,422
Which is the better way to set a `Bitmap`, setting it in xml as background or setting it programmatically? I'm encountering `Out of Memory` issue and sometime giving binary xml error.I have used background image of max size 500kb(xxhdpi). So I'm wondering which is the better way to set bitmap as background. Setting bitmap in xml or setting it in programmatically in java class. Does anyone have say about it. Thanks in advance.
2016/04/14
[ "https://Stackoverflow.com/questions/36622422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082923/" ]
I agree with jrturton. It'll only work in highly controlled conditions **and with three beacons** and the result will be far from perfect. Here's what happens when you calculate with two beacons: Just look at it as a triangle. [![enter image description here](https://i.stack.imgur.com/e6miq.png)](https://i.stack.imgur.com/e6miq.png) By using the [distance formula](https://www.mathsisfun.com/algebra/distance-2-points.html) you have two equations: *20m = sqrt( ( 1 - iPhone.x )^2 + ( 2 - iPhone.y )^2) 40m = sqrt( ( 10 - iPhone.x)^2 + ( 2 - iPhone.y )^2)* Now you need to solve for `iPhone.x` and `iPhone.y` 20 ^ 2 = ( 1 - iPhone.x )^2 + ( 2 - iPhone.y )^2 40 ^ 2 = ( 10 - iPhone.x)^2 + ( 2 - iPhone.y )^2 So these are equations for circles and you have to calculate the point at [which they're touching](http://www.mathsmutt.co.uk/files/tcirc.htm). You'll receive two points, not one. [![enter image description here](https://i.stack.imgur.com/nslVW.png)](https://i.stack.imgur.com/nslVW.png) **You can't know the exact position from just two beacons.** **As somebody mentioned in the comments, you need three beacons to do that.**
I've got a good result finally, in order if some one needs the solution: I have considered the p1 and p2 as center of two circles. Then I have calculated the distance between two centers (two points distance formula) like this: `double dx = (b.x-a.x); double dy = (b.y-a.y); double dist = sqrt(dx*dx + dy*dy);` Then I have found a base formula to limit the approximate accuracy to the distance between two points (p1, p2) ``` double l = dist / (dA + dB); ``` Now I got two circles with known centers and calculate the radius based on accuracy and limit ``` float r1 = l * dA; float r2 = l * dB; ``` Now there are two circles with known centers and radius intersecting in single point which is the position of mobile.
36,622,422
Which is the better way to set a `Bitmap`, setting it in xml as background or setting it programmatically? I'm encountering `Out of Memory` issue and sometime giving binary xml error.I have used background image of max size 500kb(xxhdpi). So I'm wondering which is the better way to set bitmap as background. Setting bitmap in xml or setting it in programmatically in java class. Does anyone have say about it. Thanks in advance.
2016/04/14
[ "https://Stackoverflow.com/questions/36622422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4082923/" ]
You can't. All the maths in the world won't change the fact that the RSSI reading you get from beacons fluctuates wildly and in response to dozens of factors outside of your control. The best you can do is to roughly say which beacons you are near, and very roughly how near they are. Any attempt to be more precise than that *will* fail as soon as you test in a real world environment.
I've got a good result finally, in order if some one needs the solution: I have considered the p1 and p2 as center of two circles. Then I have calculated the distance between two centers (two points distance formula) like this: `double dx = (b.x-a.x); double dy = (b.y-a.y); double dist = sqrt(dx*dx + dy*dy);` Then I have found a base formula to limit the approximate accuracy to the distance between two points (p1, p2) ``` double l = dist / (dA + dB); ``` Now I got two circles with known centers and calculate the radius based on accuracy and limit ``` float r1 = l * dA; float r2 = l * dB; ``` Now there are two circles with known centers and radius intersecting in single point which is the position of mobile.
16,237,082
I want to take grouped values (column: 'Criticality') from one table dbo.VTM\_duedate and next count values (column: 'DEVICE\_NAME') in another table dbo.TPM\_scan based on grouped values. Table 1 ``` USE tempdb; GO IF OBJECT_ID('dbo.VTM_duedate') IS NOT NULL DROP TABLE dbo.VTM_duedate; GO CREATE TABLE dbo.VTM_duedate ( Criticality varchar(30) NOT NULL, KB varchar(10) NOT NULL ); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 157848); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 155439); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 635533); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 189164); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 188641); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 537990); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 1349605); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 5646789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6545789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 5637965); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6464367) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1323123) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1004326) ; GO ``` Table 2 ``` USE tempdb; GO IF OBJECT_ID('dbo.TPM_scan') IS NOT NULL DROP TABLE dbo.TPM_scan; GO CREATE TABLE dbo.TPM_scan ( DEVICE_NAME varchar(30) NOT NULL, APP_ID varchar(10) NOT NULL, Criticality varchar(10) NOT NULL ); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 157848, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 155439, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 635533, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 189164, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 188641, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 537990, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 1349605, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('JAP543X2', 5646789, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EU456CLX', 6545789, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 5637965, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 6464367, 'Medium') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1323123, 'High') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1004326, 'Medium') ; GO ``` Expected results: ``` Criticality Device_count Critical 3 High 6 Medium 4 ```
2013/04/26
[ "https://Stackoverflow.com/questions/16237082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2124434/" ]
``` $yesterday = date("Y-m-d", strtotime('-1 day')); $result = mysql_query("SELECT * FROM microcompany WHERE date='$yesterday' AND code='2.0.0'") or die(mysql_error()); ```
``` $date = new DateTime('Yesterday'); echo $date->format('Y-m-d'); ``` Or ``` $date = new DateTime('2013-01-28'); $date->modify('-1 day'); echo $date->format('Y-m-d'); ``` FYI, [you shouldn't use `mysql_*` functions in new code](https://stackoverflow.com/q/12859942/). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [red box](https://www.php.net/manual/en/function.mysql-connect.php)? Learn about [*prepared statements*](https://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://php.net/pdo), or [MySQLi](http://php.net/mysqli) - [this article](https://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide which. If you choose PDO, [here is a good tutorial](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers).
16,237,082
I want to take grouped values (column: 'Criticality') from one table dbo.VTM\_duedate and next count values (column: 'DEVICE\_NAME') in another table dbo.TPM\_scan based on grouped values. Table 1 ``` USE tempdb; GO IF OBJECT_ID('dbo.VTM_duedate') IS NOT NULL DROP TABLE dbo.VTM_duedate; GO CREATE TABLE dbo.VTM_duedate ( Criticality varchar(30) NOT NULL, KB varchar(10) NOT NULL ); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 157848); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 155439); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 635533); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 189164); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 188641); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 537990); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 1349605); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 5646789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6545789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 5637965); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6464367) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1323123) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1004326) ; GO ``` Table 2 ``` USE tempdb; GO IF OBJECT_ID('dbo.TPM_scan') IS NOT NULL DROP TABLE dbo.TPM_scan; GO CREATE TABLE dbo.TPM_scan ( DEVICE_NAME varchar(30) NOT NULL, APP_ID varchar(10) NOT NULL, Criticality varchar(10) NOT NULL ); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 157848, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 155439, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 635533, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 189164, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 188641, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 537990, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 1349605, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('JAP543X2', 5646789, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EU456CLX', 6545789, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 5637965, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 6464367, 'Medium') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1323123, 'High') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1004326, 'Medium') ; GO ``` Expected results: ``` Criticality Device_count Critical 3 High 6 Medium 4 ```
2013/04/26
[ "https://Stackoverflow.com/questions/16237082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2124434/" ]
``` $yesterday = date("Y-m-d", strtotime('-1 day')); $result = mysql_query("SELECT * FROM microcompany WHERE date='$yesterday' AND code='2.0.0'") or die(mysql_error()); ```
use native mysql functions for that purpose. ``` $result = mysql_query("SELECT * FROM microcompany WHERE date=date_sub(date(now()), interval 1 day) AND code='2.0.0'") or die(mysql_error()); ```
16,237,082
I want to take grouped values (column: 'Criticality') from one table dbo.VTM\_duedate and next count values (column: 'DEVICE\_NAME') in another table dbo.TPM\_scan based on grouped values. Table 1 ``` USE tempdb; GO IF OBJECT_ID('dbo.VTM_duedate') IS NOT NULL DROP TABLE dbo.VTM_duedate; GO CREATE TABLE dbo.VTM_duedate ( Criticality varchar(30) NOT NULL, KB varchar(10) NOT NULL ); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 157848); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 155439); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 635533); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 189164); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 188641); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 537990); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 1349605); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 5646789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6545789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 5637965); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6464367) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1323123) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1004326) ; GO ``` Table 2 ``` USE tempdb; GO IF OBJECT_ID('dbo.TPM_scan') IS NOT NULL DROP TABLE dbo.TPM_scan; GO CREATE TABLE dbo.TPM_scan ( DEVICE_NAME varchar(30) NOT NULL, APP_ID varchar(10) NOT NULL, Criticality varchar(10) NOT NULL ); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 157848, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 155439, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 635533, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 189164, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 188641, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 537990, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 1349605, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('JAP543X2', 5646789, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EU456CLX', 6545789, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 5637965, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 6464367, 'Medium') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1323123, 'High') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1004326, 'Medium') ; GO ``` Expected results: ``` Criticality Device_count Critical 3 High 6 Medium 4 ```
2013/04/26
[ "https://Stackoverflow.com/questions/16237082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2124434/" ]
Why not use the MySQL function? They are meant to be used in MySQL. ``` SELECT * FROM microcompany WHERE date=DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) AND code='2.0.0' ``` btw. mysql-\* functions are deprecated: <http://www.php.net/manual/en/function.mysql-query.php>
``` $date = new DateTime('Yesterday'); $fdate = $date->format('Y-m-d'); echo $fdate; ```
16,237,082
I want to take grouped values (column: 'Criticality') from one table dbo.VTM\_duedate and next count values (column: 'DEVICE\_NAME') in another table dbo.TPM\_scan based on grouped values. Table 1 ``` USE tempdb; GO IF OBJECT_ID('dbo.VTM_duedate') IS NOT NULL DROP TABLE dbo.VTM_duedate; GO CREATE TABLE dbo.VTM_duedate ( Criticality varchar(30) NOT NULL, KB varchar(10) NOT NULL ); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 157848); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 155439); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 635533); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 189164); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 188641); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 537990); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 1349605); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 5646789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6545789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 5637965); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6464367) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1323123) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1004326) ; GO ``` Table 2 ``` USE tempdb; GO IF OBJECT_ID('dbo.TPM_scan') IS NOT NULL DROP TABLE dbo.TPM_scan; GO CREATE TABLE dbo.TPM_scan ( DEVICE_NAME varchar(30) NOT NULL, APP_ID varchar(10) NOT NULL, Criticality varchar(10) NOT NULL ); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 157848, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 155439, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 635533, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 189164, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 188641, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 537990, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 1349605, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('JAP543X2', 5646789, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EU456CLX', 6545789, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 5637965, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 6464367, 'Medium') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1323123, 'High') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1004326, 'Medium') ; GO ``` Expected results: ``` Criticality Device_count Critical 3 High 6 Medium 4 ```
2013/04/26
[ "https://Stackoverflow.com/questions/16237082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2124434/" ]
Why not use the MySQL function? They are meant to be used in MySQL. ``` SELECT * FROM microcompany WHERE date=DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) AND code='2.0.0' ``` btw. mysql-\* functions are deprecated: <http://www.php.net/manual/en/function.mysql-query.php>
use native mysql functions for that purpose. ``` $result = mysql_query("SELECT * FROM microcompany WHERE date=date_sub(date(now()), interval 1 day) AND code='2.0.0'") or die(mysql_error()); ```
16,237,082
I want to take grouped values (column: 'Criticality') from one table dbo.VTM\_duedate and next count values (column: 'DEVICE\_NAME') in another table dbo.TPM\_scan based on grouped values. Table 1 ``` USE tempdb; GO IF OBJECT_ID('dbo.VTM_duedate') IS NOT NULL DROP TABLE dbo.VTM_duedate; GO CREATE TABLE dbo.VTM_duedate ( Criticality varchar(30) NOT NULL, KB varchar(10) NOT NULL ); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 157848); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 155439); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 635533); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 189164); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 188641); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 537990); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 1349605); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 5646789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6545789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 5637965); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6464367) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1323123) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1004326) ; GO ``` Table 2 ``` USE tempdb; GO IF OBJECT_ID('dbo.TPM_scan') IS NOT NULL DROP TABLE dbo.TPM_scan; GO CREATE TABLE dbo.TPM_scan ( DEVICE_NAME varchar(30) NOT NULL, APP_ID varchar(10) NOT NULL, Criticality varchar(10) NOT NULL ); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 157848, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 155439, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 635533, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 189164, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 188641, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 537990, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 1349605, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('JAP543X2', 5646789, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EU456CLX', 6545789, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 5637965, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 6464367, 'Medium') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1323123, 'High') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1004326, 'Medium') ; GO ``` Expected results: ``` Criticality Device_count Critical 3 High 6 Medium 4 ```
2013/04/26
[ "https://Stackoverflow.com/questions/16237082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2124434/" ]
use native mysql functions for that purpose. ``` $result = mysql_query("SELECT * FROM microcompany WHERE date=date_sub(date(now()), interval 1 day) AND code='2.0.0'") or die(mysql_error()); ```
``` <?php $yesterday = date('Y-m-d', strtotime('-1 day',strtotime(date("y-m-d")) )); $query = "SELECT * FROM microcompany WHERE date='".$yesterday."' AND code='2.0.0'"; $newQuery = 'update microcompany set date = "'.$yesterday.' where date = "'.$oldDate.'" and code ="2.0.0"'; ?> ```
16,237,082
I want to take grouped values (column: 'Criticality') from one table dbo.VTM\_duedate and next count values (column: 'DEVICE\_NAME') in another table dbo.TPM\_scan based on grouped values. Table 1 ``` USE tempdb; GO IF OBJECT_ID('dbo.VTM_duedate') IS NOT NULL DROP TABLE dbo.VTM_duedate; GO CREATE TABLE dbo.VTM_duedate ( Criticality varchar(30) NOT NULL, KB varchar(10) NOT NULL ); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 157848); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 155439); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 635533); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 189164); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 188641); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 537990); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 1349605); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 5646789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6545789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 5637965); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6464367) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1323123) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1004326) ; GO ``` Table 2 ``` USE tempdb; GO IF OBJECT_ID('dbo.TPM_scan') IS NOT NULL DROP TABLE dbo.TPM_scan; GO CREATE TABLE dbo.TPM_scan ( DEVICE_NAME varchar(30) NOT NULL, APP_ID varchar(10) NOT NULL, Criticality varchar(10) NOT NULL ); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 157848, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 155439, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 635533, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 189164, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 188641, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 537990, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 1349605, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('JAP543X2', 5646789, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EU456CLX', 6545789, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 5637965, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 6464367, 'Medium') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1323123, 'High') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1004326, 'Medium') ; GO ``` Expected results: ``` Criticality Device_count Critical 3 High 6 Medium 4 ```
2013/04/26
[ "https://Stackoverflow.com/questions/16237082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2124434/" ]
Why not use the MySQL function? They are meant to be used in MySQL. ``` SELECT * FROM microcompany WHERE date=DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) AND code='2.0.0' ``` btw. mysql-\* functions are deprecated: <http://www.php.net/manual/en/function.mysql-query.php>
``` $date = new DateTime('Yesterday'); echo $date->format('Y-m-d'); ``` Or ``` $date = new DateTime('2013-01-28'); $date->modify('-1 day'); echo $date->format('Y-m-d'); ``` FYI, [you shouldn't use `mysql_*` functions in new code](https://stackoverflow.com/q/12859942/). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [red box](https://www.php.net/manual/en/function.mysql-connect.php)? Learn about [*prepared statements*](https://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://php.net/pdo), or [MySQLi](http://php.net/mysqli) - [this article](https://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide which. If you choose PDO, [here is a good tutorial](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers).
16,237,082
I want to take grouped values (column: 'Criticality') from one table dbo.VTM\_duedate and next count values (column: 'DEVICE\_NAME') in another table dbo.TPM\_scan based on grouped values. Table 1 ``` USE tempdb; GO IF OBJECT_ID('dbo.VTM_duedate') IS NOT NULL DROP TABLE dbo.VTM_duedate; GO CREATE TABLE dbo.VTM_duedate ( Criticality varchar(30) NOT NULL, KB varchar(10) NOT NULL ); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 157848); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 155439); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 635533); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 189164); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 188641); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 537990); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 1349605); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 5646789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6545789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 5637965); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6464367) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1323123) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1004326) ; GO ``` Table 2 ``` USE tempdb; GO IF OBJECT_ID('dbo.TPM_scan') IS NOT NULL DROP TABLE dbo.TPM_scan; GO CREATE TABLE dbo.TPM_scan ( DEVICE_NAME varchar(30) NOT NULL, APP_ID varchar(10) NOT NULL, Criticality varchar(10) NOT NULL ); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 157848, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 155439, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 635533, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 189164, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 188641, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 537990, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 1349605, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('JAP543X2', 5646789, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EU456CLX', 6545789, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 5637965, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 6464367, 'Medium') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1323123, 'High') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1004326, 'Medium') ; GO ``` Expected results: ``` Criticality Device_count Critical 3 High 6 Medium 4 ```
2013/04/26
[ "https://Stackoverflow.com/questions/16237082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2124434/" ]
``` $yesterday = date("Y-m-d", strtotime('-1 day')); $result = mysql_query("SELECT * FROM microcompany WHERE date='$yesterday' AND code='2.0.0'") or die(mysql_error()); ```
``` $date = new DateTime('Yesterday'); $fdate = $date->format('Y-m-d'); echo $fdate; ```
16,237,082
I want to take grouped values (column: 'Criticality') from one table dbo.VTM\_duedate and next count values (column: 'DEVICE\_NAME') in another table dbo.TPM\_scan based on grouped values. Table 1 ``` USE tempdb; GO IF OBJECT_ID('dbo.VTM_duedate') IS NOT NULL DROP TABLE dbo.VTM_duedate; GO CREATE TABLE dbo.VTM_duedate ( Criticality varchar(30) NOT NULL, KB varchar(10) NOT NULL ); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 157848); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 155439); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 635533); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 189164); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 188641); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 537990); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 1349605); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 5646789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6545789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 5637965); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6464367) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1323123) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1004326) ; GO ``` Table 2 ``` USE tempdb; GO IF OBJECT_ID('dbo.TPM_scan') IS NOT NULL DROP TABLE dbo.TPM_scan; GO CREATE TABLE dbo.TPM_scan ( DEVICE_NAME varchar(30) NOT NULL, APP_ID varchar(10) NOT NULL, Criticality varchar(10) NOT NULL ); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 157848, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 155439, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 635533, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 189164, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 188641, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 537990, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 1349605, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('JAP543X2', 5646789, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EU456CLX', 6545789, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 5637965, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 6464367, 'Medium') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1323123, 'High') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1004326, 'Medium') ; GO ``` Expected results: ``` Criticality Device_count Critical 3 High 6 Medium 4 ```
2013/04/26
[ "https://Stackoverflow.com/questions/16237082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2124434/" ]
``` $date = new DateTime('Yesterday'); $fdate = $date->format('Y-m-d'); echo $fdate; ```
``` <?php $yesterday = date('Y-m-d', strtotime('-1 day',strtotime(date("y-m-d")) )); $query = "SELECT * FROM microcompany WHERE date='".$yesterday."' AND code='2.0.0'"; $newQuery = 'update microcompany set date = "'.$yesterday.' where date = "'.$oldDate.'" and code ="2.0.0"'; ?> ```
16,237,082
I want to take grouped values (column: 'Criticality') from one table dbo.VTM\_duedate and next count values (column: 'DEVICE\_NAME') in another table dbo.TPM\_scan based on grouped values. Table 1 ``` USE tempdb; GO IF OBJECT_ID('dbo.VTM_duedate') IS NOT NULL DROP TABLE dbo.VTM_duedate; GO CREATE TABLE dbo.VTM_duedate ( Criticality varchar(30) NOT NULL, KB varchar(10) NOT NULL ); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 157848); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 155439); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 635533); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 189164); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 188641); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 537990); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 1349605); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 5646789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6545789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 5637965); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6464367) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1323123) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1004326) ; GO ``` Table 2 ``` USE tempdb; GO IF OBJECT_ID('dbo.TPM_scan') IS NOT NULL DROP TABLE dbo.TPM_scan; GO CREATE TABLE dbo.TPM_scan ( DEVICE_NAME varchar(30) NOT NULL, APP_ID varchar(10) NOT NULL, Criticality varchar(10) NOT NULL ); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 157848, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 155439, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 635533, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 189164, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 188641, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 537990, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 1349605, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('JAP543X2', 5646789, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EU456CLX', 6545789, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 5637965, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 6464367, 'Medium') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1323123, 'High') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1004326, 'Medium') ; GO ``` Expected results: ``` Criticality Device_count Critical 3 High 6 Medium 4 ```
2013/04/26
[ "https://Stackoverflow.com/questions/16237082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2124434/" ]
Why not use the MySQL function? They are meant to be used in MySQL. ``` SELECT * FROM microcompany WHERE date=DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) AND code='2.0.0' ``` btw. mysql-\* functions are deprecated: <http://www.php.net/manual/en/function.mysql-query.php>
``` <?php $yesterday = date('Y-m-d', strtotime('-1 day',strtotime(date("y-m-d")) )); $query = "SELECT * FROM microcompany WHERE date='".$yesterday."' AND code='2.0.0'"; $newQuery = 'update microcompany set date = "'.$yesterday.' where date = "'.$oldDate.'" and code ="2.0.0"'; ?> ```
16,237,082
I want to take grouped values (column: 'Criticality') from one table dbo.VTM\_duedate and next count values (column: 'DEVICE\_NAME') in another table dbo.TPM\_scan based on grouped values. Table 1 ``` USE tempdb; GO IF OBJECT_ID('dbo.VTM_duedate') IS NOT NULL DROP TABLE dbo.VTM_duedate; GO CREATE TABLE dbo.VTM_duedate ( Criticality varchar(30) NOT NULL, KB varchar(10) NOT NULL ); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 157848); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 155439); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 635533); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 189164); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 188641); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 537990); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 1349605); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Critical', 5646789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6545789); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('High', 5637965); INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 6464367) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1323123) ; INSERT INTO dbo.VTM_duedate(Criticality, KB) VALUES('Medium', 1004326) ; GO ``` Table 2 ``` USE tempdb; GO IF OBJECT_ID('dbo.TPM_scan') IS NOT NULL DROP TABLE dbo.TPM_scan; GO CREATE TABLE dbo.TPM_scan ( DEVICE_NAME varchar(30) NOT NULL, APP_ID varchar(10) NOT NULL, Criticality varchar(10) NOT NULL ); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 157848, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 155439, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('LDNSQLF700', 635533, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 189164, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('NYSQL502', 188641, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 537990, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('AUSSQL140', 1349605, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('JAP543X2', 5646789, 'Medium'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EU456CLX', 6545789, 'Critical'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 5637965, 'High'); INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 6464367, 'Medium') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1323123, 'High') ; INSERT INTO dbo.TPM_scan(DEVICE_NAME, APP_ID, Criticality) VALUES('EUCTX654', 1004326, 'Medium') ; GO ``` Expected results: ``` Criticality Device_count Critical 3 High 6 Medium 4 ```
2013/04/26
[ "https://Stackoverflow.com/questions/16237082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2124434/" ]
``` $date = new DateTime('Yesterday'); echo $date->format('Y-m-d'); ``` Or ``` $date = new DateTime('2013-01-28'); $date->modify('-1 day'); echo $date->format('Y-m-d'); ``` FYI, [you shouldn't use `mysql_*` functions in new code](https://stackoverflow.com/q/12859942/). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [red box](https://www.php.net/manual/en/function.mysql-connect.php)? Learn about [*prepared statements*](https://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://php.net/pdo), or [MySQLi](http://php.net/mysqli) - [this article](https://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide which. If you choose PDO, [here is a good tutorial](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers).
use native mysql functions for that purpose. ``` $result = mysql_query("SELECT * FROM microcompany WHERE date=date_sub(date(now()), interval 1 day) AND code='2.0.0'") or die(mysql_error()); ```
5,401,262
What is the most effective way to obtain a vector having a unique specified object property (not unique objects just objects with unique specified property). If y needed to be a unique property ``` point.x = 2 point.y = 3 point.x = 3 point.y = 3 point.x = 4 point.y = 4 point.x = 4 point.y = 5 ``` Could become: ``` point.x = 3 point.y = 3 point.x = 4 point.y = 4 point.x = 4 point.y = 5 ```
2011/03/23
[ "https://Stackoverflow.com/questions/5401262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/506565/" ]
`Person` is an object with two functions - `Create` and `showMe`. In JavaScript, there are no classes, only objects, and this is how you write up an object - using 'Object Literal Notation' (the curly braces and functions/properties separated by commas). `New` is a clever re-implementation of the `new` keyword. Instead of classes, javascript has prototypes, and instead of creating an instance of a class you create a copy of the prototype. In this case, if you passed `Person` to `New()`, it would used as the prototype in `new_.prototype = aClass`, and the rest of this function will return an object with the `Person` prototype, which means any changes to `Person` later on will be inherited into `obj` as well (unless `obj` has overridden them).
``` `Person` -- a variable w/ 'parts' (used loosely) `Person.Create` and `Person.showMe' `Person.Create` -- function of `Person` that sets `Person.name` and `Person.age` to its arguments `Person.showMe` -- returns a string explaining values of `Person.name` and `Person.age` `New` -- a function intended to instantiate new Person's thru prototypal (this is NOT class based) inheritenced `New._new` -- `New` uses this to get it done ``` Basically thru prototype inheritence, even though `Person` is only 'made' once, other 'versions' of it can be constructed in kind. It can be used like this (try it here: <http://jsfiddle.net/PBhCs/>) ``` var Person = { Create: function(name, age) { this.name = name; this.age = age }, showMe: function() { return " Person Name: " + this.name + " Age: " + this.age + " "; } }; function New(aClass, aParams) { function new_() { aClass.Create.apply(this, aParams); }; new_.prototype = aClass; var obj = new new_(); return obj; } var a = New(Person, ['moo', 5]); var b = New(Person, ['arf', 10]); alert(a.showMe() + b.showMe()); ```
57,358,535
I want to send push notification to the client app from the merchant app. Both are two different android apps. How can I achieve this using `FCM` or any other service? Do I need to have both these apps in the same `Firebase` project or different firebase projects?
2019/08/05
[ "https://Stackoverflow.com/questions/57358535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9290001/" ]
In order to send messages, use FCM Rest API POST\_API\_URL: <https://fcm.googleapis.com/> Header : 1) Authorization : key=legacy\_server\_key 2) Content-Type : application/json Body: { "to":"receiver push token", "notification":{ "title":"", "body":"" }, "data":{ }, "android":{ "priority":"high" }, "apns":{ "headers":{ "apns-priority":"10" }, "payload":{ "headers":{ "category":"abc" } } } }
You can do that either with one firebase project or two .. it dosen't really matter.. You should use a webservice (API) as a proxy to send notification. In order to send messages you can use a set of languages or use a the rest API (hitting *<https://fcm.googleapis.com/fcm/send>*) provided by the [firebase documentation](https://firebase.google.com/docs/cloud-messaging/send-message)
6,957,683
Why does Microsoft use extension methods for classes that it creates; instead of just adding the methods to the classes, or creating child classes?
2011/08/05
[ "https://Stackoverflow.com/questions/6957683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401173/" ]
There are a number of reason Microsoft did this. The two biggest being: 1. Extension methods apply to interfaces, not just classes. Had Microsoft simply added the Linq methods directly to IEnumerable, it would have required every concrete implementation of that interface to implement those methods as well. By making them extension methods, written in terms of the existing IEnumerable<> behavior, every IEnumerable<> class gets them automatically. 2. For the 3.0 and 3.5 Frameworks, the core System.dll is the 2.0 library. Everything new in 3.0 ad 3.5 was added on top of that, in System.Core or other related libraries. The only way to get, for example, a new method in the List<> class that exists in 3.5 but not in 2.0 is to make in an extension method available in a 3.5 library.
My two cents: because extension methods were added only in later versions of the .NET framework, they already had .NET Framework 1, 1.1, 2.0 and newer then at some point they added extension methods so they have used them to enrich the feature set on top of existing classes.
6,957,683
Why does Microsoft use extension methods for classes that it creates; instead of just adding the methods to the classes, or creating child classes?
2011/08/05
[ "https://Stackoverflow.com/questions/6957683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401173/" ]
`IgnoreRoute()` on `RouteCollection` is an extension method because it is intended for use with the MVC framework, rather than a core ASP.NET application. My guess would be that they didn't want to pollute the `RouteCollection` class with methods that non-MVC applications wouldn't need, while still allowing MVC applications to make use of the class. I'm not sure this approach necessarily make sense (since, for example, they could have just created a child class); for more general reasons that extension methods might be used, others have answered nicely.
My two cents: because extension methods were added only in later versions of the .NET framework, they already had .NET Framework 1, 1.1, 2.0 and newer then at some point they added extension methods so they have used them to enrich the feature set on top of existing classes.
6,957,683
Why does Microsoft use extension methods for classes that it creates; instead of just adding the methods to the classes, or creating child classes?
2011/08/05
[ "https://Stackoverflow.com/questions/6957683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401173/" ]
This is an example of the [Non-Virtual Interface](https://stackoverflow.com/questions/6481260/non-virtual-interface-design-pattern-question-in-c-c) pattern (similar to [Template Method](http://en.wikipedia.org/wiki/Template_method_pattern)). This is a pattern used in languages with multiple (implementation) inheritance, and the way to do it in C# is to use extension methods. The basic idea is that you have only non-virtual and pure-virtual (abstract) methods. The implementor of the interface (or inheritor of the class/mixin, in languages with multiple inheritance), implements a small method or set of methods (in this case, GetEnumerator), and in return gets a whole slew of methods that depend on that one abstract method (like Select, Where, Aggregate, etc.) As Michael Edenfield said in his answer, if we want to implmeent this pattern and we want IEnumerable to be an interface, we need to use extension methods. And making IEnumerable into an abstract class would be bad because its supposed to be a very low-cost, basic interface that should be put on pretty much any collection - implementing IEnumerable should not require rethinking a class hierarchy, it should be almost "for free".
My two cents: because extension methods were added only in later versions of the .NET framework, they already had .NET Framework 1, 1.1, 2.0 and newer then at some point they added extension methods so they have used them to enrich the feature set on top of existing classes.
6,957,683
Why does Microsoft use extension methods for classes that it creates; instead of just adding the methods to the classes, or creating child classes?
2011/08/05
[ "https://Stackoverflow.com/questions/6957683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401173/" ]
I think the main reason is that it's very easy to extend such methods. For example, if you Linq extension methods you can easily write yout own set of extension methods (maybe foreach or some specific filter) which will work greate with microsoft methods: mylist.Where(...).MyFilter(...).Select(...)
My two cents: because extension methods were added only in later versions of the .NET framework, they already had .NET Framework 1, 1.1, 2.0 and newer then at some point they added extension methods so they have used them to enrich the feature set on top of existing classes.
6,957,683
Why does Microsoft use extension methods for classes that it creates; instead of just adding the methods to the classes, or creating child classes?
2011/08/05
[ "https://Stackoverflow.com/questions/6957683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401173/" ]
There are a number of reason Microsoft did this. The two biggest being: 1. Extension methods apply to interfaces, not just classes. Had Microsoft simply added the Linq methods directly to IEnumerable, it would have required every concrete implementation of that interface to implement those methods as well. By making them extension methods, written in terms of the existing IEnumerable<> behavior, every IEnumerable<> class gets them automatically. 2. For the 3.0 and 3.5 Frameworks, the core System.dll is the 2.0 library. Everything new in 3.0 ad 3.5 was added on top of that, in System.Core or other related libraries. The only way to get, for example, a new method in the List<> class that exists in 3.5 but not in 2.0 is to make in an extension method available in a 3.5 library.
`IgnoreRoute()` on `RouteCollection` is an extension method because it is intended for use with the MVC framework, rather than a core ASP.NET application. My guess would be that they didn't want to pollute the `RouteCollection` class with methods that non-MVC applications wouldn't need, while still allowing MVC applications to make use of the class. I'm not sure this approach necessarily make sense (since, for example, they could have just created a child class); for more general reasons that extension methods might be used, others have answered nicely.
6,957,683
Why does Microsoft use extension methods for classes that it creates; instead of just adding the methods to the classes, or creating child classes?
2011/08/05
[ "https://Stackoverflow.com/questions/6957683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401173/" ]
There are a number of reason Microsoft did this. The two biggest being: 1. Extension methods apply to interfaces, not just classes. Had Microsoft simply added the Linq methods directly to IEnumerable, it would have required every concrete implementation of that interface to implement those methods as well. By making them extension methods, written in terms of the existing IEnumerable<> behavior, every IEnumerable<> class gets them automatically. 2. For the 3.0 and 3.5 Frameworks, the core System.dll is the 2.0 library. Everything new in 3.0 ad 3.5 was added on top of that, in System.Core or other related libraries. The only way to get, for example, a new method in the List<> class that exists in 3.5 but not in 2.0 is to make in an extension method available in a 3.5 library.
This is an example of the [Non-Virtual Interface](https://stackoverflow.com/questions/6481260/non-virtual-interface-design-pattern-question-in-c-c) pattern (similar to [Template Method](http://en.wikipedia.org/wiki/Template_method_pattern)). This is a pattern used in languages with multiple (implementation) inheritance, and the way to do it in C# is to use extension methods. The basic idea is that you have only non-virtual and pure-virtual (abstract) methods. The implementor of the interface (or inheritor of the class/mixin, in languages with multiple inheritance), implements a small method or set of methods (in this case, GetEnumerator), and in return gets a whole slew of methods that depend on that one abstract method (like Select, Where, Aggregate, etc.) As Michael Edenfield said in his answer, if we want to implmeent this pattern and we want IEnumerable to be an interface, we need to use extension methods. And making IEnumerable into an abstract class would be bad because its supposed to be a very low-cost, basic interface that should be put on pretty much any collection - implementing IEnumerable should not require rethinking a class hierarchy, it should be almost "for free".
6,957,683
Why does Microsoft use extension methods for classes that it creates; instead of just adding the methods to the classes, or creating child classes?
2011/08/05
[ "https://Stackoverflow.com/questions/6957683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401173/" ]
There are a number of reason Microsoft did this. The two biggest being: 1. Extension methods apply to interfaces, not just classes. Had Microsoft simply added the Linq methods directly to IEnumerable, it would have required every concrete implementation of that interface to implement those methods as well. By making them extension methods, written in terms of the existing IEnumerable<> behavior, every IEnumerable<> class gets them automatically. 2. For the 3.0 and 3.5 Frameworks, the core System.dll is the 2.0 library. Everything new in 3.0 ad 3.5 was added on top of that, in System.Core or other related libraries. The only way to get, for example, a new method in the List<> class that exists in 3.5 but not in 2.0 is to make in an extension method available in a 3.5 library.
I think the main reason is that it's very easy to extend such methods. For example, if you Linq extension methods you can easily write yout own set of extension methods (maybe foreach or some specific filter) which will work greate with microsoft methods: mylist.Where(...).MyFilter(...).Select(...)
6,957,683
Why does Microsoft use extension methods for classes that it creates; instead of just adding the methods to the classes, or creating child classes?
2011/08/05
[ "https://Stackoverflow.com/questions/6957683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401173/" ]
`IgnoreRoute()` on `RouteCollection` is an extension method because it is intended for use with the MVC framework, rather than a core ASP.NET application. My guess would be that they didn't want to pollute the `RouteCollection` class with methods that non-MVC applications wouldn't need, while still allowing MVC applications to make use of the class. I'm not sure this approach necessarily make sense (since, for example, they could have just created a child class); for more general reasons that extension methods might be used, others have answered nicely.
This is an example of the [Non-Virtual Interface](https://stackoverflow.com/questions/6481260/non-virtual-interface-design-pattern-question-in-c-c) pattern (similar to [Template Method](http://en.wikipedia.org/wiki/Template_method_pattern)). This is a pattern used in languages with multiple (implementation) inheritance, and the way to do it in C# is to use extension methods. The basic idea is that you have only non-virtual and pure-virtual (abstract) methods. The implementor of the interface (or inheritor of the class/mixin, in languages with multiple inheritance), implements a small method or set of methods (in this case, GetEnumerator), and in return gets a whole slew of methods that depend on that one abstract method (like Select, Where, Aggregate, etc.) As Michael Edenfield said in his answer, if we want to implmeent this pattern and we want IEnumerable to be an interface, we need to use extension methods. And making IEnumerable into an abstract class would be bad because its supposed to be a very low-cost, basic interface that should be put on pretty much any collection - implementing IEnumerable should not require rethinking a class hierarchy, it should be almost "for free".
6,957,683
Why does Microsoft use extension methods for classes that it creates; instead of just adding the methods to the classes, or creating child classes?
2011/08/05
[ "https://Stackoverflow.com/questions/6957683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401173/" ]
`IgnoreRoute()` on `RouteCollection` is an extension method because it is intended for use with the MVC framework, rather than a core ASP.NET application. My guess would be that they didn't want to pollute the `RouteCollection` class with methods that non-MVC applications wouldn't need, while still allowing MVC applications to make use of the class. I'm not sure this approach necessarily make sense (since, for example, they could have just created a child class); for more general reasons that extension methods might be used, others have answered nicely.
I think the main reason is that it's very easy to extend such methods. For example, if you Linq extension methods you can easily write yout own set of extension methods (maybe foreach or some specific filter) which will work greate with microsoft methods: mylist.Where(...).MyFilter(...).Select(...)
28,955
In Christianity, God's grace is what allows us to have a relationship with him. He gives us what we don't deserve like righteousness, life, and in the ultimate example his own son, in spite of our sin so that we might finally have eternal peace with him. And in light of God's grace Christians are expected give grace to others. This grace is different than mercy. From the divine perspective, mercy is not getting **punished** for what you deserve whereas grace is being **blessed** even when you don't deserve it. So for the Christian who is called to give grace like God, we're expected to do good to others even when they don't deserve it (and especially to those of the household of faith). Does this concept also exist in Islam, and if so does it exist in the same way? I know Allah is described as merciful (*Ar-Rahman*) but mercy isn't quite as far reaching as grace according to the definitions above.
2015/12/03
[ "https://islam.stackexchange.com/questions/28955", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/6581/" ]
I did not find a clear definition of grace (of Christianity). But, I can try relating different aspects of the definition I found in [wiki](https://en.wikipedia.org/wiki/Divine_grace#Christianity:_the_graces_of_the_Holy_Rosary) to that of Islam from mostly from Qur'an. > > Grace in Christianity is the free and unmerited favour of God as manifested in the salvation of sinners and the bestowing of blessings > > > analogous to > > So which of the favors of your Lord would you deny? [Qur'an [55:13]](http://quran.com/55/13) > > > The whole Chapter Ar-Rahman sets the context of that one line which is highly repeated. --- > > Common Christian teaching is that grace is unmerited mercy (favor) that God gave to humanity by sending his son to die on a cross, thus delivering eternal salvation. > > > analogous to > > Indeed, in this [Qur'an] is notification for a worshipping people. And We have not sent you, [O Muhammad], except as a mercy to the worlds. [Qur'an [21:106-107]](http://www.quran.com/21/106-107) > > > implying God sent Muhammad as a prophet (**not as son**) to remind everyone, even those who don't deserve. But, the reminder / blessings [will be taken only by those who fear](http://www.quran.com/87/10). But, definitely no concept of son's sacrifice in Islam. --- > > And the child (Jesus) grew, and waxed strong in spirit, filled with wisdom: and the grace of God was upon him. [Luke [2:40]](https://www.biblegateway.com/passage/?search=Luke%202&version=ESV) > > > the same thing in Qur'an > > And when Jesus brought clear proofs, he said, "I have come to you with wisdom and to make clear to you some of that over which you differ, so fear Allah and obey me. [Qur'an [43:63]](http://www.quran.com/43/63) > > > analogous to > > And We gave to Abraham, Isaac and Jacob - all [of them] We guided. And Noah, We guided before; and among his descendants, David and Solomon and Job and Joseph and Moses and Aaron. Thus do We reward the doers of good. [Qur'an [6:84]](http://quran.com/6/84) > > > --- > > In this example (of Luke 2:40 above) when using the definition of grace to mean unmerited favor it does not make sense, to some, that the sinless Christ would need this..... This at its root means literally Christ dispenses Gods grace from himself. > > > There is nothing like that in Islam. --- > > Equally some say, how can one fall short of grace? (Galatians 5:4) or meekness attract it and pride repel it (James 4:6) if it is unmerited. > > > The answer to this is, > > ...For indeed, Allah sends astray whom He wills and guides whom He wills....[Qur'an [35:8]](http://quran.com/35/8) > > > And the solution is given as, one should remember God as much as he can. --- Concluding, > > Alternatively Bill Gothard has suggested "God's grace gives us the desire and the power to do his will. > > > If I understood it right, irrespective of what you believe *God's grace* is, I can best relate it to the term '*guidance*' which is frequently used in the Qur'an.
In Islam the great and only lord "Allah" have mentioned that he is closer to us than our eyelashes and we can ask for anything we need directly from him rather than someone else. This shows that god is merciful and gives us whatever is right and good for us. He doesn't look at it whether we deserve it or not. And we believe that anything wrong that happens or right is from Allah and everything wrong has something "right" behind it because god is never harming us. And our relation with god is only us being generated by him and we must always do as per his directions. Of cours Allah is graceful, when something harmful is going to happen to us, like accidents but as per god's grace we are safe that's how Allah shows his grace to us. In Arabic its called Fazel the one who is graceful. And merciful is Rahman in Arabic. Hope I have helped you somehow.
28,955
In Christianity, God's grace is what allows us to have a relationship with him. He gives us what we don't deserve like righteousness, life, and in the ultimate example his own son, in spite of our sin so that we might finally have eternal peace with him. And in light of God's grace Christians are expected give grace to others. This grace is different than mercy. From the divine perspective, mercy is not getting **punished** for what you deserve whereas grace is being **blessed** even when you don't deserve it. So for the Christian who is called to give grace like God, we're expected to do good to others even when they don't deserve it (and especially to those of the household of faith). Does this concept also exist in Islam, and if so does it exist in the same way? I know Allah is described as merciful (*Ar-Rahman*) but mercy isn't quite as far reaching as grace according to the definitions above.
2015/12/03
[ "https://islam.stackexchange.com/questions/28955", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/6581/" ]
There are several words related to mercy in Quran that don't have exact translations in English and all are translated to mercy but are not really the same. Two of major names of God related to mercy in Quran are Ar-Rahman and Ar-Rahim. Typically Ar-Rahman is interpreted to mean the merciful towards all beings while Ar-Rahim is interpreted to mean the merciful towards the righteous. The forgiving of sins is related to other names like Al-Ghafir (الغافر) and Afv (عفوا). According to Quran God's mercy is all-encompassing in this world. For example, verse 7:155 God responds to Moses as follows: > > وَٱكْتُبْ لَنَا فِى هَـٰذِهِ ٱلدُّنْيَا حَسَنَةًۭ وَفِى ٱلْءَاخِرَةِ إِنَّا هُدْنَآ إِلَيْكَ ۚ قَالَ عَذَابِىٓ أُصِيبُ بِهِۦ مَنْ أَشَآءُ ۖ وَرَحْمَتِى وَسِعَتْ كُلَّ شَىْءٍۢ ۚ فَسَأَكْتُبُهَا لِلَّذِينَ يَتَّقُونَ وَيُؤْتُونَ ٱلزَّكَوٰةَ وَٱلَّذِينَ هُم بِـَٔايَـٰتِنَا يُؤْمِنُونَ > > > [Moses said:] "And write for us in this world that which is good and in the hereafter, for we have been guided towards you." > > [God] said: "My punishment is inflicted upon whom I will; and my mercy extends towards all beings. Thus I will write it [in hereafter] for those who act mindfully and give alms and those who believe in our signs. > > > --- No one *deserves* to be blessed *by themselves*, neither in Islam (see e.g. verse 20:21) nor in Christianity (see e.g. the Book of Job in the Old Testament) as far as I understand. For some verses in Quran with the theme of being good to others even when they are not good towards you see verses 13:22, 24:22, 42:40, and 64:14. I think 24:22 is quite close to what you say in regards to being good towards others as God is towards us. --- Regarding the original sin, according to Quran the original sin was already forgiven when Adam apologized. Therefore the original sin doesn't play much role in Islam. There is no need for some special arrangements for God to be able to forgive a sin. In Quran's view, Adam was destined to be sent to Earth from the start to act as viceroy of God (خليفة الله). For more information see verses 2:29-39.
In Islam the great and only lord "Allah" have mentioned that he is closer to us than our eyelashes and we can ask for anything we need directly from him rather than someone else. This shows that god is merciful and gives us whatever is right and good for us. He doesn't look at it whether we deserve it or not. And we believe that anything wrong that happens or right is from Allah and everything wrong has something "right" behind it because god is never harming us. And our relation with god is only us being generated by him and we must always do as per his directions. Of cours Allah is graceful, when something harmful is going to happen to us, like accidents but as per god's grace we are safe that's how Allah shows his grace to us. In Arabic its called Fazel the one who is graceful. And merciful is Rahman in Arabic. Hope I have helped you somehow.
28,955
In Christianity, God's grace is what allows us to have a relationship with him. He gives us what we don't deserve like righteousness, life, and in the ultimate example his own son, in spite of our sin so that we might finally have eternal peace with him. And in light of God's grace Christians are expected give grace to others. This grace is different than mercy. From the divine perspective, mercy is not getting **punished** for what you deserve whereas grace is being **blessed** even when you don't deserve it. So for the Christian who is called to give grace like God, we're expected to do good to others even when they don't deserve it (and especially to those of the household of faith). Does this concept also exist in Islam, and if so does it exist in the same way? I know Allah is described as merciful (*Ar-Rahman*) but mercy isn't quite as far reaching as grace according to the definitions above.
2015/12/03
[ "https://islam.stackexchange.com/questions/28955", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/6581/" ]
In Islam the great and only lord "Allah" have mentioned that he is closer to us than our eyelashes and we can ask for anything we need directly from him rather than someone else. This shows that god is merciful and gives us whatever is right and good for us. He doesn't look at it whether we deserve it or not. And we believe that anything wrong that happens or right is from Allah and everything wrong has something "right" behind it because god is never harming us. And our relation with god is only us being generated by him and we must always do as per his directions. Of cours Allah is graceful, when something harmful is going to happen to us, like accidents but as per god's grace we are safe that's how Allah shows his grace to us. In Arabic its called Fazel the one who is graceful. And merciful is Rahman in Arabic. Hope I have helped you somehow.
In Islam, no one deserves anything, Allah first gifts His creatures with a talentive state, so that they will have requests, then will respond back their needs by mercy. The evolution from existing in posse toward completion is wholely based on Him being the Most Gracious (Ar-Rahman: الرحمن) and the Most Merciful (Ar-Raheem: آلرحیم). ... as far as I have understood
28,955
In Christianity, God's grace is what allows us to have a relationship with him. He gives us what we don't deserve like righteousness, life, and in the ultimate example his own son, in spite of our sin so that we might finally have eternal peace with him. And in light of God's grace Christians are expected give grace to others. This grace is different than mercy. From the divine perspective, mercy is not getting **punished** for what you deserve whereas grace is being **blessed** even when you don't deserve it. So for the Christian who is called to give grace like God, we're expected to do good to others even when they don't deserve it (and especially to those of the household of faith). Does this concept also exist in Islam, and if so does it exist in the same way? I know Allah is described as merciful (*Ar-Rahman*) but mercy isn't quite as far reaching as grace according to the definitions above.
2015/12/03
[ "https://islam.stackexchange.com/questions/28955", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/6581/" ]
In Islam the great and only lord "Allah" have mentioned that he is closer to us than our eyelashes and we can ask for anything we need directly from him rather than someone else. This shows that god is merciful and gives us whatever is right and good for us. He doesn't look at it whether we deserve it or not. And we believe that anything wrong that happens or right is from Allah and everything wrong has something "right" behind it because god is never harming us. And our relation with god is only us being generated by him and we must always do as per his directions. Of cours Allah is graceful, when something harmful is going to happen to us, like accidents but as per god's grace we are safe that's how Allah shows his grace to us. In Arabic its called Fazel the one who is graceful. And merciful is Rahman in Arabic. Hope I have helped you somehow.
Short answer: yes: "fa azallahum al shaytan"...the satan made them fall...from what? from the state of bliss that they were in by being allowed to be in the garden to eat of whatever was therein except "this tree."
28,955
In Christianity, God's grace is what allows us to have a relationship with him. He gives us what we don't deserve like righteousness, life, and in the ultimate example his own son, in spite of our sin so that we might finally have eternal peace with him. And in light of God's grace Christians are expected give grace to others. This grace is different than mercy. From the divine perspective, mercy is not getting **punished** for what you deserve whereas grace is being **blessed** even when you don't deserve it. So for the Christian who is called to give grace like God, we're expected to do good to others even when they don't deserve it (and especially to those of the household of faith). Does this concept also exist in Islam, and if so does it exist in the same way? I know Allah is described as merciful (*Ar-Rahman*) but mercy isn't quite as far reaching as grace according to the definitions above.
2015/12/03
[ "https://islam.stackexchange.com/questions/28955", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/6581/" ]
I did not find a clear definition of grace (of Christianity). But, I can try relating different aspects of the definition I found in [wiki](https://en.wikipedia.org/wiki/Divine_grace#Christianity:_the_graces_of_the_Holy_Rosary) to that of Islam from mostly from Qur'an. > > Grace in Christianity is the free and unmerited favour of God as manifested in the salvation of sinners and the bestowing of blessings > > > analogous to > > So which of the favors of your Lord would you deny? [Qur'an [55:13]](http://quran.com/55/13) > > > The whole Chapter Ar-Rahman sets the context of that one line which is highly repeated. --- > > Common Christian teaching is that grace is unmerited mercy (favor) that God gave to humanity by sending his son to die on a cross, thus delivering eternal salvation. > > > analogous to > > Indeed, in this [Qur'an] is notification for a worshipping people. And We have not sent you, [O Muhammad], except as a mercy to the worlds. [Qur'an [21:106-107]](http://www.quran.com/21/106-107) > > > implying God sent Muhammad as a prophet (**not as son**) to remind everyone, even those who don't deserve. But, the reminder / blessings [will be taken only by those who fear](http://www.quran.com/87/10). But, definitely no concept of son's sacrifice in Islam. --- > > And the child (Jesus) grew, and waxed strong in spirit, filled with wisdom: and the grace of God was upon him. [Luke [2:40]](https://www.biblegateway.com/passage/?search=Luke%202&version=ESV) > > > the same thing in Qur'an > > And when Jesus brought clear proofs, he said, "I have come to you with wisdom and to make clear to you some of that over which you differ, so fear Allah and obey me. [Qur'an [43:63]](http://www.quran.com/43/63) > > > analogous to > > And We gave to Abraham, Isaac and Jacob - all [of them] We guided. And Noah, We guided before; and among his descendants, David and Solomon and Job and Joseph and Moses and Aaron. Thus do We reward the doers of good. [Qur'an [6:84]](http://quran.com/6/84) > > > --- > > In this example (of Luke 2:40 above) when using the definition of grace to mean unmerited favor it does not make sense, to some, that the sinless Christ would need this..... This at its root means literally Christ dispenses Gods grace from himself. > > > There is nothing like that in Islam. --- > > Equally some say, how can one fall short of grace? (Galatians 5:4) or meekness attract it and pride repel it (James 4:6) if it is unmerited. > > > The answer to this is, > > ...For indeed, Allah sends astray whom He wills and guides whom He wills....[Qur'an [35:8]](http://quran.com/35/8) > > > And the solution is given as, one should remember God as much as he can. --- Concluding, > > Alternatively Bill Gothard has suggested "God's grace gives us the desire and the power to do his will. > > > If I understood it right, irrespective of what you believe *God's grace* is, I can best relate it to the term '*guidance*' which is frequently used in the Qur'an.
In Islam, no one deserves anything, Allah first gifts His creatures with a talentive state, so that they will have requests, then will respond back their needs by mercy. The evolution from existing in posse toward completion is wholely based on Him being the Most Gracious (Ar-Rahman: الرحمن) and the Most Merciful (Ar-Raheem: آلرحیم). ... as far as I have understood
28,955
In Christianity, God's grace is what allows us to have a relationship with him. He gives us what we don't deserve like righteousness, life, and in the ultimate example his own son, in spite of our sin so that we might finally have eternal peace with him. And in light of God's grace Christians are expected give grace to others. This grace is different than mercy. From the divine perspective, mercy is not getting **punished** for what you deserve whereas grace is being **blessed** even when you don't deserve it. So for the Christian who is called to give grace like God, we're expected to do good to others even when they don't deserve it (and especially to those of the household of faith). Does this concept also exist in Islam, and if so does it exist in the same way? I know Allah is described as merciful (*Ar-Rahman*) but mercy isn't quite as far reaching as grace according to the definitions above.
2015/12/03
[ "https://islam.stackexchange.com/questions/28955", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/6581/" ]
I did not find a clear definition of grace (of Christianity). But, I can try relating different aspects of the definition I found in [wiki](https://en.wikipedia.org/wiki/Divine_grace#Christianity:_the_graces_of_the_Holy_Rosary) to that of Islam from mostly from Qur'an. > > Grace in Christianity is the free and unmerited favour of God as manifested in the salvation of sinners and the bestowing of blessings > > > analogous to > > So which of the favors of your Lord would you deny? [Qur'an [55:13]](http://quran.com/55/13) > > > The whole Chapter Ar-Rahman sets the context of that one line which is highly repeated. --- > > Common Christian teaching is that grace is unmerited mercy (favor) that God gave to humanity by sending his son to die on a cross, thus delivering eternal salvation. > > > analogous to > > Indeed, in this [Qur'an] is notification for a worshipping people. And We have not sent you, [O Muhammad], except as a mercy to the worlds. [Qur'an [21:106-107]](http://www.quran.com/21/106-107) > > > implying God sent Muhammad as a prophet (**not as son**) to remind everyone, even those who don't deserve. But, the reminder / blessings [will be taken only by those who fear](http://www.quran.com/87/10). But, definitely no concept of son's sacrifice in Islam. --- > > And the child (Jesus) grew, and waxed strong in spirit, filled with wisdom: and the grace of God was upon him. [Luke [2:40]](https://www.biblegateway.com/passage/?search=Luke%202&version=ESV) > > > the same thing in Qur'an > > And when Jesus brought clear proofs, he said, "I have come to you with wisdom and to make clear to you some of that over which you differ, so fear Allah and obey me. [Qur'an [43:63]](http://www.quran.com/43/63) > > > analogous to > > And We gave to Abraham, Isaac and Jacob - all [of them] We guided. And Noah, We guided before; and among his descendants, David and Solomon and Job and Joseph and Moses and Aaron. Thus do We reward the doers of good. [Qur'an [6:84]](http://quran.com/6/84) > > > --- > > In this example (of Luke 2:40 above) when using the definition of grace to mean unmerited favor it does not make sense, to some, that the sinless Christ would need this..... This at its root means literally Christ dispenses Gods grace from himself. > > > There is nothing like that in Islam. --- > > Equally some say, how can one fall short of grace? (Galatians 5:4) or meekness attract it and pride repel it (James 4:6) if it is unmerited. > > > The answer to this is, > > ...For indeed, Allah sends astray whom He wills and guides whom He wills....[Qur'an [35:8]](http://quran.com/35/8) > > > And the solution is given as, one should remember God as much as he can. --- Concluding, > > Alternatively Bill Gothard has suggested "God's grace gives us the desire and the power to do his will. > > > If I understood it right, irrespective of what you believe *God's grace* is, I can best relate it to the term '*guidance*' which is frequently used in the Qur'an.
Short answer: yes: "fa azallahum al shaytan"...the satan made them fall...from what? from the state of bliss that they were in by being allowed to be in the garden to eat of whatever was therein except "this tree."
28,955
In Christianity, God's grace is what allows us to have a relationship with him. He gives us what we don't deserve like righteousness, life, and in the ultimate example his own son, in spite of our sin so that we might finally have eternal peace with him. And in light of God's grace Christians are expected give grace to others. This grace is different than mercy. From the divine perspective, mercy is not getting **punished** for what you deserve whereas grace is being **blessed** even when you don't deserve it. So for the Christian who is called to give grace like God, we're expected to do good to others even when they don't deserve it (and especially to those of the household of faith). Does this concept also exist in Islam, and if so does it exist in the same way? I know Allah is described as merciful (*Ar-Rahman*) but mercy isn't quite as far reaching as grace according to the definitions above.
2015/12/03
[ "https://islam.stackexchange.com/questions/28955", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/6581/" ]
There are several words related to mercy in Quran that don't have exact translations in English and all are translated to mercy but are not really the same. Two of major names of God related to mercy in Quran are Ar-Rahman and Ar-Rahim. Typically Ar-Rahman is interpreted to mean the merciful towards all beings while Ar-Rahim is interpreted to mean the merciful towards the righteous. The forgiving of sins is related to other names like Al-Ghafir (الغافر) and Afv (عفوا). According to Quran God's mercy is all-encompassing in this world. For example, verse 7:155 God responds to Moses as follows: > > وَٱكْتُبْ لَنَا فِى هَـٰذِهِ ٱلدُّنْيَا حَسَنَةًۭ وَفِى ٱلْءَاخِرَةِ إِنَّا هُدْنَآ إِلَيْكَ ۚ قَالَ عَذَابِىٓ أُصِيبُ بِهِۦ مَنْ أَشَآءُ ۖ وَرَحْمَتِى وَسِعَتْ كُلَّ شَىْءٍۢ ۚ فَسَأَكْتُبُهَا لِلَّذِينَ يَتَّقُونَ وَيُؤْتُونَ ٱلزَّكَوٰةَ وَٱلَّذِينَ هُم بِـَٔايَـٰتِنَا يُؤْمِنُونَ > > > [Moses said:] "And write for us in this world that which is good and in the hereafter, for we have been guided towards you." > > [God] said: "My punishment is inflicted upon whom I will; and my mercy extends towards all beings. Thus I will write it [in hereafter] for those who act mindfully and give alms and those who believe in our signs. > > > --- No one *deserves* to be blessed *by themselves*, neither in Islam (see e.g. verse 20:21) nor in Christianity (see e.g. the Book of Job in the Old Testament) as far as I understand. For some verses in Quran with the theme of being good to others even when they are not good towards you see verses 13:22, 24:22, 42:40, and 64:14. I think 24:22 is quite close to what you say in regards to being good towards others as God is towards us. --- Regarding the original sin, according to Quran the original sin was already forgiven when Adam apologized. Therefore the original sin doesn't play much role in Islam. There is no need for some special arrangements for God to be able to forgive a sin. In Quran's view, Adam was destined to be sent to Earth from the start to act as viceroy of God (خليفة الله). For more information see verses 2:29-39.
In Islam, no one deserves anything, Allah first gifts His creatures with a talentive state, so that they will have requests, then will respond back their needs by mercy. The evolution from existing in posse toward completion is wholely based on Him being the Most Gracious (Ar-Rahman: الرحمن) and the Most Merciful (Ar-Raheem: آلرحیم). ... as far as I have understood
28,955
In Christianity, God's grace is what allows us to have a relationship with him. He gives us what we don't deserve like righteousness, life, and in the ultimate example his own son, in spite of our sin so that we might finally have eternal peace with him. And in light of God's grace Christians are expected give grace to others. This grace is different than mercy. From the divine perspective, mercy is not getting **punished** for what you deserve whereas grace is being **blessed** even when you don't deserve it. So for the Christian who is called to give grace like God, we're expected to do good to others even when they don't deserve it (and especially to those of the household of faith). Does this concept also exist in Islam, and if so does it exist in the same way? I know Allah is described as merciful (*Ar-Rahman*) but mercy isn't quite as far reaching as grace according to the definitions above.
2015/12/03
[ "https://islam.stackexchange.com/questions/28955", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/6581/" ]
There are several words related to mercy in Quran that don't have exact translations in English and all are translated to mercy but are not really the same. Two of major names of God related to mercy in Quran are Ar-Rahman and Ar-Rahim. Typically Ar-Rahman is interpreted to mean the merciful towards all beings while Ar-Rahim is interpreted to mean the merciful towards the righteous. The forgiving of sins is related to other names like Al-Ghafir (الغافر) and Afv (عفوا). According to Quran God's mercy is all-encompassing in this world. For example, verse 7:155 God responds to Moses as follows: > > وَٱكْتُبْ لَنَا فِى هَـٰذِهِ ٱلدُّنْيَا حَسَنَةًۭ وَفِى ٱلْءَاخِرَةِ إِنَّا هُدْنَآ إِلَيْكَ ۚ قَالَ عَذَابِىٓ أُصِيبُ بِهِۦ مَنْ أَشَآءُ ۖ وَرَحْمَتِى وَسِعَتْ كُلَّ شَىْءٍۢ ۚ فَسَأَكْتُبُهَا لِلَّذِينَ يَتَّقُونَ وَيُؤْتُونَ ٱلزَّكَوٰةَ وَٱلَّذِينَ هُم بِـَٔايَـٰتِنَا يُؤْمِنُونَ > > > [Moses said:] "And write for us in this world that which is good and in the hereafter, for we have been guided towards you." > > [God] said: "My punishment is inflicted upon whom I will; and my mercy extends towards all beings. Thus I will write it [in hereafter] for those who act mindfully and give alms and those who believe in our signs. > > > --- No one *deserves* to be blessed *by themselves*, neither in Islam (see e.g. verse 20:21) nor in Christianity (see e.g. the Book of Job in the Old Testament) as far as I understand. For some verses in Quran with the theme of being good to others even when they are not good towards you see verses 13:22, 24:22, 42:40, and 64:14. I think 24:22 is quite close to what you say in regards to being good towards others as God is towards us. --- Regarding the original sin, according to Quran the original sin was already forgiven when Adam apologized. Therefore the original sin doesn't play much role in Islam. There is no need for some special arrangements for God to be able to forgive a sin. In Quran's view, Adam was destined to be sent to Earth from the start to act as viceroy of God (خليفة الله). For more information see verses 2:29-39.
Short answer: yes: "fa azallahum al shaytan"...the satan made them fall...from what? from the state of bliss that they were in by being allowed to be in the garden to eat of whatever was therein except "this tree."
1,488,186
Is it possible in C++ to stringify template arguments? I tried this: ``` #include <iostream> #define STRINGIFY(x) #x template <typename T> struct Stringify { Stringify() { std::cout << STRINGIFY(T) << endl; } }; int main() { Stringify<int> s; } ``` But what I get is a `T`, and not an `int`. Seems that the preprocessor macros are evaluated before template instantiation. Is there any other way to do this? Is there any way for the preprocessing to take place after template instantiation? (Compiler is VC++).
2009/09/28
[ "https://Stackoverflow.com/questions/1488186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177482/" ]
This breaks one of my primary tenets of C++ code writing: Avoid using tricks in both the template features and the preprocessor at the same time. Part of the reason for templates and the nastiness they introduce into the language was an attempt to wean developers away from using the preprocessor. If you use both, then the terrorists win.
Here’s what I do: I have a `demangle()` function (implemented on top of `abi::__cxa_demangle()` which I call with a couple of convenience template function overloads, `nameof()`, with either the type I want stringified or an instance of same. It’s fairly compact, so I’ll reproduce it here in all its glory. In `demangle.hh` we have: ```cpp #pragma once #include <typeinfo> namespace terminator { /// actual function to demangle an allegedly mangled thing char const* demangle(char const* const symbol) noexcept; /// convenience function template to stringify a name of a type, /// either per an explicit specialization: /// char const* mytypename = terminator::nameof<SomeType>(); template <typename NameType> char const* nameof() { try { return demangle(typeid(NameType).name()); } catch (std::bad_typeid const&) { return "<unknown>"; } } /// … or as implied by an instance argument: /// char const* myinstancetypename = terminator::nameof(someinstance); template <typename ArgType> char const* nameof(ArgType argument) { try { return demangle(typeid(argument).name()); } catch (std::bad_typeid const&) { return "<unknown>"; } } } /* namespace terminator */ ``` … And then in `demangle.cpp`: ```cpp #include "demangle.hh" #include <cstdlib> #include <cxxabi.h> #include <mutex> #include <memory> namespace terminator { namespace { /// define one singular, private, static std::mutex, /// to keep the demangler from reentering itself static std::mutex mangle_barrier; /// define a corresponding private and static std::unique_ptr, /// using a delete-expression to reclaim the memory malloc()'ed by /// abi::__cxa_demangle() upon its return. /// … we use clang pragmas to add flags locally for this to work: #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #pragma clang diagnostic ignored "-Wexit-time-destructors" std::unique_ptr<char, decltype(std::free)&> demangled_name{ nullptr, std::free }; #pragma clang diagnostic pop } char const* demangle(char const* const symbol) noexcept { if (!symbol) { return "<null>"; } std::lock_guard<std::mutex> lock(mangle_barrier); int status = -4; demangled_name.reset( abi::__cxa_demangle(symbol, demangled_name.get(), nullptr, &status)); return ((status == 0) ? demangled_name.release() : symbol); } } /* namespace terminator */ ``` To use this, I think you’ll have to link to `libc++` (or whatever your local equivalent is) to use `abi::__cxa_demangle()`. What may be suboptimal for the OP is the fact that this does the demangling and stringification at runtime. I’d personally love something `constexpr`-friendly in leu of this, but since I suffer from a severe macro-abuse allergy, I find this to be the least generally-unreasonable solution to this problem. (the `terminator` namespace is inconsequential – I use this code in a libunwind-based stacktracer called from termination handler – feel free to `s///g` that token)
1,488,186
Is it possible in C++ to stringify template arguments? I tried this: ``` #include <iostream> #define STRINGIFY(x) #x template <typename T> struct Stringify { Stringify() { std::cout << STRINGIFY(T) << endl; } }; int main() { Stringify<int> s; } ``` But what I get is a `T`, and not an `int`. Seems that the preprocessor macros are evaluated before template instantiation. Is there any other way to do this? Is there any way for the preprocessing to take place after template instantiation? (Compiler is VC++).
2009/09/28
[ "https://Stackoverflow.com/questions/1488186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177482/" ]
Your code doesn't work because the preprocessor, responsible for searching and expanding the macros you use in your code, is not aware of the language itself. It is just a text parser. It finds that STRINGIFY(T) in the very function template and expand it, much before you give a type to that template. As it turns out, you will always get "T" instead of the typename you expected, unfortunately. As [litb](https://stackoverflow.com/users/34509/litb) suggested, I've (badly) implemented this `getTypeName' function template that returns the typename you pass it: ``` #include <iostream> template <typename _Get_TypeName> const std::string &getTypeName() { static std::string name; if (name.empty()) { const char *beginStr = "_Get_TypeName ="; const size_t beginStrLen = 15; // Yes, I know... // But isn't it better than strlen()? size_t begin,length; name = __PRETTY_FUNCTION__; begin = name.find(beginStr) + beginStrLen + 1; length = name.find("]",begin) - begin; name = name.substr(begin,length); } return name; } int main() { typedef void (*T)(int,int); // Using getTypeName() std::cout << getTypeName<float>() << '\n'; std::cout << getTypeName<T>() << '\n'; // You don't actually need the // typedef in this case, but // for it to work with the // typeid below, you'll need it // Using typeid().name() std::cout << typeid(float).name() << '\n'; std::cout << typeid(T).name() << '\n'; return 0; } ``` The code above results in the following output with GCC flag -s ("strip all symbols from binary") enabled: ``` float void (*)(int, int) f PFviiE ``` So, you see, getTypename() does a fairly better job, at the cost of that fugly string parsing hack (I KNOW, it's damn ugly). A few points to take into account: * The code is GCC only. I don't know how to port it to another compiler. Probably only a few others have such a facility to produce so pretty function names, and from what I searched, MSVC++ doesn't have one, if you're asking yourself that. * If, in a new version, GCC formats `__PRETTY_FUNCTION__`'s differently, the string matching can break and you'll have to fix it. For this same reason I also warn that getTypeName() *might* be good for debugging (and, still, maybe not even good for that), but it is *surely* bad, bad, and bad for other purposes such as comparing two types in a template or something like that (I don't know, just guessing what someone might think of..). Use it solely for debugging, and preferentially don't call it in release builds (use macros to disable), so that you don't use `__PRETTY_FUNCTION__` and thus the compiler doesn't produce the string for it. * I'm definitely no expert, and I'm not sure whether some odd type could cause the string matching to fail. I'd like to ask for people who read this post to comment if they know of such a case. * The code uses a static std::string. It means that, if some exception is thrown from its constructor or destructor, there is no way that it will reach a catch block and you'll get an unhandled exception. I don't know whether std::strings can do that, but beware that, if they do, you're potentially in trouble. I used it because it needs a destructor to free the memory. You could implement your own class for that, though, ensuring no exception is thrown besides allocation failure (that's pretty much fatal, isn't it? So...), and return a simple C-string. * With typedefs you can get some weird results, like this (for some reason, the site breaks the formatting of this snippet, so I'm using this paste link): <http://pastebin.com/f51b888ad> Despite those disadvantages, I'd like to say that it sure is fast. For the second time you lookup for one same type name, it will cost picking a reference to a global std::string containing the name. And, comparatively to the template specialiazation methods suggested before, there is nothing else you have to declare besides the very template itself, so it is really much easier to use.
If you use boost/core/demangle.hpp, you can get a reliable human-readable string. ``` char const * name = typeid(T).name(); boost::core::scoped_demangled_name demangled( name ); std::cout << (demangled.get() ? demangled.get() : "Failed to demangle") << std::endl; ```
1,488,186
Is it possible in C++ to stringify template arguments? I tried this: ``` #include <iostream> #define STRINGIFY(x) #x template <typename T> struct Stringify { Stringify() { std::cout << STRINGIFY(T) << endl; } }; int main() { Stringify<int> s; } ``` But what I get is a `T`, and not an `int`. Seems that the preprocessor macros are evaluated before template instantiation. Is there any other way to do this? Is there any way for the preprocessing to take place after template instantiation? (Compiler is VC++).
2009/09/28
[ "https://Stackoverflow.com/questions/1488186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177482/" ]
You could use some template magic. ``` #include <iostream> template <typename T> struct TypeName { static const char *name; }; template <typename T> const char *TypeName<T>::name = "unknown"; template <> const char *TypeName<int>::name = "int"; template <typename T> struct Stringify { Stringify() { std::cout << TypeName<T>::name << std::endl; } }; int main() { Stringify<int> s; } ``` This has an advantage over RTTI (i.e. `typeinfo`) - it is resolved during compilation; and disadvantage - you need to provide type information yourself (unless there is some library that does that already that I'm not aware of; maybe something in Boost even). Or, as [Martin York](https://stackoverflow.com/users/14065/martin-york) suggested in comments, use inline function templates instead: ``` template <typename T> inline const char* typeName(void) { return "unknown"; } template <> inline const char* typeName<int>(void) { return "int"; } // ... std::cout << typeName<T>() << std::endl; ``` But, if you'll ever need to store more information about that particular type, then class templates will probably be better.
No, you cannot work on types as if they were variables. You could write code that extracted the typeid() of an element and printed the name, but the resulting value will probably not be what you expect (type names are not standarized). You can also work with template specializations (and some macro magic) to achieve a more interesting version if the number of types you want to work with is limited: ``` template <typename T> const char* printtype(); // not implemented // implement specializations for given types #define DEFINE_PRINT_TYPE( type ) \ template<>\ const char* printtype<type>() {\ return #type;\ } DEFINE_PRINT_TYPE( int ); DEFINE_PRINT_TYPE( double ); // ... and so on #undef DEFINE_PRINT_TYPE template <typename T> void test() { std::cout << printtype<T>() << std::endl; } int main() { test<int>(); test<double>(); test<float>(); // compilation error, printtype undefined for float } ``` Or you could even combine both versions: implement the printtype generic template using typeinfo and then provide specializations for the types you want to have fancier names. ``` template <typename T> const char* printtype() { return typeid(T).name(); } ```
1,488,186
Is it possible in C++ to stringify template arguments? I tried this: ``` #include <iostream> #define STRINGIFY(x) #x template <typename T> struct Stringify { Stringify() { std::cout << STRINGIFY(T) << endl; } }; int main() { Stringify<int> s; } ``` But what I get is a `T`, and not an `int`. Seems that the preprocessor macros are evaluated before template instantiation. Is there any other way to do this? Is there any way for the preprocessing to take place after template instantiation? (Compiler is VC++).
2009/09/28
[ "https://Stackoverflow.com/questions/1488186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177482/" ]
No, you cannot work on types as if they were variables. You could write code that extracted the typeid() of an element and printed the name, but the resulting value will probably not be what you expect (type names are not standarized). You can also work with template specializations (and some macro magic) to achieve a more interesting version if the number of types you want to work with is limited: ``` template <typename T> const char* printtype(); // not implemented // implement specializations for given types #define DEFINE_PRINT_TYPE( type ) \ template<>\ const char* printtype<type>() {\ return #type;\ } DEFINE_PRINT_TYPE( int ); DEFINE_PRINT_TYPE( double ); // ... and so on #undef DEFINE_PRINT_TYPE template <typename T> void test() { std::cout << printtype<T>() << std::endl; } int main() { test<int>(); test<double>(); test<float>(); // compilation error, printtype undefined for float } ``` Or you could even combine both versions: implement the printtype generic template using typeinfo and then provide specializations for the types you want to have fancier names. ``` template <typename T> const char* printtype() { return typeid(T).name(); } ```
in my code I use the "awful" double-declaration of the "Class-Name" ``` MqFactoryC<MyServer>::Add("MyServer").Default(); ``` because c++ is NOT able to extract the string "MyServer" from the template… the only "way" to get "rid" of this… using a cpp "wrapper" ``` #define MQ_CPPSTR(s) #s #define MqFactoryCAdd(T) MqFactoryC<T>::Add(MQ_CPPSTR(T)).Default() ```
1,488,186
Is it possible in C++ to stringify template arguments? I tried this: ``` #include <iostream> #define STRINGIFY(x) #x template <typename T> struct Stringify { Stringify() { std::cout << STRINGIFY(T) << endl; } }; int main() { Stringify<int> s; } ``` But what I get is a `T`, and not an `int`. Seems that the preprocessor macros are evaluated before template instantiation. Is there any other way to do this? Is there any way for the preprocessing to take place after template instantiation? (Compiler is VC++).
2009/09/28
[ "https://Stackoverflow.com/questions/1488186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177482/" ]
You could try ``` typeid(T).name() ``` **Edit**: Fixed based on comments.
Here’s what I do: I have a `demangle()` function (implemented on top of `abi::__cxa_demangle()` which I call with a couple of convenience template function overloads, `nameof()`, with either the type I want stringified or an instance of same. It’s fairly compact, so I’ll reproduce it here in all its glory. In `demangle.hh` we have: ```cpp #pragma once #include <typeinfo> namespace terminator { /// actual function to demangle an allegedly mangled thing char const* demangle(char const* const symbol) noexcept; /// convenience function template to stringify a name of a type, /// either per an explicit specialization: /// char const* mytypename = terminator::nameof<SomeType>(); template <typename NameType> char const* nameof() { try { return demangle(typeid(NameType).name()); } catch (std::bad_typeid const&) { return "<unknown>"; } } /// … or as implied by an instance argument: /// char const* myinstancetypename = terminator::nameof(someinstance); template <typename ArgType> char const* nameof(ArgType argument) { try { return demangle(typeid(argument).name()); } catch (std::bad_typeid const&) { return "<unknown>"; } } } /* namespace terminator */ ``` … And then in `demangle.cpp`: ```cpp #include "demangle.hh" #include <cstdlib> #include <cxxabi.h> #include <mutex> #include <memory> namespace terminator { namespace { /// define one singular, private, static std::mutex, /// to keep the demangler from reentering itself static std::mutex mangle_barrier; /// define a corresponding private and static std::unique_ptr, /// using a delete-expression to reclaim the memory malloc()'ed by /// abi::__cxa_demangle() upon its return. /// … we use clang pragmas to add flags locally for this to work: #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #pragma clang diagnostic ignored "-Wexit-time-destructors" std::unique_ptr<char, decltype(std::free)&> demangled_name{ nullptr, std::free }; #pragma clang diagnostic pop } char const* demangle(char const* const symbol) noexcept { if (!symbol) { return "<null>"; } std::lock_guard<std::mutex> lock(mangle_barrier); int status = -4; demangled_name.reset( abi::__cxa_demangle(symbol, demangled_name.get(), nullptr, &status)); return ((status == 0) ? demangled_name.release() : symbol); } } /* namespace terminator */ ``` To use this, I think you’ll have to link to `libc++` (or whatever your local equivalent is) to use `abi::__cxa_demangle()`. What may be suboptimal for the OP is the fact that this does the demangling and stringification at runtime. I’d personally love something `constexpr`-friendly in leu of this, but since I suffer from a severe macro-abuse allergy, I find this to be the least generally-unreasonable solution to this problem. (the `terminator` namespace is inconsequential – I use this code in a libunwind-based stacktracer called from termination handler – feel free to `s///g` that token)
1,488,186
Is it possible in C++ to stringify template arguments? I tried this: ``` #include <iostream> #define STRINGIFY(x) #x template <typename T> struct Stringify { Stringify() { std::cout << STRINGIFY(T) << endl; } }; int main() { Stringify<int> s; } ``` But what I get is a `T`, and not an `int`. Seems that the preprocessor macros are evaluated before template instantiation. Is there any other way to do this? Is there any way for the preprocessing to take place after template instantiation? (Compiler is VC++).
2009/09/28
[ "https://Stackoverflow.com/questions/1488186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177482/" ]
You could use some template magic. ``` #include <iostream> template <typename T> struct TypeName { static const char *name; }; template <typename T> const char *TypeName<T>::name = "unknown"; template <> const char *TypeName<int>::name = "int"; template <typename T> struct Stringify { Stringify() { std::cout << TypeName<T>::name << std::endl; } }; int main() { Stringify<int> s; } ``` This has an advantage over RTTI (i.e. `typeinfo`) - it is resolved during compilation; and disadvantage - you need to provide type information yourself (unless there is some library that does that already that I'm not aware of; maybe something in Boost even). Or, as [Martin York](https://stackoverflow.com/users/14065/martin-york) suggested in comments, use inline function templates instead: ``` template <typename T> inline const char* typeName(void) { return "unknown"; } template <> inline const char* typeName<int>(void) { return "int"; } // ... std::cout << typeName<T>() << std::endl; ``` But, if you'll ever need to store more information about that particular type, then class templates will probably be better.
Your code doesn't work because the preprocessor, responsible for searching and expanding the macros you use in your code, is not aware of the language itself. It is just a text parser. It finds that STRINGIFY(T) in the very function template and expand it, much before you give a type to that template. As it turns out, you will always get "T" instead of the typename you expected, unfortunately. As [litb](https://stackoverflow.com/users/34509/litb) suggested, I've (badly) implemented this `getTypeName' function template that returns the typename you pass it: ``` #include <iostream> template <typename _Get_TypeName> const std::string &getTypeName() { static std::string name; if (name.empty()) { const char *beginStr = "_Get_TypeName ="; const size_t beginStrLen = 15; // Yes, I know... // But isn't it better than strlen()? size_t begin,length; name = __PRETTY_FUNCTION__; begin = name.find(beginStr) + beginStrLen + 1; length = name.find("]",begin) - begin; name = name.substr(begin,length); } return name; } int main() { typedef void (*T)(int,int); // Using getTypeName() std::cout << getTypeName<float>() << '\n'; std::cout << getTypeName<T>() << '\n'; // You don't actually need the // typedef in this case, but // for it to work with the // typeid below, you'll need it // Using typeid().name() std::cout << typeid(float).name() << '\n'; std::cout << typeid(T).name() << '\n'; return 0; } ``` The code above results in the following output with GCC flag -s ("strip all symbols from binary") enabled: ``` float void (*)(int, int) f PFviiE ``` So, you see, getTypename() does a fairly better job, at the cost of that fugly string parsing hack (I KNOW, it's damn ugly). A few points to take into account: * The code is GCC only. I don't know how to port it to another compiler. Probably only a few others have such a facility to produce so pretty function names, and from what I searched, MSVC++ doesn't have one, if you're asking yourself that. * If, in a new version, GCC formats `__PRETTY_FUNCTION__`'s differently, the string matching can break and you'll have to fix it. For this same reason I also warn that getTypeName() *might* be good for debugging (and, still, maybe not even good for that), but it is *surely* bad, bad, and bad for other purposes such as comparing two types in a template or something like that (I don't know, just guessing what someone might think of..). Use it solely for debugging, and preferentially don't call it in release builds (use macros to disable), so that you don't use `__PRETTY_FUNCTION__` and thus the compiler doesn't produce the string for it. * I'm definitely no expert, and I'm not sure whether some odd type could cause the string matching to fail. I'd like to ask for people who read this post to comment if they know of such a case. * The code uses a static std::string. It means that, if some exception is thrown from its constructor or destructor, there is no way that it will reach a catch block and you'll get an unhandled exception. I don't know whether std::strings can do that, but beware that, if they do, you're potentially in trouble. I used it because it needs a destructor to free the memory. You could implement your own class for that, though, ensuring no exception is thrown besides allocation failure (that's pretty much fatal, isn't it? So...), and return a simple C-string. * With typedefs you can get some weird results, like this (for some reason, the site breaks the formatting of this snippet, so I'm using this paste link): <http://pastebin.com/f51b888ad> Despite those disadvantages, I'd like to say that it sure is fast. For the second time you lookup for one same type name, it will cost picking a reference to a global std::string containing the name. And, comparatively to the template specialiazation methods suggested before, there is nothing else you have to declare besides the very template itself, so it is really much easier to use.
1,488,186
Is it possible in C++ to stringify template arguments? I tried this: ``` #include <iostream> #define STRINGIFY(x) #x template <typename T> struct Stringify { Stringify() { std::cout << STRINGIFY(T) << endl; } }; int main() { Stringify<int> s; } ``` But what I get is a `T`, and not an `int`. Seems that the preprocessor macros are evaluated before template instantiation. Is there any other way to do this? Is there any way for the preprocessing to take place after template instantiation? (Compiler is VC++).
2009/09/28
[ "https://Stackoverflow.com/questions/1488186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177482/" ]
You could try ``` typeid(T).name() ``` **Edit**: Fixed based on comments.
No, you cannot work on types as if they were variables. You could write code that extracted the typeid() of an element and printed the name, but the resulting value will probably not be what you expect (type names are not standarized). You can also work with template specializations (and some macro magic) to achieve a more interesting version if the number of types you want to work with is limited: ``` template <typename T> const char* printtype(); // not implemented // implement specializations for given types #define DEFINE_PRINT_TYPE( type ) \ template<>\ const char* printtype<type>() {\ return #type;\ } DEFINE_PRINT_TYPE( int ); DEFINE_PRINT_TYPE( double ); // ... and so on #undef DEFINE_PRINT_TYPE template <typename T> void test() { std::cout << printtype<T>() << std::endl; } int main() { test<int>(); test<double>(); test<float>(); // compilation error, printtype undefined for float } ``` Or you could even combine both versions: implement the printtype generic template using typeinfo and then provide specializations for the types you want to have fancier names. ``` template <typename T> const char* printtype() { return typeid(T).name(); } ```
1,488,186
Is it possible in C++ to stringify template arguments? I tried this: ``` #include <iostream> #define STRINGIFY(x) #x template <typename T> struct Stringify { Stringify() { std::cout << STRINGIFY(T) << endl; } }; int main() { Stringify<int> s; } ``` But what I get is a `T`, and not an `int`. Seems that the preprocessor macros are evaluated before template instantiation. Is there any other way to do this? Is there any way for the preprocessing to take place after template instantiation? (Compiler is VC++).
2009/09/28
[ "https://Stackoverflow.com/questions/1488186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177482/" ]
You could try ``` typeid(T).name() ``` **Edit**: Fixed based on comments.
This breaks one of my primary tenets of C++ code writing: Avoid using tricks in both the template features and the preprocessor at the same time. Part of the reason for templates and the nastiness they introduce into the language was an attempt to wean developers away from using the preprocessor. If you use both, then the terrorists win.
1,488,186
Is it possible in C++ to stringify template arguments? I tried this: ``` #include <iostream> #define STRINGIFY(x) #x template <typename T> struct Stringify { Stringify() { std::cout << STRINGIFY(T) << endl; } }; int main() { Stringify<int> s; } ``` But what I get is a `T`, and not an `int`. Seems that the preprocessor macros are evaluated before template instantiation. Is there any other way to do this? Is there any way for the preprocessing to take place after template instantiation? (Compiler is VC++).
2009/09/28
[ "https://Stackoverflow.com/questions/1488186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177482/" ]
You could try ``` typeid(T).name() ``` **Edit**: Fixed based on comments.
in my code I use the "awful" double-declaration of the "Class-Name" ``` MqFactoryC<MyServer>::Add("MyServer").Default(); ``` because c++ is NOT able to extract the string "MyServer" from the template… the only "way" to get "rid" of this… using a cpp "wrapper" ``` #define MQ_CPPSTR(s) #s #define MqFactoryCAdd(T) MqFactoryC<T>::Add(MQ_CPPSTR(T)).Default() ```
1,488,186
Is it possible in C++ to stringify template arguments? I tried this: ``` #include <iostream> #define STRINGIFY(x) #x template <typename T> struct Stringify { Stringify() { std::cout << STRINGIFY(T) << endl; } }; int main() { Stringify<int> s; } ``` But what I get is a `T`, and not an `int`. Seems that the preprocessor macros are evaluated before template instantiation. Is there any other way to do this? Is there any way for the preprocessing to take place after template instantiation? (Compiler is VC++).
2009/09/28
[ "https://Stackoverflow.com/questions/1488186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177482/" ]
You could use some template magic. ``` #include <iostream> template <typename T> struct TypeName { static const char *name; }; template <typename T> const char *TypeName<T>::name = "unknown"; template <> const char *TypeName<int>::name = "int"; template <typename T> struct Stringify { Stringify() { std::cout << TypeName<T>::name << std::endl; } }; int main() { Stringify<int> s; } ``` This has an advantage over RTTI (i.e. `typeinfo`) - it is resolved during compilation; and disadvantage - you need to provide type information yourself (unless there is some library that does that already that I'm not aware of; maybe something in Boost even). Or, as [Martin York](https://stackoverflow.com/users/14065/martin-york) suggested in comments, use inline function templates instead: ``` template <typename T> inline const char* typeName(void) { return "unknown"; } template <> inline const char* typeName<int>(void) { return "int"; } // ... std::cout << typeName<T>() << std::endl; ``` But, if you'll ever need to store more information about that particular type, then class templates will probably be better.
This breaks one of my primary tenets of C++ code writing: Avoid using tricks in both the template features and the preprocessor at the same time. Part of the reason for templates and the nastiness they introduce into the language was an attempt to wean developers away from using the preprocessor. If you use both, then the terrorists win.
44,205,591
I am using @angular v4.0.3 and webpack 2.2.0. It was working fine using [Auler](http://ium.com/@evertonrobertoauler/angular-4-universal-app-with-angular-cli-db8b53bba07d) post but as I included localStorage it stopped working. Is there any way to make it work or any module for localStorage in angular universal
2017/05/26
[ "https://Stackoverflow.com/questions/44205591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6214945/" ]
A good way is to make `localStorage` an injectable and provide different implementations for it. An abstract class that reflects [`Storage` API](https://github.com/Microsoft/TypeScript/blob/v2.3.3/lib/lib.d.ts#L15751-L15760) can be used as a token: ``` export abstract class LocalStorage { readonly length: number; abstract clear(): void; abstract getItem(key: string): string | null; abstract key(index: number): string | null; abstract removeItem(key: string): void; abstract setItem(key: string, data: string): void; [key: string]: any; [index: number]: string; } ``` Then for browser app module it is ``` export function localStorageFactory() { return localStorage; } ... { provide: LocalStorage, useFactory: localStorageFactory } ``` And for server app module `localStorage` can be replaced with some implementation, like [`node-storage-shim`](https://github.com/mnahkies/node-storage-shim) for in-memory storage: ``` { provide: LocalStorage, useClass: StorageShim } ``` Using DI instead of global persistent storage also makes testing easier.
This happens because using Angular Universal for Server Side Rendering, the Angular app runs in both the Nodejs server and the client browser. At this point, the server app does not have a reference to the localStorage object, because it is only available on the client-side. There's an article I wrote about this with the solution implemented: [How to use localStorage on Angular 9 Universal (SSR)](https://medium.com/@santibarbat/how-to-use-localstorage-with-angular-9-universal-ssr-517578615637)
974,186
I feel like this should be easy, but I can't remember the technique that I should use to solve this. How does one solve an integral like this: $$\int\_0^\infty \frac x {(x+1)^3}$$
2014/10/15
[ "https://math.stackexchange.com/questions/974186", "https://math.stackexchange.com", "https://math.stackexchange.com/users/184443/" ]
Try this $${x\over (x +1)^3} = {x + 1\over(x + 1)^3} - {1\over(x+1)^3}. $$
\begin{align\*} & \int\_0^\infty \frac{x}{(x+1)^3} \mathrm{d} x \\ & = \int\_0^\infty \frac{x + 1 -1}{(x+1)^3} \mathrm{d} x \\ & = \int\_0^\infty \left( \frac{1}{(x+1)^2} - \frac{1}{(x+1)^3} \right) \mathrm{d} x \\ \end{align\*} Now use the substitution $u = x+1$.
974,186
I feel like this should be easy, but I can't remember the technique that I should use to solve this. How does one solve an integral like this: $$\int\_0^\infty \frac x {(x+1)^3}$$
2014/10/15
[ "https://math.stackexchange.com/questions/974186", "https://math.stackexchange.com", "https://math.stackexchange.com/users/184443/" ]
$$ \int\_0^\infty \frac{x}{(x+1)^3} \mathrm{d} x =\int\_1^\infty \frac{x-1}{x^3} \mathrm{d} x \\ =\left[-\frac1{x} + \frac12 \frac1{x^2}\right]\_1^{\infty}=\frac12 $$
\begin{align\*} & \int\_0^\infty \frac{x}{(x+1)^3} \mathrm{d} x \\ & = \int\_0^\infty \frac{x + 1 -1}{(x+1)^3} \mathrm{d} x \\ & = \int\_0^\infty \left( \frac{1}{(x+1)^2} - \frac{1}{(x+1)^3} \right) \mathrm{d} x \\ \end{align\*} Now use the substitution $u = x+1$.
59,989,280
We have a situation in oracle SQL. ``` select x from A where x=10; ``` so if `10` exists in the column, value will be displayed `10`. but if it doesn't exists I want to display `null`. I tried `NVL` but it is not returning anything as data is not displaying. Could you please help me to resolve this.
2020/01/30
[ "https://Stackoverflow.com/questions/59989280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you want to return multiple rows from the original `SELECT` then you can use `UNION ALL` to add a row when the value does not exist: ```sql SELECT x FROM A WHERE x = 10 UNION ALL SELECT NULL FROM DUAL WHERE NOT EXISTS ( SELECT x FROM A WHERE x = 10 ) ``` If your table is: ```sql CREATE TABLE a ( x ) AS SELECT 10 FROM DUAL UNION ALL SELECT 10 FROM DUAL UNION ALL SELECT 10 FROM DUAL; ``` Then the query will output: > > > ``` > > | X | > | -: | > | 10 | > | 10 | > | 10 | > > ``` > > Then if you `DELETE FROM a;` and repeat the query, it will output: > > > ``` > > | X | > | ---: | > | *null* | > > ``` > > *db<>fiddle [here](https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=e7d9429506b034b7de16ac873b9d958d)*
Try this: ``` select max(x) from A where x = 10; --this will return null if no data ``` And then you can do a NVL: ``` select nvl(max(x), 0) from A where x = 10; --this will return 0 if no data ```
59,989,280
We have a situation in oracle SQL. ``` select x from A where x=10; ``` so if `10` exists in the column, value will be displayed `10`. but if it doesn't exists I want to display `null`. I tried `NVL` but it is not returning anything as data is not displaying. Could you please help me to resolve this.
2020/01/30
[ "https://Stackoverflow.com/questions/59989280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you want to return multiple rows from the original `SELECT` then you can use `UNION ALL` to add a row when the value does not exist: ```sql SELECT x FROM A WHERE x = 10 UNION ALL SELECT NULL FROM DUAL WHERE NOT EXISTS ( SELECT x FROM A WHERE x = 10 ) ``` If your table is: ```sql CREATE TABLE a ( x ) AS SELECT 10 FROM DUAL UNION ALL SELECT 10 FROM DUAL UNION ALL SELECT 10 FROM DUAL; ``` Then the query will output: > > > ``` > > | X | > | -: | > | 10 | > | 10 | > | 10 | > > ``` > > Then if you `DELETE FROM a;` and repeat the query, it will output: > > > ``` > > | X | > | ---: | > | *null* | > > ``` > > *db<>fiddle [here](https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=e7d9429506b034b7de16ac873b9d958d)*
`Where` clause filter out the data what you are looking for, if it doesn't exists then query will return no record. So, you can remove `where` clause & do aggregation : ``` select max(case when a.x = 10 then 10 end) from a; ```
73,682,009
I would like to make 3 radio buttons and I would like to get the value of checked one when I press a button. ``` <py-script> <input id="rad1" name="choice" type="radio"> <label for="rad1">1</label> <input id="rad2" name="choice" type="radio"> <label for="rad2">2</label> <input id="rad3" name="choice" type="radio"> <label for="rad3">3</label> <button id="btn">Go</button> <py-script> from js import document from pyodide import create_proxy def on_btn_click(event): global choice checked_value = ___???___ ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← choice = checked_value button = document.querySelector("#btn") button.addEventListener("click", create_proxy(on_btn_click)) </py-script> ``` What is missing in the `??? ← ← ← ← ← ← ←` in order to grab the checked value in the function handler?
2022/09/11
[ "https://Stackoverflow.com/questions/73682009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389717/" ]
You may check every radio button separatelly and use `if/else` to set correct value ``` document.querySelector("#rad1").checked document.querySelector("#rad2").checked document.querySelector("#rad3").checked ``` But if you have the same name in all radio buttons then you can use `name` and pseudo-selector `:checked` to get only checked radio button ``` document.querySelector("[name='choice']:checked").id ``` And if you add `value="1"` directly in radio button then you can get value ``` document.querySelector("[name='choice']:checked").value ``` --- BTW: If you don't have other radio buttons with different name then you could reduce it to ``` document.querySelector(":checked").value ``` --- Minimal working code which displays selection in JavaScript console (in DevTools) ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1" /> <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> <script defer src="https://pyscript.net/latest/pyscript.js"></script> </head> <body> <input id="rad1" type="radio" name="choice" value="1"><label for="rad1">1</label> <input id="rad2" type="radio" name="choice" value="2"><label for="rad2">2</label> <input id="rad3" type="radio" name="choice" value="3"><label for="rad3">3</label> <button id="btn">Go</button> <py-script> from js import document from js import console from pyodide import create_proxy def on_btn_click(event): global choice console.log(event) #console.log('#rad1: ' + document.querySelector("#rad1").checked) #console.log('#rad2: ' + document.querySelector("#rad2").checked) #console.log('#rad3: ' + document.querySelector("#rad3").checked) console.log('id: ' + document.querySelector("[name='choice']:checked").id) console.log('value: ' + document.querySelector("[name='choice']:checked").value) button = document.querySelector("#btn") button.addEventListener("click", create_proxy(on_btn_click)) </py-script> </body> </html> ``` JavaScript Console in Firefox: [![enter image description here](https://i.stack.imgur.com/7P4HU.png)](https://i.stack.imgur.com/7P4HU.png)
As someone in the comments said, ``` document.querySelector("#rad1").checked ``` should do the trick. You can do it this way in javascript and this is pretty much the same (ofc not identical but still).
39,345,634
I have tried `var res = str.replace(/ |,|.|/g, "");` and `var res = str.replace(/ |,|.|/gi, "");`. What am I missing here? ```js var str = "Text with comma, space, and period."; var res = str.replace(/ |,|.|/g, ""); document.write(res); ```
2016/09/06
[ "https://Stackoverflow.com/questions/39345634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6764260/" ]
If you just want to delete all spaces, commas and periods you can do it like that: ``` var res = str.replace(/[ ,.]/g, ""); ``` You can also use the `|` operator, but in that case you have to escape the period, because a plain period will match with any character. As a general remark, if in a regular expression you have multiple alternatives with `|` that all consist of a single character, it is preferable to use a set with `[...]`.
You need to escape dot `\.`: ``` "Text with comma, space and period.".replace(/ |,|\.|/g, "") ```
39,345,634
I have tried `var res = str.replace(/ |,|.|/g, "");` and `var res = str.replace(/ |,|.|/gi, "");`. What am I missing here? ```js var str = "Text with comma, space, and period."; var res = str.replace(/ |,|.|/g, ""); document.write(res); ```
2016/09/06
[ "https://Stackoverflow.com/questions/39345634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6764260/" ]
You need to escape dot `\.`: ``` "Text with comma, space and period.".replace(/ |,|\.|/g, "") ```
You can use these lines: ``` str = str.replace(/[ ,.]/g,''); ``` Plus i have added a fiddle for this at [Fiddle](https://jsfiddle.net/ac8Lh7tn/)
39,345,634
I have tried `var res = str.replace(/ |,|.|/g, "");` and `var res = str.replace(/ |,|.|/gi, "");`. What am I missing here? ```js var str = "Text with comma, space, and period."; var res = str.replace(/ |,|.|/g, ""); document.write(res); ```
2016/09/06
[ "https://Stackoverflow.com/questions/39345634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6764260/" ]
If you just want to delete all spaces, commas and periods you can do it like that: ``` var res = str.replace(/[ ,.]/g, ""); ``` You can also use the `|` operator, but in that case you have to escape the period, because a plain period will match with any character. As a general remark, if in a regular expression you have multiple alternatives with `|` that all consist of a single character, it is preferable to use a set with `[...]`.
You can use these lines: ``` str = str.replace(/[ ,.]/g,''); ``` Plus i have added a fiddle for this at [Fiddle](https://jsfiddle.net/ac8Lh7tn/)
7,402,617
I'm trying to copy a column with data from a table to another in MySQL. But I can't wrap my head around it. Both tables have an id column called 'nid' which fits perfectly. I want to move the column called 'field\_pref\_position\_value' from the table 'content\_field\_pref\_position' to the column 'pref\_position' in the table 'content\_type\_player'. I already made the column 'pref\_position'. Any help much appreciated. **EDIT:** I made a huge mistake. I copied the column to the table 'content\_type\_player' instead of 'content\_type\_transfer' which it should have been, but now when i'm trying to use the same query for content\_type\_transfer it just returns **'0 row(s) affected. ( Query took 0.0015 sec )'** without updating the column. Can't figure out what the deal is? I'm using this Query: ``` UPDATE content_type_transfer JOIN content_field_pref_position ON content_field_pref_position.nid = content_type_transfer.nid SET content_type_transfer.pref_position = content_field_pref_position.field_pref_position_value ```
2011/09/13
[ "https://Stackoverflow.com/questions/7402617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/935038/" ]
I think you have just named the same table twice: ``` UPDATE content_type_player SET content_type_player.pref_position = content_field_pref_position.field_pref_position_value FROM content_field_**player** JOIN content_field_pref_position ON content_type_player.nid = content_field_pref_position.nid ```
As suggested by @heximal ``` UPDATE content_type_player SET b.pref_position = a.field_pref_position_value FROM content_field_pref_position a content_type_player b WHERE a.nid = b.nid ```
7,402,617
I'm trying to copy a column with data from a table to another in MySQL. But I can't wrap my head around it. Both tables have an id column called 'nid' which fits perfectly. I want to move the column called 'field\_pref\_position\_value' from the table 'content\_field\_pref\_position' to the column 'pref\_position' in the table 'content\_type\_player'. I already made the column 'pref\_position'. Any help much appreciated. **EDIT:** I made a huge mistake. I copied the column to the table 'content\_type\_player' instead of 'content\_type\_transfer' which it should have been, but now when i'm trying to use the same query for content\_type\_transfer it just returns **'0 row(s) affected. ( Query took 0.0015 sec )'** without updating the column. Can't figure out what the deal is? I'm using this Query: ``` UPDATE content_type_transfer JOIN content_field_pref_position ON content_field_pref_position.nid = content_type_transfer.nid SET content_type_transfer.pref_position = content_field_pref_position.field_pref_position_value ```
2011/09/13
[ "https://Stackoverflow.com/questions/7402617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/935038/" ]
I think you have just named the same table twice: ``` UPDATE content_type_player SET content_type_player.pref_position = content_field_pref_position.field_pref_position_value FROM content_field_**player** JOIN content_field_pref_position ON content_type_player.nid = content_field_pref_position.nid ```
As suggested by Nielsiano ``` UPDATE content_type_player JOIN content_field_pref_position ON content_field_pref_position.nid = content_type_player.nid SET content_type_player.pref_position = content_field_pref_position.field_pref_position_value ```
2,975,824
In googling I can't seem to find an example of intercepting event on a proxied type and it doesn't seem to be working for me. Is there a way I can do this (ie. use an IInterceptor when an event is invoked)?
2010/06/04
[ "https://Stackoverflow.com/questions/2975824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326518/" ]
I've used this in a Universal app to determine if the code is running on an iPad ``` if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // Do iPad only stuff here } ```
Check out the documentation for [UIDevice](http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIDevice_Class/Reference/UIDevice.html)
2,975,824
In googling I can't seem to find an example of intercepting event on a proxied type and it doesn't seem to be working for me. Is there a way I can do this (ie. use an IInterceptor when an event is invoked)?
2010/06/04
[ "https://Stackoverflow.com/questions/2975824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326518/" ]
Check out the documentation for [UIDevice](http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIDevice_Class/Reference/UIDevice.html)
Look at `UIDevice` and it's properties. There is a `systemVersion` string that will work for what you want.