diff --git "a/data/finetune/train_data.csv" "b/data/finetune/train_data.csv" new file mode 100644--- /dev/null +++ "b/data/finetune/train_data.csv" @@ -0,0 +1,60782 @@ +qid,question,date,metadata,response_j,response_k +53179085,"I'm writing a code using Java Swing to press the right button when I type a number key. +But I can't find what I want through search. +This is my code and I can't understand why this isn't working. +Please help me.. + +``` +import javax.swing.*; +import java.awt.Dimension; +import java.awt.event.*; + +class class01 { + + public static void main(String[] args) { + + JFrame f = new JFrame(""Key event test""); + f.setSize(230, 500); + f.setLayout(null); + f.setVisible(true); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JLabel label = new JLabel(); + + JButton button1 = new JButton(""Coffe""); + button1.setSize(100, 100); + button1.setLocation(0, 0); + + JButton button2 = new JButton(""Latte""); + button2.setSize(100, 100); + button2.setLocation(0, 100); + + JButton button3 = new JButton(""Espresso""); + button3.setSize(100, 100); + button3.setLocation(100, 100); + + JButton button4 = new JButton(""Vanilla Latte""); + button4.setSize(100, 100); + button4.setLocation(100, 0); + + f.add(button1); + f.add(button2); + f.add(button3); + f.add(button4); + + // Show message when the corresponding button is pressed. + button1.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + button1.keyPressed(KeyEvent.VK_1); + JOptionPane.showMessageDialog(f.getComponent(0), ""Coffee selected""); + } + }); + button2.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + button2.keyPressed(KeyEvent.VK_2); + JOptionPane.showMessageDialog(f.getComponent(0), ""Latte selected""); + } + }); + button3.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + button3.keyPressed(KeyEvent.VK_3); + JOptionPane.showMessageDialog(f.getComponent(0), ""Espresso selected""); + } + }); + button4.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + button4.keyPressed(KeyEvent.VK_4); + JOptionPane.showMessageDialog(f.getComponent(0), ""Vanilla Latte selected""); + } + }); + } +} + +```",2018/11/06,"['https://Stackoverflow.com/questions/53179085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8933767/']","The code you are showing does exactly one thing: attach action listeners to your buttons.. + +Meaning: when you click the button, then the listener will be called. + +You need a generic keyboard listener that translates key events into calls to the appropriate button, respectively action listener instead.","When you do this: + +``` +button1.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + button1.keyPressed(KeyEvent.VK_1); + JOptionPane.showMessageDialog(f.getComponent(0), ""Coffee selected""); + } + }); + +``` + +You are telling `button1` what to do when somebody clicks on the button. The line with `keyPressed` should not be there (it does not compile even). + +What you need to do is listen for key presses by adding a `KeyListener` to the frame like this: + +``` +f.addKeyListener(new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) { + if( e.getKeyChar() == KeyEvent.VK_1) { + JOptionPane.showMessageDialog(f.getComponent(0), ""Coffee selected""); + } + } + }); + +``` + +I repeated the `showMessageDialog`, but you should extract the actual logic into a method and call that method from within the `KeyListener` on the frame and the `ActionListener` on the button." +53179085,"I'm writing a code using Java Swing to press the right button when I type a number key. +But I can't find what I want through search. +This is my code and I can't understand why this isn't working. +Please help me.. + +``` +import javax.swing.*; +import java.awt.Dimension; +import java.awt.event.*; + +class class01 { + + public static void main(String[] args) { + + JFrame f = new JFrame(""Key event test""); + f.setSize(230, 500); + f.setLayout(null); + f.setVisible(true); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JLabel label = new JLabel(); + + JButton button1 = new JButton(""Coffe""); + button1.setSize(100, 100); + button1.setLocation(0, 0); + + JButton button2 = new JButton(""Latte""); + button2.setSize(100, 100); + button2.setLocation(0, 100); + + JButton button3 = new JButton(""Espresso""); + button3.setSize(100, 100); + button3.setLocation(100, 100); + + JButton button4 = new JButton(""Vanilla Latte""); + button4.setSize(100, 100); + button4.setLocation(100, 0); + + f.add(button1); + f.add(button2); + f.add(button3); + f.add(button4); + + // Show message when the corresponding button is pressed. + button1.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + button1.keyPressed(KeyEvent.VK_1); + JOptionPane.showMessageDialog(f.getComponent(0), ""Coffee selected""); + } + }); + button2.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + button2.keyPressed(KeyEvent.VK_2); + JOptionPane.showMessageDialog(f.getComponent(0), ""Latte selected""); + } + }); + button3.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + button3.keyPressed(KeyEvent.VK_3); + JOptionPane.showMessageDialog(f.getComponent(0), ""Espresso selected""); + } + }); + button4.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + button4.keyPressed(KeyEvent.VK_4); + JOptionPane.showMessageDialog(f.getComponent(0), ""Vanilla Latte selected""); + } + }); + } +} + +```",2018/11/06,"['https://Stackoverflow.com/questions/53179085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8933767/']","From what I understand, essentially you want to have the same operation of a button assigned to a specific key stroke. + +Things you want to avoid are `KeyListener`, especially because you have other focusable components in the view, namely buttons, which will steal keyboard focus and render the `KeyListener` useless. This is why, in almost all cases, you want to avoid `KeyListener`. + +A better and more reliable solution would be to use the [Key Bindings API](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html), which overcomes this focus related issue, but it also encourages the use of reusable components of work through the [`Action`s API](https://docs.oracle.com/javase/tutorial/uiswing/misc/action.html) + +Something like... + +``` +import java.awt.EventQueue; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.util.StringJoiner; +import javax.swing.AbstractAction; +import javax.swing.ActionMap; +import javax.swing.InputMap; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.KeyStroke; + +public class Test { + + public static void main(String[] args) { + new Test(); + } + + public Test() { + EventQueue.invokeLater(new Runnable() { + @Override + public void run() { + JFrame frame = new JFrame(); + frame.add(new TestPane()); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + }); + } + + public class TestPane extends JPanel { + + public TestPane() { + JTextField field = new JTextField(10); + field.setEditable(false); + field.setFocusable(false); + + InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW); + ActionMap am = getActionMap(); + + im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), ""Pressed.One""); + im.put(KeyStroke.getKeyStroke(KeyEvent.VK_2, 0), ""Pressed.Two""); + im.put(KeyStroke.getKeyStroke(KeyEvent.VK_3, 0), ""Pressed.Three""); + im.put(KeyStroke.getKeyStroke(KeyEvent.VK_4, 0), ""Pressed.Four""); + + am.put(""Pressed.One"", new OrderAction(1, field)); + am.put(""Pressed.Two"", new OrderAction(2, field)); + am.put(""Pressed.Three"", new OrderAction(3, field)); + am.put(""Pressed.Four"", new OrderAction(4, field)); + + JButton btnOne = new JButton(new OrderAction(1, field)); + JButton btnTwo = new JButton(new OrderAction(2, field)); + JButton btnThree = new JButton(new OrderAction(3, field)); + JButton btnFour = new JButton(new OrderAction(4, field)); + + setLayout(new GridBagLayout()); + GridBagConstraints gbc = new GridBagConstraints(); + + gbc.weightx = 1; + gbc.weighty = 1; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.gridy = 1; + add(btnOne, gbc); + gbc.gridx++; + add(btnTwo, gbc); + gbc.gridx = 0; + gbc.gridy++; + add(btnThree, gbc); + gbc.gridx++; + add(btnFour, gbc); + + gbc.gridx = 0; + gbc.gridy = 0; + + gbc.gridwidth = 2; + add(field, gbc); + } + + protected class OrderAction extends AbstractAction { + + private int value; + private JTextField field; + + public OrderAction(int value, JTextField field) { + this.value = value; + this.field = field; + switch (value) { + case 1: + putValue(NAME, ""Coffe""); + break; + case 2: + putValue(NAME, ""Latte""); + break; + case 3: + putValue(NAME, ""Espresso""); + break; + case 4: + putValue(NAME, ""Vanilla Latte""); + break; + } + } + + @Override + public void actionPerformed(ActionEvent e) { + StringJoiner sj = new StringJoiner(""; ""); + if (field.getText() != null && field.getText().length() > 0) { + sj.add(field.getText()); + } + sj.add(Integer.toString(value)); + field.setText(sj.toString()); + } + + } + + } + +} + +``` + +Note, you could apply the key bindings directly to each button instead + +Now, if you want to ""visually"" press the button on a key stroke, I would recommend either creating a custom `JButton` or factory method, which could allow for a more simplified implementation, but the basic idea would be to define a key binding and `Action` which simply called the buttons `doClick` method, for example + +``` +import java.awt.EventQueue; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.util.StringJoiner; +import javax.swing.AbstractAction; +import javax.swing.ActionMap; +import javax.swing.InputMap; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.KeyStroke; + +public class Test { + + public static void main(String[] args) { + new Test(); + } + + public Test() { + EventQueue.invokeLater(new Runnable() { + @Override + public void run() { + JFrame frame = new JFrame(); + frame.add(new TestPane()); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + }); + } + + public class TestPane extends JPanel { + + public TestPane() { + JTextField field = new JTextField(10); + field.setEditable(false); + field.setFocusable(false); + + JButton btnOne = new JButton(new OrderAction(1, field)); + JButton btnTwo = new JButton(new OrderAction(2, field)); + JButton btnThree = new JButton(new OrderAction(3, field)); + JButton btnFour = new JButton(new OrderAction(4, field)); + + InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW); + ActionMap am = getActionMap(); + + im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), ""Pressed.One""); + im.put(KeyStroke.getKeyStroke(KeyEvent.VK_2, 0), ""Pressed.Two""); + im.put(KeyStroke.getKeyStroke(KeyEvent.VK_3, 0), ""Pressed.Three""); + im.put(KeyStroke.getKeyStroke(KeyEvent.VK_4, 0), ""Pressed.Four""); + + am.put(""Pressed.One"", new ProxyAction(btnOne)); + am.put(""Pressed.Two"", new ProxyAction(btnTwo)); + am.put(""Pressed.Three"", new ProxyAction(btnThree)); + am.put(""Pressed.Four"", new ProxyAction(btnFour)); + + setLayout(new GridBagLayout()); + GridBagConstraints gbc = new GridBagConstraints(); + + gbc.weightx = 1; + gbc.weighty = 1; + gbc.fill = GridBagConstraints.BOTH; + gbc.gridx = 0; + gbc.gridy = 1; + add(btnOne, gbc); + gbc.gridx++; + add(btnTwo, gbc); + gbc.gridx = 0; + gbc.gridy++; + add(btnThree, gbc); + gbc.gridx++; + add(btnFour, gbc); + + gbc.gridx = 0; + gbc.gridy = 0; + + gbc.gridwidth = 2; + add(field, gbc); + } + + protected class ProxyAction extends AbstractAction { + + private JButton btn; + + public ProxyAction(JButton btn) { + this.btn = btn; + } + + @Override + public void actionPerformed(ActionEvent e) { + btn.doClick(); + } + + } + + protected class OrderAction extends AbstractAction { + + private int value; + private JTextField field; + + public OrderAction(int value, JTextField field) { + this.value = value; + this.field = field; + switch (value) { + case 1: + putValue(NAME, ""Coffe""); + break; + case 2: + putValue(NAME, ""Latte""); + break; + case 3: + putValue(NAME, ""Espresso""); + break; + case 4: + putValue(NAME, ""Vanilla Latte""); + break; + } + } + + @Override + public void actionPerformed(ActionEvent e) { + StringJoiner sj = new StringJoiner(""; ""); + if (field.getText() != null && field.getText().length() > 0) { + sj.add(field.getText()); + } + sj.add(Integer.toString(value)); + field.setText(sj.toString()); + } + + } + + } + +} + +```","When you do this: + +``` +button1.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg0) { + button1.keyPressed(KeyEvent.VK_1); + JOptionPane.showMessageDialog(f.getComponent(0), ""Coffee selected""); + } + }); + +``` + +You are telling `button1` what to do when somebody clicks on the button. The line with `keyPressed` should not be there (it does not compile even). + +What you need to do is listen for key presses by adding a `KeyListener` to the frame like this: + +``` +f.addKeyListener(new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) { + if( e.getKeyChar() == KeyEvent.VK_1) { + JOptionPane.showMessageDialog(f.getComponent(0), ""Coffee selected""); + } + } + }); + +``` + +I repeated the `showMessageDialog`, but you should extract the actual logic into a method and call that method from within the `KeyListener` on the frame and the `ActionListener` on the button." +213173,"I am a senior Siebel CRM developer having more than 8 years of working experience. Now, I am very keen and excited to learn Salesforce and get certified as soon as possible. + +Please guide me where to start from scratch ?",2018/03/29,"['https://salesforce.stackexchange.com/questions/213173', 'https://salesforce.stackexchange.com', 'https://salesforce.stackexchange.com/users/55249/']","After some research and not reaching to any solution, I refreshed the selected Business Units by removing them, saving and the adding and saving again. This solved my issue.","You may need to raise the case with SFMC support. I have seen these issues, and support needs to toggle some backend settings to reset the SC and SFMC connection." +6763429,"i want to write a shape with "" \* "" and "" | "" the shape is below. +The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5 + +``` + +|*____| +|_*___| +|__*__| +|___*_| +|____*| +|___*_| +|__*__| +|_*___| +|*____| +|_*___| + +``` + +``` + private static void Function() + { + int height, width; + + if (width == 2) + while (height > 0) + { + FirstPart(width, height); + height -= width; + } + else + while (height > 0) + { + if (height > 1) + { + FirstPart(width, height); + height -= width; + } + if (height > 0) + { + SecondPart(width, height); + height -= width - 2; + } + } + } + + private static void FirstPart(int width,int height) + { + + if(height > width) + for (int i = 0; i < width; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + private static void SecondPart(int width,int height) + { + + if(height > width) + + for (int i = 0; i < width-2; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width-1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width - 1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + +```",2011/07/20,"['https://Stackoverflow.com/questions/6763429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/852118/']","I see a + +``` +while (Height > 0) + +``` + +so your infinite loop is coming from Height never getting less or equal to 0.","It's better to rewrite. When you do, decouple the code into several functions so that one function draws a single line, and another one calls the former to draw all the lines." +6763429,"i want to write a shape with "" \* "" and "" | "" the shape is below. +The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5 + +``` + +|*____| +|_*___| +|__*__| +|___*_| +|____*| +|___*_| +|__*__| +|_*___| +|*____| +|_*___| + +``` + +``` + private static void Function() + { + int height, width; + + if (width == 2) + while (height > 0) + { + FirstPart(width, height); + height -= width; + } + else + while (height > 0) + { + if (height > 1) + { + FirstPart(width, height); + height -= width; + } + if (height > 0) + { + SecondPart(width, height); + height -= width - 2; + } + } + } + + private static void FirstPart(int width,int height) + { + + if(height > width) + for (int i = 0; i < width; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + private static void SecondPart(int width,int height) + { + + if(height > width) + + for (int i = 0; i < width-2; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width-1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width - 1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + +```",2011/07/20,"['https://Stackoverflow.com/questions/6763429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/852118/']","I see a + +``` +while (Height > 0) + +``` + +so your infinite loop is coming from Height never getting less or equal to 0.","``` +void WriteStars(int Width,int Height) +{ + int _sp=1; //Star Pos + bool _left = false; + for(int i =0;i 0) + { + FirstPart(width, height); + height -= width; + } + else + while (height > 0) + { + if (height > 1) + { + FirstPart(width, height); + height -= width; + } + if (height > 0) + { + SecondPart(width, height); + height -= width - 2; + } + } + } + + private static void FirstPart(int width,int height) + { + + if(height > width) + for (int i = 0; i < width; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + private static void SecondPart(int width,int height) + { + + if(height > width) + + for (int i = 0; i < width-2; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width-1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width - 1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + +```",2011/07/20,"['https://Stackoverflow.com/questions/6763429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/852118/']","``` + private static void WriteStars(int width, int height) + { + int j = 0; + for (int i = 0; i < height; i++) + { + Console.Write(""|""); + for (int f = 0; f < width; f++) + { + if (f == Math.Abs(j)) + { + Console.Write(""*""); + } + else + { + Console.Write("" ""); + } + } + j++; + if (Math.Abs(j) == width - 1) + { + j *= -1; + } + Console.WriteLine(""|""); + } + } + +``` + +Probably going to get downvoted for giving you a complete answer, but maybe it'll show you one correct approach and you can learn something from it...","I see a + +``` +while (Height > 0) + +``` + +so your infinite loop is coming from Height never getting less or equal to 0." +6763429,"i want to write a shape with "" \* "" and "" | "" the shape is below. +The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5 + +``` + +|*____| +|_*___| +|__*__| +|___*_| +|____*| +|___*_| +|__*__| +|_*___| +|*____| +|_*___| + +``` + +``` + private static void Function() + { + int height, width; + + if (width == 2) + while (height > 0) + { + FirstPart(width, height); + height -= width; + } + else + while (height > 0) + { + if (height > 1) + { + FirstPart(width, height); + height -= width; + } + if (height > 0) + { + SecondPart(width, height); + height -= width - 2; + } + } + } + + private static void FirstPart(int width,int height) + { + + if(height > width) + for (int i = 0; i < width; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + private static void SecondPart(int width,int height) + { + + if(height > width) + + for (int i = 0; i < width-2; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width-1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width - 1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + +```",2011/07/20,"['https://Stackoverflow.com/questions/6763429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/852118/']","I see a + +``` +while (Height > 0) + +``` + +so your infinite loop is coming from Height never getting less or equal to 0.","even shorter: + +``` +static void Variante_2(int height, int width) +{ + byte[][] arr = new byte[height][]; + int pos = 0; + int mov = 1; + for (int line = 0; line < height; line++) + { + arr[line] = new byte[width]; + for (int col = 0; col < width; col++) { arr[line][col] = 45; } + arr[line][pos] = 42; + pos += mov; + if (pos == 0 || pos == (width - 1)) { mov *= -1; } + Console.WriteLine(""|"" + ASCIIEncoding.ASCII.GetString(arr[line]) + ""|""); + } + string temp = Console.ReadLine(); +} + +```" +6763429,"i want to write a shape with "" \* "" and "" | "" the shape is below. +The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5 + +``` + +|*____| +|_*___| +|__*__| +|___*_| +|____*| +|___*_| +|__*__| +|_*___| +|*____| +|_*___| + +``` + +``` + private static void Function() + { + int height, width; + + if (width == 2) + while (height > 0) + { + FirstPart(width, height); + height -= width; + } + else + while (height > 0) + { + if (height > 1) + { + FirstPart(width, height); + height -= width; + } + if (height > 0) + { + SecondPart(width, height); + height -= width - 2; + } + } + } + + private static void FirstPart(int width,int height) + { + + if(height > width) + for (int i = 0; i < width; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + private static void SecondPart(int width,int height) + { + + if(height > width) + + for (int i = 0; i < width-2; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width-1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width - 1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + +```",2011/07/20,"['https://Stackoverflow.com/questions/6763429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/852118/']","I see a + +``` +while (Height > 0) + +``` + +so your infinite loop is coming from Height never getting less or equal to 0.","and it is possible to do it with less code: + +``` +static void Variante_3(int height, int width) +{ + int pos = 1; + int mov = 1; + for (int line = 0; line < height; line++) + { + Console.WriteLine(""|"" + ""*"".PadLeft(pos, '_') + ""|"".PadLeft(width - pos, '_')); + pos += mov; + if (pos == 1 || pos == (width - 1)) { mov *= -1; } + } + string temp = Console.ReadLine(); +} + +``` + +Sorry to all not doing others homework, but I couldn´t sleep without showing this *g*" +6763429,"i want to write a shape with "" \* "" and "" | "" the shape is below. +The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5 + +``` + +|*____| +|_*___| +|__*__| +|___*_| +|____*| +|___*_| +|__*__| +|_*___| +|*____| +|_*___| + +``` + +``` + private static void Function() + { + int height, width; + + if (width == 2) + while (height > 0) + { + FirstPart(width, height); + height -= width; + } + else + while (height > 0) + { + if (height > 1) + { + FirstPart(width, height); + height -= width; + } + if (height > 0) + { + SecondPart(width, height); + height -= width - 2; + } + } + } + + private static void FirstPart(int width,int height) + { + + if(height > width) + for (int i = 0; i < width; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + private static void SecondPart(int width,int height) + { + + if(height > width) + + for (int i = 0; i < width-2; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width-1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width - 1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + +```",2011/07/20,"['https://Stackoverflow.com/questions/6763429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/852118/']","``` + private static void WriteStars(int width, int height) + { + int j = 0; + for (int i = 0; i < height; i++) + { + Console.Write(""|""); + for (int f = 0; f < width; f++) + { + if (f == Math.Abs(j)) + { + Console.Write(""*""); + } + else + { + Console.Write("" ""); + } + } + j++; + if (Math.Abs(j) == width - 1) + { + j *= -1; + } + Console.WriteLine(""|""); + } + } + +``` + +Probably going to get downvoted for giving you a complete answer, but maybe it'll show you one correct approach and you can learn something from it...","It's better to rewrite. When you do, decouple the code into several functions so that one function draws a single line, and another one calls the former to draw all the lines." +6763429,"i want to write a shape with "" \* "" and "" | "" the shape is below. +The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5 + +``` + +|*____| +|_*___| +|__*__| +|___*_| +|____*| +|___*_| +|__*__| +|_*___| +|*____| +|_*___| + +``` + +``` + private static void Function() + { + int height, width; + + if (width == 2) + while (height > 0) + { + FirstPart(width, height); + height -= width; + } + else + while (height > 0) + { + if (height > 1) + { + FirstPart(width, height); + height -= width; + } + if (height > 0) + { + SecondPart(width, height); + height -= width - 2; + } + } + } + + private static void FirstPart(int width,int height) + { + + if(height > width) + for (int i = 0; i < width; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + private static void SecondPart(int width,int height) + { + + if(height > width) + + for (int i = 0; i < width-2; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width-1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width - 1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + +```",2011/07/20,"['https://Stackoverflow.com/questions/6763429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/852118/']","``` + private static void WriteStars(int width, int height) + { + int j = 0; + for (int i = 0; i < height; i++) + { + Console.Write(""|""); + for (int f = 0; f < width; f++) + { + if (f == Math.Abs(j)) + { + Console.Write(""*""); + } + else + { + Console.Write("" ""); + } + } + j++; + if (Math.Abs(j) == width - 1) + { + j *= -1; + } + Console.WriteLine(""|""); + } + } + +``` + +Probably going to get downvoted for giving you a complete answer, but maybe it'll show you one correct approach and you can learn something from it...","``` +void WriteStars(int Width,int Height) +{ + int _sp=1; //Star Pos + bool _left = false; + for(int i =0;i 0) + { + FirstPart(width, height); + height -= width; + } + else + while (height > 0) + { + if (height > 1) + { + FirstPart(width, height); + height -= width; + } + if (height > 0) + { + SecondPart(width, height); + height -= width - 2; + } + } + } + + private static void FirstPart(int width,int height) + { + + if(height > width) + for (int i = 0; i < width; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + private static void SecondPart(int width,int height) + { + + if(height > width) + + for (int i = 0; i < width-2; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width-1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width - 1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + +```",2011/07/20,"['https://Stackoverflow.com/questions/6763429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/852118/']","``` + private static void WriteStars(int width, int height) + { + int j = 0; + for (int i = 0; i < height; i++) + { + Console.Write(""|""); + for (int f = 0; f < width; f++) + { + if (f == Math.Abs(j)) + { + Console.Write(""*""); + } + else + { + Console.Write("" ""); + } + } + j++; + if (Math.Abs(j) == width - 1) + { + j *= -1; + } + Console.WriteLine(""|""); + } + } + +``` + +Probably going to get downvoted for giving you a complete answer, but maybe it'll show you one correct approach and you can learn something from it...","even shorter: + +``` +static void Variante_2(int height, int width) +{ + byte[][] arr = new byte[height][]; + int pos = 0; + int mov = 1; + for (int line = 0; line < height; line++) + { + arr[line] = new byte[width]; + for (int col = 0; col < width; col++) { arr[line][col] = 45; } + arr[line][pos] = 42; + pos += mov; + if (pos == 0 || pos == (width - 1)) { mov *= -1; } + Console.WriteLine(""|"" + ASCIIEncoding.ASCII.GetString(arr[line]) + ""|""); + } + string temp = Console.ReadLine(); +} + +```" +6763429,"i want to write a shape with "" \* "" and "" | "" the shape is below. +The program must take height and width from user.Width is column number without ' | '.I tried to write but confused.My code sometimes works great and sometimes being stupid.For example when i enter height : 13, width : 4 it writes one more,if witdh is 1 it enters infinite loop.While trying to solve it became too conflicted.Must i fix it or rewrite ? Here is the code : height =10, width = 5 + +``` + +|*____| +|_*___| +|__*__| +|___*_| +|____*| +|___*_| +|__*__| +|_*___| +|*____| +|_*___| + +``` + +``` + private static void Function() + { + int height, width; + + if (width == 2) + while (height > 0) + { + FirstPart(width, height); + height -= width; + } + else + while (height > 0) + { + if (height > 1) + { + FirstPart(width, height); + height -= width; + } + if (height > 0) + { + SecondPart(width, height); + height -= width - 2; + } + } + } + + private static void FirstPart(int width,int height) + { + + if(height > width) + for (int i = 0; i < width; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + 1 == j) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + private static void SecondPart(int width,int height) + { + + if(height > width) + + for (int i = 0; i < width-2; i++) + { + for (int j = 0; j < width+2; j++) + { + + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width-1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + else + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width + 2; j++) + { + if (j == 0 || j == width + 1) + Console.Write(""|""); + else + if (i + j == width - 1) + Console.Write(""*""); + else + Console.Write("" ""); + } + Console.WriteLine(); + } + } + +```",2011/07/20,"['https://Stackoverflow.com/questions/6763429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/852118/']","``` + private static void WriteStars(int width, int height) + { + int j = 0; + for (int i = 0; i < height; i++) + { + Console.Write(""|""); + for (int f = 0; f < width; f++) + { + if (f == Math.Abs(j)) + { + Console.Write(""*""); + } + else + { + Console.Write("" ""); + } + } + j++; + if (Math.Abs(j) == width - 1) + { + j *= -1; + } + Console.WriteLine(""|""); + } + } + +``` + +Probably going to get downvoted for giving you a complete answer, but maybe it'll show you one correct approach and you can learn something from it...","and it is possible to do it with less code: + +``` +static void Variante_3(int height, int width) +{ + int pos = 1; + int mov = 1; + for (int line = 0; line < height; line++) + { + Console.WriteLine(""|"" + ""*"".PadLeft(pos, '_') + ""|"".PadLeft(width - pos, '_')); + pos += mov; + if (pos == 1 || pos == (width - 1)) { mov *= -1; } + } + string temp = Console.ReadLine(); +} + +``` + +Sorry to all not doing others homework, but I couldn´t sleep without showing this *g*" +62851314,"Let me explain what is happening: + +* Database: Oracle 19c +* Apex: 19.1.0.00.15 +* ORDS standalone is 19.1.0.r0921545 + +I did the tasks to configure an Apex Social Sign In to Microsoft AAD without almost any issue: + +* I created the authentication method in Apex. +* I register my application and get the web credentials in Azure. +* I created a wallet in my database with the root CA Microsoft certificates and configured the instance settings to usee that wallet. +* My wallet in the database server contains the property auto\_login to avoid using passwords. +* I created the ACEs entries to allow connection to the login.microsoftonline.com in the port 443 +* Although it is not important for the purpose of the question itself and the error that is producing, just comment that I configured the wallet settings in the internal workspace in order to provide access to the wallet to the apex applications. + +For some weeks the process was working fine, I was having a perfect Single Sing on mechanism for all my apex applications in the different workspaces. However, since some days ago, I am getting always the same error: + +**ORA-29024: Certificate validation failure** + +After some digging I realise that someone has configured a PROXY for outgoing traffic. Before even trying in Apex, I tried in SQL using APEX\_WEB\_SERVICE + +Request with proxy settings to login.microsoftonline.com + +``` +select apex_web_service.make_rest_request( + p_url => 'https://login.microsoftonline.com', + p_http_method => 'GET', + p_wallet_path => 'file:/home/oracle/wallet', + p_wallet_pwd => 'MyPassword' , + p_proxy_override => 'http://myproxy:myport' + 7 ) from dual; +ERROR: +ORA-29273: HTTP request failed +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1035 +ORA-29024: Certificate validation failure +ORA-06512: at ""SYS.UTL_HTTP"", line 380 +ORA-06512: at ""SYS.UTL_HTTP"", line 1148 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 934 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1580 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEBSERVICES_API"", line 408 +ORA-06512: at line 1 + +``` + +Request without proxy settings, just to see if I can get there + +``` +SQL> select apex_web_service.make_rest_request( + 2 p_url => 'https://login.microsoftonline.com', + 3 p_http_method => 'GET', + 4 p_wallet_path => 'file:/home/oracle/wallet' + 5* ) from dual +SQL> / +ERROR: +ORA-29273: HTTP request failed +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1035 +ORA-29024: Certificate validation failure +ORA-06512: at ""SYS.UTL_HTTP"", line 380 +ORA-06512: at ""SYS.UTL_HTTP"", line 1148 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 934 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1580 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEBSERVICES_API"", line 408 +ORA-06512: at line 1 + +``` + +Request to google using Proxy settings + +``` +select apex_web_service.make_rest_request( + p_url => 'https://google.com', + p_http_method => 'GET', + p_wallet_path => 'file:/home/oracle/wallet', + p_wallet_pwd => 'MyPassword' , + 6 p_proxy_override => 'http://myproxy:myport' + 7 ) from dual ; +ERROR: +ORA-29273: HTTP request failed +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1035 +ORA-29024: Certificate validation failure +ORA-06512: at ""SYS.UTL_HTTP"", line 380 +ORA-06512: at ""SYS.UTL_HTTP"", line 1148 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 934 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1580 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEBSERVICES_API"", line 408 +ORA-06512: at line 1 + +``` + +Request to google without proxy settings + +``` +SQL> select apex_web_service.make_rest_request( + 2 p_url => 'https://google.com', + 3 p_http_method => 'GET', + 4 p_wallet_path => 'file:/home/oracle/wallet' + 5* ) from dual +SQL> / +ERROR: +ORA-29273: HTTP request failed +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1035 +ORA-12535: TNS:operation timed out +ORA-06512: at ""SYS.UTL_HTTP"", line 380 +ORA-06512: at ""SYS.UTL_HTTP"", line 1148 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 934 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1580 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEBSERVICES_API"", line 408 +ORA-06512: at line 1 + +``` + +My questions are the following: + +* It is a network problem or a proxy issue regarding inbound/outbound +traffic ? I can reach Microsoft but not Google in the port 443 when I don't specify proxy. +* Why am I getting invalid certificate when it has nothing to do with +the certificates ? +* How can I setup my APEX to use authentication on Azure or any other +provider for that matter when I have a proxy in the middle ? +* As I use ORDS standalone, am I allow to keep using it or I need a +reverse proxy with Tomcat ? + +I tried to configure the ACE to use HTTP\_PROXY in the ports by running + +``` +begin + sys.dbms_network_acl_admin.append_host_ace( + host => 'myproxyserver' + ,lower_port => 8080 + ,upper_port => 8080 + ,ace => xs$ace_type( + privilege_list => xs$name_list('http_proxy') + ,granted => true + ,principal_name => 'MY_PRINCIPAL' + ,principal_type => XS_ACL.PTYPE_DB + ) + ); +end; +/ + +``` + +Even I grant to the ACE privileges over the wallet + +``` +SET SERVEROUTPUT ON +BEGIN + DBMS_NETWORK_ACL_ADMIN.APPEND_WALLET_ACE + ( + WALLET_PATH => 'file:/home/oracle/wallet', + ACE => XS$ACE_TYPE( + PRIVILEGE_LIST => XS$NAME_LIST('use_passwords','use_client_certificates'), + PRINCIPAL_NAME => 'MY_PRINCIPAL', + PRINCIPAL_TYPE => XS_ACL.PTYPE_DB + ) + ); +EXCEPTION WHEN OTHERS THEN + DBMS_OUTPUT.PUT_LINE('Error while configuring ACL for wallet: '|| SQLERRM); +END; +/ + +``` + +but I am still getting the same error all over. + +Any help would be appreciated! +Thank you",2020/07/11,"['https://Stackoverflow.com/questions/62851314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13755538/']","I had issue like this, it seems Oracle SSL library has some bugs. Finally I implemented some Java Source for OJVM, please read my answer here: ","In my understanding,you will need to do following(in addition to what you did) : + +1. login to Apex as administrator +2. From settings, go to 'Wallet' +3. Add Wallet path(absolute path with prefix 'file://' and password you used for creating wallet + +Now, your problem should be solved." +62851314,"Let me explain what is happening: + +* Database: Oracle 19c +* Apex: 19.1.0.00.15 +* ORDS standalone is 19.1.0.r0921545 + +I did the tasks to configure an Apex Social Sign In to Microsoft AAD without almost any issue: + +* I created the authentication method in Apex. +* I register my application and get the web credentials in Azure. +* I created a wallet in my database with the root CA Microsoft certificates and configured the instance settings to usee that wallet. +* My wallet in the database server contains the property auto\_login to avoid using passwords. +* I created the ACEs entries to allow connection to the login.microsoftonline.com in the port 443 +* Although it is not important for the purpose of the question itself and the error that is producing, just comment that I configured the wallet settings in the internal workspace in order to provide access to the wallet to the apex applications. + +For some weeks the process was working fine, I was having a perfect Single Sing on mechanism for all my apex applications in the different workspaces. However, since some days ago, I am getting always the same error: + +**ORA-29024: Certificate validation failure** + +After some digging I realise that someone has configured a PROXY for outgoing traffic. Before even trying in Apex, I tried in SQL using APEX\_WEB\_SERVICE + +Request with proxy settings to login.microsoftonline.com + +``` +select apex_web_service.make_rest_request( + p_url => 'https://login.microsoftonline.com', + p_http_method => 'GET', + p_wallet_path => 'file:/home/oracle/wallet', + p_wallet_pwd => 'MyPassword' , + p_proxy_override => 'http://myproxy:myport' + 7 ) from dual; +ERROR: +ORA-29273: HTTP request failed +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1035 +ORA-29024: Certificate validation failure +ORA-06512: at ""SYS.UTL_HTTP"", line 380 +ORA-06512: at ""SYS.UTL_HTTP"", line 1148 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 934 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1580 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEBSERVICES_API"", line 408 +ORA-06512: at line 1 + +``` + +Request without proxy settings, just to see if I can get there + +``` +SQL> select apex_web_service.make_rest_request( + 2 p_url => 'https://login.microsoftonline.com', + 3 p_http_method => 'GET', + 4 p_wallet_path => 'file:/home/oracle/wallet' + 5* ) from dual +SQL> / +ERROR: +ORA-29273: HTTP request failed +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1035 +ORA-29024: Certificate validation failure +ORA-06512: at ""SYS.UTL_HTTP"", line 380 +ORA-06512: at ""SYS.UTL_HTTP"", line 1148 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 934 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1580 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEBSERVICES_API"", line 408 +ORA-06512: at line 1 + +``` + +Request to google using Proxy settings + +``` +select apex_web_service.make_rest_request( + p_url => 'https://google.com', + p_http_method => 'GET', + p_wallet_path => 'file:/home/oracle/wallet', + p_wallet_pwd => 'MyPassword' , + 6 p_proxy_override => 'http://myproxy:myport' + 7 ) from dual ; +ERROR: +ORA-29273: HTTP request failed +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1035 +ORA-29024: Certificate validation failure +ORA-06512: at ""SYS.UTL_HTTP"", line 380 +ORA-06512: at ""SYS.UTL_HTTP"", line 1148 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 934 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1580 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEBSERVICES_API"", line 408 +ORA-06512: at line 1 + +``` + +Request to google without proxy settings + +``` +SQL> select apex_web_service.make_rest_request( + 2 p_url => 'https://google.com', + 3 p_http_method => 'GET', + 4 p_wallet_path => 'file:/home/oracle/wallet' + 5* ) from dual +SQL> / +ERROR: +ORA-29273: HTTP request failed +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1035 +ORA-12535: TNS:operation timed out +ORA-06512: at ""SYS.UTL_HTTP"", line 380 +ORA-06512: at ""SYS.UTL_HTTP"", line 1148 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 934 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1580 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEBSERVICES_API"", line 408 +ORA-06512: at line 1 + +``` + +My questions are the following: + +* It is a network problem or a proxy issue regarding inbound/outbound +traffic ? I can reach Microsoft but not Google in the port 443 when I don't specify proxy. +* Why am I getting invalid certificate when it has nothing to do with +the certificates ? +* How can I setup my APEX to use authentication on Azure or any other +provider for that matter when I have a proxy in the middle ? +* As I use ORDS standalone, am I allow to keep using it or I need a +reverse proxy with Tomcat ? + +I tried to configure the ACE to use HTTP\_PROXY in the ports by running + +``` +begin + sys.dbms_network_acl_admin.append_host_ace( + host => 'myproxyserver' + ,lower_port => 8080 + ,upper_port => 8080 + ,ace => xs$ace_type( + privilege_list => xs$name_list('http_proxy') + ,granted => true + ,principal_name => 'MY_PRINCIPAL' + ,principal_type => XS_ACL.PTYPE_DB + ) + ); +end; +/ + +``` + +Even I grant to the ACE privileges over the wallet + +``` +SET SERVEROUTPUT ON +BEGIN + DBMS_NETWORK_ACL_ADMIN.APPEND_WALLET_ACE + ( + WALLET_PATH => 'file:/home/oracle/wallet', + ACE => XS$ACE_TYPE( + PRIVILEGE_LIST => XS$NAME_LIST('use_passwords','use_client_certificates'), + PRINCIPAL_NAME => 'MY_PRINCIPAL', + PRINCIPAL_TYPE => XS_ACL.PTYPE_DB + ) + ); +EXCEPTION WHEN OTHERS THEN + DBMS_OUTPUT.PUT_LINE('Error while configuring ACL for wallet: '|| SQLERRM); +END; +/ + +``` + +but I am still getting the same error all over. + +Any help would be appreciated! +Thank you",2020/07/11,"['https://Stackoverflow.com/questions/62851314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13755538/']","Thank you to all who post answers, but finally, after struggling for a while, I found the root cause. Actually Oracle was right after all, as Microsoft has changed the way the authentication is handled, either you are using Oauth2 or OpenID, when you use Office365 and Azure Active Directory. + +In this case, my organisation is using Office 365 and at the beginning was enough with importing the PKI certificates from : + + + +After a change done in Azure Active Directory (AAD), you now need also the Global Sign certificates from [office.com](http://office.com) + +I hope it clarifies to other users who got in the same problem trying to authenticate with Azure Active Directory using Apex Social sign in. + +You can download the certificates directly from office365.com + +[![enter image description here](https://i.stack.imgur.com/zkbq2.png)](https://i.stack.imgur.com/zkbq2.png) + +After adding the new two certificates to the wallet, you can now enter without issues: + +``` +select apex_web_service.make_rest_request( + p_url => 'https://login.microsoftonline.com', + p_http_method => 'GET', + 4 p_wallet_path => 'file:/home/oracle/wallet' ) from dual ; + +APEX_WEB_SERVICE.MAKE_REST_REQUEST(P_URL=>'HTTPS://LOGIN.MICROSOFTONLINE.COM',P_ +-------------------------------------------------------------------------------- + + + + +```","In my understanding,you will need to do following(in addition to what you did) : + +1. login to Apex as administrator +2. From settings, go to 'Wallet' +3. Add Wallet path(absolute path with prefix 'file://' and password you used for creating wallet + +Now, your problem should be solved." +62851314,"Let me explain what is happening: + +* Database: Oracle 19c +* Apex: 19.1.0.00.15 +* ORDS standalone is 19.1.0.r0921545 + +I did the tasks to configure an Apex Social Sign In to Microsoft AAD without almost any issue: + +* I created the authentication method in Apex. +* I register my application and get the web credentials in Azure. +* I created a wallet in my database with the root CA Microsoft certificates and configured the instance settings to usee that wallet. +* My wallet in the database server contains the property auto\_login to avoid using passwords. +* I created the ACEs entries to allow connection to the login.microsoftonline.com in the port 443 +* Although it is not important for the purpose of the question itself and the error that is producing, just comment that I configured the wallet settings in the internal workspace in order to provide access to the wallet to the apex applications. + +For some weeks the process was working fine, I was having a perfect Single Sing on mechanism for all my apex applications in the different workspaces. However, since some days ago, I am getting always the same error: + +**ORA-29024: Certificate validation failure** + +After some digging I realise that someone has configured a PROXY for outgoing traffic. Before even trying in Apex, I tried in SQL using APEX\_WEB\_SERVICE + +Request with proxy settings to login.microsoftonline.com + +``` +select apex_web_service.make_rest_request( + p_url => 'https://login.microsoftonline.com', + p_http_method => 'GET', + p_wallet_path => 'file:/home/oracle/wallet', + p_wallet_pwd => 'MyPassword' , + p_proxy_override => 'http://myproxy:myport' + 7 ) from dual; +ERROR: +ORA-29273: HTTP request failed +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1035 +ORA-29024: Certificate validation failure +ORA-06512: at ""SYS.UTL_HTTP"", line 380 +ORA-06512: at ""SYS.UTL_HTTP"", line 1148 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 934 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1580 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEBSERVICES_API"", line 408 +ORA-06512: at line 1 + +``` + +Request without proxy settings, just to see if I can get there + +``` +SQL> select apex_web_service.make_rest_request( + 2 p_url => 'https://login.microsoftonline.com', + 3 p_http_method => 'GET', + 4 p_wallet_path => 'file:/home/oracle/wallet' + 5* ) from dual +SQL> / +ERROR: +ORA-29273: HTTP request failed +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1035 +ORA-29024: Certificate validation failure +ORA-06512: at ""SYS.UTL_HTTP"", line 380 +ORA-06512: at ""SYS.UTL_HTTP"", line 1148 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 934 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1580 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEBSERVICES_API"", line 408 +ORA-06512: at line 1 + +``` + +Request to google using Proxy settings + +``` +select apex_web_service.make_rest_request( + p_url => 'https://google.com', + p_http_method => 'GET', + p_wallet_path => 'file:/home/oracle/wallet', + p_wallet_pwd => 'MyPassword' , + 6 p_proxy_override => 'http://myproxy:myport' + 7 ) from dual ; +ERROR: +ORA-29273: HTTP request failed +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1035 +ORA-29024: Certificate validation failure +ORA-06512: at ""SYS.UTL_HTTP"", line 380 +ORA-06512: at ""SYS.UTL_HTTP"", line 1148 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 934 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1580 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEBSERVICES_API"", line 408 +ORA-06512: at line 1 + +``` + +Request to google without proxy settings + +``` +SQL> select apex_web_service.make_rest_request( + 2 p_url => 'https://google.com', + 3 p_http_method => 'GET', + 4 p_wallet_path => 'file:/home/oracle/wallet' + 5* ) from dual +SQL> / +ERROR: +ORA-29273: HTTP request failed +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1035 +ORA-12535: TNS:operation timed out +ORA-06512: at ""SYS.UTL_HTTP"", line 380 +ORA-06512: at ""SYS.UTL_HTTP"", line 1148 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 934 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEB_SERVICES"", line 1580 +ORA-06512: at ""APEX_190100.WWV_FLOW_WEBSERVICES_API"", line 408 +ORA-06512: at line 1 + +``` + +My questions are the following: + +* It is a network problem or a proxy issue regarding inbound/outbound +traffic ? I can reach Microsoft but not Google in the port 443 when I don't specify proxy. +* Why am I getting invalid certificate when it has nothing to do with +the certificates ? +* How can I setup my APEX to use authentication on Azure or any other +provider for that matter when I have a proxy in the middle ? +* As I use ORDS standalone, am I allow to keep using it or I need a +reverse proxy with Tomcat ? + +I tried to configure the ACE to use HTTP\_PROXY in the ports by running + +``` +begin + sys.dbms_network_acl_admin.append_host_ace( + host => 'myproxyserver' + ,lower_port => 8080 + ,upper_port => 8080 + ,ace => xs$ace_type( + privilege_list => xs$name_list('http_proxy') + ,granted => true + ,principal_name => 'MY_PRINCIPAL' + ,principal_type => XS_ACL.PTYPE_DB + ) + ); +end; +/ + +``` + +Even I grant to the ACE privileges over the wallet + +``` +SET SERVEROUTPUT ON +BEGIN + DBMS_NETWORK_ACL_ADMIN.APPEND_WALLET_ACE + ( + WALLET_PATH => 'file:/home/oracle/wallet', + ACE => XS$ACE_TYPE( + PRIVILEGE_LIST => XS$NAME_LIST('use_passwords','use_client_certificates'), + PRINCIPAL_NAME => 'MY_PRINCIPAL', + PRINCIPAL_TYPE => XS_ACL.PTYPE_DB + ) + ); +EXCEPTION WHEN OTHERS THEN + DBMS_OUTPUT.PUT_LINE('Error while configuring ACL for wallet: '|| SQLERRM); +END; +/ + +``` + +but I am still getting the same error all over. + +Any help would be appreciated! +Thank you",2020/07/11,"['https://Stackoverflow.com/questions/62851314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13755538/']","Thank you to all who post answers, but finally, after struggling for a while, I found the root cause. Actually Oracle was right after all, as Microsoft has changed the way the authentication is handled, either you are using Oauth2 or OpenID, when you use Office365 and Azure Active Directory. + +In this case, my organisation is using Office 365 and at the beginning was enough with importing the PKI certificates from : + + + +After a change done in Azure Active Directory (AAD), you now need also the Global Sign certificates from [office.com](http://office.com) + +I hope it clarifies to other users who got in the same problem trying to authenticate with Azure Active Directory using Apex Social sign in. + +You can download the certificates directly from office365.com + +[![enter image description here](https://i.stack.imgur.com/zkbq2.png)](https://i.stack.imgur.com/zkbq2.png) + +After adding the new two certificates to the wallet, you can now enter without issues: + +``` +select apex_web_service.make_rest_request( + p_url => 'https://login.microsoftonline.com', + p_http_method => 'GET', + 4 p_wallet_path => 'file:/home/oracle/wallet' ) from dual ; + +APEX_WEB_SERVICE.MAKE_REST_REQUEST(P_URL=>'HTTPS://LOGIN.MICROSOFTONLINE.COM',P_ +-------------------------------------------------------------------------------- + + + + +```","I had issue like this, it seems Oracle SSL library has some bugs. Finally I implemented some Java Source for OJVM, please read my answer here: " +20576864,"I am using Omniauth in a Rails application for login, my omniauth.rb, is as show below: + +``` +OmniAuth.config.logger = Rails.logger + +Rails.application.config.middleware.use OmniAuth::Builder do + provider :facebook, 'xxxxxxx', 'xxxxxxx' + provider :google_oauth2, 'xxxxxxxxx','xxxxxxxx' +end + +``` + +When a user attempts to login (via Facebook or Goolge) and denies permissions, get the following error: + +``` + OmniAuth::Strategies::OAuth2::CallbackError + +``` + +with this parameters: + +``` +{""error""=>""access_denied"", + ""error_code""=>""200"", + ""error_description""=>""Permissions error"", + ""error_reason""=>""user_denied"", + ""state""=>""60daee5f78d9cc28972050ae8ca8f950bb4ed5958302bcea""} + +``` + +if the user accept, no problem and everything works fine. + +I've tried some of the possible solutions related with this error, and listed on this website, but none solved my problem. For example: + +[How to rescue OmniAuth::Strategies::OAuth2::CallbackError?](https://stackoverflow.com/questions/10737200/how-to-rescue-omniauthstrategiesoauth2callbackerror) + +[Omniauth+facebook error when trying to cancel the popup](https://stackoverflow.com/questions/10647642/omniauthfacebook-error-when-trying-to-cancel-the-popup) + +Please, I need help to solve this problem.",2013/12/13,"['https://Stackoverflow.com/questions/20576864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3100897/']","Our old friend `strace` solves this mystery. + +In the `fflush(""cat"")` case, awk quickly writes all three values while cat is still loading. When cat finishes loading, it reads all three values in sequence and writes them out at the same time. + +In the case of `close(""cat"")`, awk waits for the process to exit, at which point cat is guaranteed to have read the value, written it, and exited. + +I increased the numbers in the `fflush` case from 3 to 1000, and now `awk` reaches 120 before cat catches up, and from there on it works basically as you expect. It prints ""1,2,..,120,1,2,...,120,121,121,122,122,123,123,..."". + +Note that you're not guaranteed to see numbers in perfect pairs. awk blocks until the number has been written to the pipe, but it doesn't wait for cat to do anything with it.","Not really something I have much experience of but the gawk manual tells us: + +> +> fflush([filename]) +> Flush any buffered output associated with filename, +> which is either a file opened for writing or a shell command for +> redirecting output **to a pipe** or coprocess. +> +> +> + +Note that ""cat"" as used above is in none of the contexts the gawk manual says are affected by fflush(). + +The same manual for close() on the other hand says: + +> +> close(filename [, how]) +> Close the file filename for input or output. +> Alternatively, the argument may be a shell command that was used for +> creating a coprocess, or for redirecting **to or from a pipe**; then +> the coprocess or pipe is closed. +> +> +> + +Note that the context in which you're using cat is redirecting **from** a pipe and so is included in the list of items affected by close() but not by fflush()." +946937,"I bought a Dell Studio XPS 8100 desktop back in 2010, which had Windows 7 installed and came with a partition for Dell Factory Restore. + +After having installed Windows 10, what happened to that partition? Did the installation get rid of it? If not and I were to use it to do a Dell Factory Restore, would it ""reinstall"" Windows 7? + +Sorry if this is a duplicate of a question somewhere, I didn't see one exactly like this asking about Windows 10 upgrade and Dell's Recovery partition.",2015/07/29,"['https://superuser.com/questions/946937', 'https://superuser.com', 'https://superuser.com/users/474857/']","The recovery partition will not be touched nor upgraded during this process. If you did a factory restore, you would end up with Windows 7.","If you run into a problem where you cannot access your recovery partition, or the partition is deleted, you can run a tool called DSRFIX and it should restore the recovery partition." +946937,"I bought a Dell Studio XPS 8100 desktop back in 2010, which had Windows 7 installed and came with a partition for Dell Factory Restore. + +After having installed Windows 10, what happened to that partition? Did the installation get rid of it? If not and I were to use it to do a Dell Factory Restore, would it ""reinstall"" Windows 7? + +Sorry if this is a duplicate of a question somewhere, I didn't see one exactly like this asking about Windows 10 upgrade and Dell's Recovery partition.",2015/07/29,"['https://superuser.com/questions/946937', 'https://superuser.com', 'https://superuser.com/users/474857/']","From what I am seeing, if there is not a system partition on the drive, only the Dell recovery partition & OS partition, then Windows 10 will alter the boot folder of that partition. This effects the PE recovery environment & will break the factory recovery. Even after reapplying the Factory.wim of windows 7 and it blue screens, Windows 10 PE recovery environment will start & not help with the start up issues. I'm presently trying to undo all of this on a Dell Inspiron laptop at present. + +I don't think this will happen if there is a 100MB system partition on the drive as this is where the Windows 10 recovery environment will install (in the boot folder). Thus leaving the Dell Recovery partition untouched leaving the F11 function in tact to be able to factory install the OS that shipped with the laptop. Isn't the digital life wonderful!!!","If you run into a problem where you cannot access your recovery partition, or the partition is deleted, you can run a tool called DSRFIX and it should restore the recovery partition." +418342,"I know I can pass parameters to java to limit the amount of memory used, but that doesn't change the application behavior. (assuming I will get an out of memory exception or similar) + +I would like to limit the amount of memory that solr uses. I am assuming it is as simple as setting a single configuration option, but googling so far has been fruitless. + +Any ideas? Thanks! + +Edit: I just want to note that I understand there will be a tradeoff between memory usage and execution speed. In this case, I am willing to sacrifice speed to reduce memory footprint. I also understand that it is possible that solr does not support the option of tuning this tradeoff.",2012/08/16,"['https://serverfault.com/questions/418342', 'https://serverfault.com', 'https://serverfault.com/users/107102/']","Check out this article, it should address your needs + + + +and like Joe said, yes you can use groups for computers as well","Yes, you can use a security group populated with computer accounts to filter Group Policy." +29743729,"I am using video.js () to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks. + +I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it. + +When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play. + +If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started. + +Can anyone help me to find the position in the video where the seek begins? + +If this is not possible, I'd settle for a way to disable seeking during playback. + +EDIT: adding code as requested. It's pretty simple: + +``` +var trackedPlayer = videojs('pvp-player'); + +trackedPlayer.on(""play"", function (e) { + console.log(""Video playback started: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""pause"", function (e) { + console.log(""Video playback paused: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeking"", function (e) { + console.log(""Video seeking: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeked"", function (e) { + console.log(""Video seek ended: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""ended"", function (e) { + console.log(""Video playback ended.""); +}); + +``` + +If I can get all the tracking I want I will replace console.log with ajax calls to store the data.",2015/04/20,"['https://Stackoverflow.com/questions/29743729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664914/']","You can listen to `timeupdate` und take the next to last value you got there before `seeking` is called as your source: + +``` +var previousTime = 0; +var currentTime = 0; +trackedPlayer.on('timeupdate', function() { + previousTime = currentTime; + currentTime = trackedPlayer.currentTime(); +}); +trackedPlayer.on('seeking', function() { + console.log('seeking from', previousTime, 'to', currentTime, '; delta:', currentTime - previousTime); +}); + +``` + +This seems to work with the HTML5 tech. I have not tested with other techs. + +There is, however, one glitch: the first time seeking a *paused* player yields only a small delta (and the almost-same previous value for both variables). But this shouldn’t matter much since the delta is only a few hundred milliseconds (and I gather you’re only interested in the “from” value). + +**Update** + +`seeked` is triggered far more infrequently than `seeking`. Try the following. + +``` +var previousTime = 0; +var currentTime = 0; +var seekStart = null; +trackedPlayer.on('timeupdate', function() { + previousTime = currentTime; + currentTime = trackedPlayer.currentTime(); +}); +trackedPlayer.on('seeking', function() { + if(seekStart === null) { + seekStart = previousTime; + } +}); +trackedPlayer.on('seeked', function() { + console.log('seeked from', seekStart, 'to', currentTime, '; delta:', currentTime - previousTime); + seekStart = null; +}); + +``` + +There are also many libraries for debouncing function calls (in this case the call to your backend).","Try with this code to know the length of video. + +``` +var duration = document.getElementById(""duration""); +var vid_duration = Math.round(document.getElementById(""video"").duration); + //alert(vid_duration); +duration.innerHTML = vid_duration; + //duration.firstChild.nodeValue = vid_duration; + +```" +29743729,"I am using video.js () to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks. + +I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it. + +When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play. + +If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started. + +Can anyone help me to find the position in the video where the seek begins? + +If this is not possible, I'd settle for a way to disable seeking during playback. + +EDIT: adding code as requested. It's pretty simple: + +``` +var trackedPlayer = videojs('pvp-player'); + +trackedPlayer.on(""play"", function (e) { + console.log(""Video playback started: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""pause"", function (e) { + console.log(""Video playback paused: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeking"", function (e) { + console.log(""Video seeking: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeked"", function (e) { + console.log(""Video seek ended: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""ended"", function (e) { + console.log(""Video playback ended.""); +}); + +``` + +If I can get all the tracking I want I will replace console.log with ajax calls to store the data.",2015/04/20,"['https://Stackoverflow.com/questions/29743729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664914/']","I needed to find the same value for a project I was working on so I could determine whether or not a user was skipping forward or backward in a videojs player. + +Initially, I thought to save the currentTime() a user was seeking **from** on **timeupdate** then immediately removing my timeupdate listener once **seeking** was dispatched. While this worked in some browsers like Chrome, unfortunately, I found that other browsers continued to fire timeupdate more frequently and would continue to update the currentTime() I was saving after the player actually seeked. + +Here was the solution that ultimately worked across Safari/Chrome/Firefox. I have yet to test in IE. + +``` +var previousTime = 0, + currentTime = 0, + completeTime = 0, + position = 0; + +trackedPlayer.on('timeupdate', function() { + previousTime = currentTime; + currentTime = Math.floor(player.currentTime()); + + // save 'position' so long as time is moving forward with each update + if (previousTime < currentTime) { + position = previousTime; + previousTime = currentTime; + } +}); + +// when seeking starts +trackedPlayer.on('seeking', function() { + player.off('timeupdate', onTimeUpdate); + + player.one('seeked', onSeekComplete); +}); + +// when seeking completes +trackedPlayer.on('seeked', function() { + completeTime = Math.floor(player.currentTime()); + console.log(""User came from: "" + position); + console.log(""User ended at: "" + completeTime); +}); + +```","Try with this code to know the length of video. + +``` +var duration = document.getElementById(""duration""); +var vid_duration = Math.round(document.getElementById(""video"").duration); + //alert(vid_duration); +duration.innerHTML = vid_duration; + //duration.firstChild.nodeValue = vid_duration; + +```" +29743729,"I am using video.js () to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks. + +I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it. + +When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play. + +If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started. + +Can anyone help me to find the position in the video where the seek begins? + +If this is not possible, I'd settle for a way to disable seeking during playback. + +EDIT: adding code as requested. It's pretty simple: + +``` +var trackedPlayer = videojs('pvp-player'); + +trackedPlayer.on(""play"", function (e) { + console.log(""Video playback started: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""pause"", function (e) { + console.log(""Video playback paused: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeking"", function (e) { + console.log(""Video seeking: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeked"", function (e) { + console.log(""Video seek ended: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""ended"", function (e) { + console.log(""Video playback ended.""); +}); + +``` + +If I can get all the tracking I want I will replace console.log with ajax calls to store the data.",2015/04/20,"['https://Stackoverflow.com/questions/29743729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664914/']","I know this is an old post but this is the only solution that worked for me. + +``` +var counter = 0; +var beforeTimeChange = 0; + +function handleSeeking() { + var timeoutTime = 300; + var beforeCounter = counter + 1; + if (trackedPlayer.cache_.currentTime === trackedPlayer.duration()) { + return; + // when video starts over, calls seek + } + beforeTimeChange = beforeTimeChange || trackedPlayer.cache_.currentTime; + setTimeout(function() { + if (beforeCounter === counter) { + console.log('before seek', beforeTimeChange, '\nafter seek', trackedPlayer.currentTime() - (timeoutTime / 1000)); + counter = 0; + beforeTimeChange = 0; + } + }, timeoutTime); + counter++; +} + +trackedPlayer.on('seeking', handleSeeking); + +```","Try with this code to know the length of video. + +``` +var duration = document.getElementById(""duration""); +var vid_duration = Math.round(document.getElementById(""video"").duration); + //alert(vid_duration); +duration.innerHTML = vid_duration; + //duration.firstChild.nodeValue = vid_duration; + +```" +29743729,"I am using video.js () to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks. + +I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it. + +When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play. + +If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started. + +Can anyone help me to find the position in the video where the seek begins? + +If this is not possible, I'd settle for a way to disable seeking during playback. + +EDIT: adding code as requested. It's pretty simple: + +``` +var trackedPlayer = videojs('pvp-player'); + +trackedPlayer.on(""play"", function (e) { + console.log(""Video playback started: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""pause"", function (e) { + console.log(""Video playback paused: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeking"", function (e) { + console.log(""Video seeking: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeked"", function (e) { + console.log(""Video seek ended: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""ended"", function (e) { + console.log(""Video playback ended.""); +}); + +``` + +If I can get all the tracking I want I will replace console.log with ajax calls to store the data.",2015/04/20,"['https://Stackoverflow.com/questions/29743729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664914/']","For a more accurate solution, you can listen to the events that trigger the seek such as mousedown on progress bar, left key, right key etc., and get the current time from these events. +For example in version 7.10.2 you can do the following, + +``` +let seekStartTime; + +player.controlBar.progressControl.on('mousedown', () => seekStartTime = player.currentTime()); +player.controlBar.progressControl.seekBar.on('mousedown', () => seekStartTime = player.currentTime()); +player.on('keydown', (e) => { + if (e.key === ""ArrowLeft"" || e.key === ""ArrowRight"") { + seekStartTime = player.currentTime(); + } +}); + +console.log(seekStartTime); + +``` + +**Note 1:** There are two seperate mousedown event listeners for progress control and seek bar. This is because the video can be seeked by clicking outside the seek bar on the progress control as well. + +**Note 2:** Seeking using hotkey numbers does not pause the video. However, if necessary you can add those keydown listeners too.","Try with this code to know the length of video. + +``` +var duration = document.getElementById(""duration""); +var vid_duration = Math.round(document.getElementById(""video"").duration); + //alert(vid_duration); +duration.innerHTML = vid_duration; + //duration.firstChild.nodeValue = vid_duration; + +```" +29743729,"I am using video.js () to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks. + +I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it. + +When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play. + +If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started. + +Can anyone help me to find the position in the video where the seek begins? + +If this is not possible, I'd settle for a way to disable seeking during playback. + +EDIT: adding code as requested. It's pretty simple: + +``` +var trackedPlayer = videojs('pvp-player'); + +trackedPlayer.on(""play"", function (e) { + console.log(""Video playback started: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""pause"", function (e) { + console.log(""Video playback paused: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeking"", function (e) { + console.log(""Video seeking: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeked"", function (e) { + console.log(""Video seek ended: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""ended"", function (e) { + console.log(""Video playback ended.""); +}); + +``` + +If I can get all the tracking I want I will replace console.log with ajax calls to store the data.",2015/04/20,"['https://Stackoverflow.com/questions/29743729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664914/']","I needed to find the start and end of a seeking action in my project and I used @Motorcykey answer and it worked, but there was a small bug. when I tried to seek to a time before the current time while the player was paused, the `position` didn't get updated. so I added just one line and it fixed it. I've tried other solutions too but so far this was the best solution that I've found. Here's the code snippet on player 'seeked' + +``` +player.on('seeked', function () { + completeTime = Math.floor(player.currentTime()); + console.log(""User came from: "" + position); + console.log(""User ended at: "" + completeTime); + position= Math.floor(player.currentTime()) +}); + +```","Try with this code to know the length of video. + +``` +var duration = document.getElementById(""duration""); +var vid_duration = Math.round(document.getElementById(""video"").duration); + //alert(vid_duration); +duration.innerHTML = vid_duration; + //duration.firstChild.nodeValue = vid_duration; + +```" +29743729,"I am using video.js () to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks. + +I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it. + +When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play. + +If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started. + +Can anyone help me to find the position in the video where the seek begins? + +If this is not possible, I'd settle for a way to disable seeking during playback. + +EDIT: adding code as requested. It's pretty simple: + +``` +var trackedPlayer = videojs('pvp-player'); + +trackedPlayer.on(""play"", function (e) { + console.log(""Video playback started: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""pause"", function (e) { + console.log(""Video playback paused: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeking"", function (e) { + console.log(""Video seeking: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeked"", function (e) { + console.log(""Video seek ended: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""ended"", function (e) { + console.log(""Video playback ended.""); +}); + +``` + +If I can get all the tracking I want I will replace console.log with ajax calls to store the data.",2015/04/20,"['https://Stackoverflow.com/questions/29743729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664914/']","You can listen to `timeupdate` und take the next to last value you got there before `seeking` is called as your source: + +``` +var previousTime = 0; +var currentTime = 0; +trackedPlayer.on('timeupdate', function() { + previousTime = currentTime; + currentTime = trackedPlayer.currentTime(); +}); +trackedPlayer.on('seeking', function() { + console.log('seeking from', previousTime, 'to', currentTime, '; delta:', currentTime - previousTime); +}); + +``` + +This seems to work with the HTML5 tech. I have not tested with other techs. + +There is, however, one glitch: the first time seeking a *paused* player yields only a small delta (and the almost-same previous value for both variables). But this shouldn’t matter much since the delta is only a few hundred milliseconds (and I gather you’re only interested in the “from” value). + +**Update** + +`seeked` is triggered far more infrequently than `seeking`. Try the following. + +``` +var previousTime = 0; +var currentTime = 0; +var seekStart = null; +trackedPlayer.on('timeupdate', function() { + previousTime = currentTime; + currentTime = trackedPlayer.currentTime(); +}); +trackedPlayer.on('seeking', function() { + if(seekStart === null) { + seekStart = previousTime; + } +}); +trackedPlayer.on('seeked', function() { + console.log('seeked from', seekStart, 'to', currentTime, '; delta:', currentTime - previousTime); + seekStart = null; +}); + +``` + +There are also many libraries for debouncing function calls (in this case the call to your backend).","I needed to find the same value for a project I was working on so I could determine whether or not a user was skipping forward or backward in a videojs player. + +Initially, I thought to save the currentTime() a user was seeking **from** on **timeupdate** then immediately removing my timeupdate listener once **seeking** was dispatched. While this worked in some browsers like Chrome, unfortunately, I found that other browsers continued to fire timeupdate more frequently and would continue to update the currentTime() I was saving after the player actually seeked. + +Here was the solution that ultimately worked across Safari/Chrome/Firefox. I have yet to test in IE. + +``` +var previousTime = 0, + currentTime = 0, + completeTime = 0, + position = 0; + +trackedPlayer.on('timeupdate', function() { + previousTime = currentTime; + currentTime = Math.floor(player.currentTime()); + + // save 'position' so long as time is moving forward with each update + if (previousTime < currentTime) { + position = previousTime; + previousTime = currentTime; + } +}); + +// when seeking starts +trackedPlayer.on('seeking', function() { + player.off('timeupdate', onTimeUpdate); + + player.one('seeked', onSeekComplete); +}); + +// when seeking completes +trackedPlayer.on('seeked', function() { + completeTime = Math.floor(player.currentTime()); + console.log(""User came from: "" + position); + console.log(""User ended at: "" + completeTime); +}); + +```" +29743729,"I am using video.js () to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks. + +I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it. + +When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play. + +If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started. + +Can anyone help me to find the position in the video where the seek begins? + +If this is not possible, I'd settle for a way to disable seeking during playback. + +EDIT: adding code as requested. It's pretty simple: + +``` +var trackedPlayer = videojs('pvp-player'); + +trackedPlayer.on(""play"", function (e) { + console.log(""Video playback started: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""pause"", function (e) { + console.log(""Video playback paused: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeking"", function (e) { + console.log(""Video seeking: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeked"", function (e) { + console.log(""Video seek ended: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""ended"", function (e) { + console.log(""Video playback ended.""); +}); + +``` + +If I can get all the tracking I want I will replace console.log with ajax calls to store the data.",2015/04/20,"['https://Stackoverflow.com/questions/29743729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664914/']","You can listen to `timeupdate` und take the next to last value you got there before `seeking` is called as your source: + +``` +var previousTime = 0; +var currentTime = 0; +trackedPlayer.on('timeupdate', function() { + previousTime = currentTime; + currentTime = trackedPlayer.currentTime(); +}); +trackedPlayer.on('seeking', function() { + console.log('seeking from', previousTime, 'to', currentTime, '; delta:', currentTime - previousTime); +}); + +``` + +This seems to work with the HTML5 tech. I have not tested with other techs. + +There is, however, one glitch: the first time seeking a *paused* player yields only a small delta (and the almost-same previous value for both variables). But this shouldn’t matter much since the delta is only a few hundred milliseconds (and I gather you’re only interested in the “from” value). + +**Update** + +`seeked` is triggered far more infrequently than `seeking`. Try the following. + +``` +var previousTime = 0; +var currentTime = 0; +var seekStart = null; +trackedPlayer.on('timeupdate', function() { + previousTime = currentTime; + currentTime = trackedPlayer.currentTime(); +}); +trackedPlayer.on('seeking', function() { + if(seekStart === null) { + seekStart = previousTime; + } +}); +trackedPlayer.on('seeked', function() { + console.log('seeked from', seekStart, 'to', currentTime, '; delta:', currentTime - previousTime); + seekStart = null; +}); + +``` + +There are also many libraries for debouncing function calls (in this case the call to your backend).","I know this is an old post but this is the only solution that worked for me. + +``` +var counter = 0; +var beforeTimeChange = 0; + +function handleSeeking() { + var timeoutTime = 300; + var beforeCounter = counter + 1; + if (trackedPlayer.cache_.currentTime === trackedPlayer.duration()) { + return; + // when video starts over, calls seek + } + beforeTimeChange = beforeTimeChange || trackedPlayer.cache_.currentTime; + setTimeout(function() { + if (beforeCounter === counter) { + console.log('before seek', beforeTimeChange, '\nafter seek', trackedPlayer.currentTime() - (timeoutTime / 1000)); + counter = 0; + beforeTimeChange = 0; + } + }, timeoutTime); + counter++; +} + +trackedPlayer.on('seeking', handleSeeking); + +```" +29743729,"I am using video.js () to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks. + +I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it. + +When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play. + +If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started. + +Can anyone help me to find the position in the video where the seek begins? + +If this is not possible, I'd settle for a way to disable seeking during playback. + +EDIT: adding code as requested. It's pretty simple: + +``` +var trackedPlayer = videojs('pvp-player'); + +trackedPlayer.on(""play"", function (e) { + console.log(""Video playback started: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""pause"", function (e) { + console.log(""Video playback paused: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeking"", function (e) { + console.log(""Video seeking: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeked"", function (e) { + console.log(""Video seek ended: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""ended"", function (e) { + console.log(""Video playback ended.""); +}); + +``` + +If I can get all the tracking I want I will replace console.log with ajax calls to store the data.",2015/04/20,"['https://Stackoverflow.com/questions/29743729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664914/']","You can listen to `timeupdate` und take the next to last value you got there before `seeking` is called as your source: + +``` +var previousTime = 0; +var currentTime = 0; +trackedPlayer.on('timeupdate', function() { + previousTime = currentTime; + currentTime = trackedPlayer.currentTime(); +}); +trackedPlayer.on('seeking', function() { + console.log('seeking from', previousTime, 'to', currentTime, '; delta:', currentTime - previousTime); +}); + +``` + +This seems to work with the HTML5 tech. I have not tested with other techs. + +There is, however, one glitch: the first time seeking a *paused* player yields only a small delta (and the almost-same previous value for both variables). But this shouldn’t matter much since the delta is only a few hundred milliseconds (and I gather you’re only interested in the “from” value). + +**Update** + +`seeked` is triggered far more infrequently than `seeking`. Try the following. + +``` +var previousTime = 0; +var currentTime = 0; +var seekStart = null; +trackedPlayer.on('timeupdate', function() { + previousTime = currentTime; + currentTime = trackedPlayer.currentTime(); +}); +trackedPlayer.on('seeking', function() { + if(seekStart === null) { + seekStart = previousTime; + } +}); +trackedPlayer.on('seeked', function() { + console.log('seeked from', seekStart, 'to', currentTime, '; delta:', currentTime - previousTime); + seekStart = null; +}); + +``` + +There are also many libraries for debouncing function calls (in this case the call to your backend).","For a more accurate solution, you can listen to the events that trigger the seek such as mousedown on progress bar, left key, right key etc., and get the current time from these events. +For example in version 7.10.2 you can do the following, + +``` +let seekStartTime; + +player.controlBar.progressControl.on('mousedown', () => seekStartTime = player.currentTime()); +player.controlBar.progressControl.seekBar.on('mousedown', () => seekStartTime = player.currentTime()); +player.on('keydown', (e) => { + if (e.key === ""ArrowLeft"" || e.key === ""ArrowRight"") { + seekStartTime = player.currentTime(); + } +}); + +console.log(seekStartTime); + +``` + +**Note 1:** There are two seperate mousedown event listeners for progress control and seek bar. This is because the video can be seeked by clicking outside the seek bar on the progress control as well. + +**Note 2:** Seeking using hotkey numbers does not pause the video. However, if necessary you can add those keydown listeners too." +29743729,"I am using video.js () to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks. + +I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it. + +When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play. + +If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started. + +Can anyone help me to find the position in the video where the seek begins? + +If this is not possible, I'd settle for a way to disable seeking during playback. + +EDIT: adding code as requested. It's pretty simple: + +``` +var trackedPlayer = videojs('pvp-player'); + +trackedPlayer.on(""play"", function (e) { + console.log(""Video playback started: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""pause"", function (e) { + console.log(""Video playback paused: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeking"", function (e) { + console.log(""Video seeking: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""seeked"", function (e) { + console.log(""Video seek ended: "" + trackedPlayer.currentTime()); +}); + +trackedPlayer.on(""ended"", function (e) { + console.log(""Video playback ended.""); +}); + +``` + +If I can get all the tracking I want I will replace console.log with ajax calls to store the data.",2015/04/20,"['https://Stackoverflow.com/questions/29743729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664914/']","You can listen to `timeupdate` und take the next to last value you got there before `seeking` is called as your source: + +``` +var previousTime = 0; +var currentTime = 0; +trackedPlayer.on('timeupdate', function() { + previousTime = currentTime; + currentTime = trackedPlayer.currentTime(); +}); +trackedPlayer.on('seeking', function() { + console.log('seeking from', previousTime, 'to', currentTime, '; delta:', currentTime - previousTime); +}); + +``` + +This seems to work with the HTML5 tech. I have not tested with other techs. + +There is, however, one glitch: the first time seeking a *paused* player yields only a small delta (and the almost-same previous value for both variables). But this shouldn’t matter much since the delta is only a few hundred milliseconds (and I gather you’re only interested in the “from” value). + +**Update** + +`seeked` is triggered far more infrequently than `seeking`. Try the following. + +``` +var previousTime = 0; +var currentTime = 0; +var seekStart = null; +trackedPlayer.on('timeupdate', function() { + previousTime = currentTime; + currentTime = trackedPlayer.currentTime(); +}); +trackedPlayer.on('seeking', function() { + if(seekStart === null) { + seekStart = previousTime; + } +}); +trackedPlayer.on('seeked', function() { + console.log('seeked from', seekStart, 'to', currentTime, '; delta:', currentTime - previousTime); + seekStart = null; +}); + +``` + +There are also many libraries for debouncing function calls (in this case the call to your backend).","I needed to find the start and end of a seeking action in my project and I used @Motorcykey answer and it worked, but there was a small bug. when I tried to seek to a time before the current time while the player was paused, the `position` didn't get updated. so I added just one line and it fixed it. I've tried other solutions too but so far this was the best solution that I've found. Here's the code snippet on player 'seeked' + +``` +player.on('seeked', function () { + completeTime = Math.floor(player.currentTime()); + console.log(""User came from: "" + position); + console.log(""User ended at: "" + completeTime); + position= Math.floor(player.currentTime()) +}); + +```" +2767139,"Can I do this in C++ (if yes, what is the syntax?): + +``` +void func(string* strs) { + // do something +} +func({""abc"", ""cde""}); + +``` + +I want to pass an array to a function, without instantiating it as a variable.",2010/05/04,"['https://Stackoverflow.com/questions/2767139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187141/']","It can't be done in the current C++, as defined by C++03. + +The feature you are looking for is called ""compound literals"". It is present in C language, as defined by C99 (with C-specific capabilities, of course), but not in C++. + +A similar feature is planned for C++ as well, but it is not there yet.","I don't think you can do that in C++98, but you can with [initializer\_lists](https://stackoverflow.com/questions/2357452/stdinitializer-list-as-function-argument) in C++1x." +2767139,"Can I do this in C++ (if yes, what is the syntax?): + +``` +void func(string* strs) { + // do something +} +func({""abc"", ""cde""}); + +``` + +I want to pass an array to a function, without instantiating it as a variable.",2010/05/04,"['https://Stackoverflow.com/questions/2767139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187141/']","It can't be done in the current C++, as defined by C++03. + +The feature you are looking for is called ""compound literals"". It is present in C language, as defined by C99 (with C-specific capabilities, of course), but not in C++. + +A similar feature is planned for C++ as well, but it is not there yet.","As written, you can't do this. The function expects a pointer-to-string. Even if you were able to pass an array as a literal, the function call would generate errors because literals are considered constant (thus, the array of literals would be of type `const string*`, not `string*` as the function expects)." +2767139,"Can I do this in C++ (if yes, what is the syntax?): + +``` +void func(string* strs) { + // do something +} +func({""abc"", ""cde""}); + +``` + +I want to pass an array to a function, without instantiating it as a variable.",2010/05/04,"['https://Stackoverflow.com/questions/2767139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187141/']","It can't be done in the current C++, as defined by C++03. + +The feature you are looking for is called ""compound literals"". It is present in C language, as defined by C99 (with C-specific capabilities, of course), but not in C++. + +A similar feature is planned for C++ as well, but it is not there yet.","Use a variadic function to pass in unlimited untyped information into a function. Then do whatever you want with the passed in data, such as stuffing it into an internal array. + +[variadic function](http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_C.2C_Objective-C.2C_C.2B.2B.2C_and_D)" +14559761,"I want to use `std::initializer_list`s in Visual Studio 2012 like a guy in [this example](http://musingstudio.com/2012/11/27/stdinitializer_list-an-even-better-way-to-populate-a-vector/) does. My operating system is Windows 8 x64. + +Therefore I lately installed the [Visual C++ Compiler November 2012 CTP](http://www.microsoft.com/en-us/download/details.aspx?id=35515) and as mentioned by Microsoft, I changed the platform toolset of my project to use that new updated compiler. + +But even after doing so, there is neither a `std::initializer_list` nor a `` header available. But the linked website from Microsoft tells me (under the headline ""Overview"") that initializer lists would be available with that update. I restarted both the IDE and my PC. I am not sure if it could be caused by the fact that I am (sadly) using the German edition of Visual Studio and the compiler update is in English. What am I doing wrong? + +Update: Trying to compile the line `auto a = { 0 };` which is criticized by IntelliSense the compiler output shows `'Microsoft Visual C++ Compiler Nov 2012 CTP' is for testing purposes only.` and then compiler crashes and a error window appears which reads `Microsoft (R) C/C++ Compiler Driver has stopped working`. Without any new syntax, everything compiles and works fine with the new compiler selected.",2013/01/28,"['https://Stackoverflow.com/questions/14559761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1079110/']","(I work for Microsoft and with Dinkumware to maintain VC's Standard Library implementation.) + +[danijar] + +> +> I am not sure if it could be caused by the fact that I am (sadly) using the German edition of Visual Studio and the compiler update is in English. +> +> +> + +Unfortunately, the English-only CTP does not support German VS. + +The ""compiler driver"" cl.exe is what invokes the compiler front-end c1xx.dll, the compiler back-end c2.dll, and the linker link.exe. It is very unusual for the compiler driver to crash. I speculate that it's attempting to display one of the error messages that were added by the CTP, but since the CTP didn't update the German resources, the compiler driver can't load the error message and proceeds to crash. + +Note that this is different from an Internal Compiler Error in the front-end or back-end, or a normal compiler error that happens to be incorrectly emitted. (Many ICEs and bogus errors have been fixed after the CTP was released.) + +> +> But even after doing so, there is neither a std::initializer\_list nor a header available. +> +> +> + +The CTP installed in a special location. (It was actually written by the compiler team.) + +On the command line, the incantations to use the CTP and put on the include path are (assuming default locations): + +``` +""C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\vcvarsall.bat"" x86 +set PATH=C:\Program Files (x86)\Microsoft Visual C++ Compiler Nov 2012 CTP\bin;%PATH% +set INCLUDE=C:\Program Files (x86)\Microsoft Visual C++ Compiler Nov 2012 CTP\include;%INCLUDE% + +``` + +> +> Trying to compile the line auto a = { 0 }; which is criticized by IntelliSense +> +> +> + +This was documented - Intellisense was not updated by the CTP, therefore it will not recognize any of the new features. + +[rubenvb] + +> +> The C++ Standard Library was not updated with the compiler, leaving you without decent and (this includes the omission of the braced init list constructors for all standard containers) +> +> +> + +You may be interested to learn that we've updated the standard library to fully support scoped enums and initializer lists. This includes all initializer\_list overloads mandated by the current Working Paper (N3485), plus installing in the usual location along with all other standard headers. (It is also Dinkumware's official copy, although the differences between it and the compiler team's ""fake"" version were mostly cosmetic.) This stuff will be available in the next public release, whenever and whatever that is. Our next task is to update the standard library with explicit conversion operators and variadic templates, replacing our brittle simulations.","As you have noticed, the November CTP is very limited in usability for at least two reasons: + +1. The compiler has numerous crash-causing bugs, such as the one you discovered. +2. The C++ Standard Library was not updated with the compiler, leaving you without decent `` and `` (this includes the omission of the braced init list constructors for *all* standard containers) + +Also: the linked example is very ugly code. If you want to use this feature, use a compiler like GCC or Clang that supports this syntax. They are both available for Windows. Hacking around a half-implemented language feature by writing extra code is just stupid." +19995,"I don't recall ever having the problem with the iron before, but it's been a few years since I used it, as I'm just getting back into some projects since my Electronics degree. + +I bought some solder for a new project (I need a lot) and it's lead-free: + +``` +95% Tin +4% Silver +1% Copper + +``` + +Now, I'm not sure how tolerant the values are for melting point but I can say that it does appear to act Eutectic, like the known combination 95.5/4/0.5 ([Indalloy 246](http://www.matweb.com/search/DataSheet.aspx?MatGUID=19662ece2a4a4bb2bbe7aa522f916185)) which has a melting point of 217 degrees Celcius. + +According to the manufacturer of my Iron (Antex) it has a tip temperature of 370 celcius. + +I sanded down the tip yesterday with a fine grain metal sanding paper to see if the tip just needed cleaning, however it's now gone ""black"" instead of the shiny silver it was when I first sanded it. + +The real question I wonder is where the problem lies, is it that my tip is dead, is my iron too low power or is it just that my iron is dead. + +I ask because I need to know whether to replace the iron, the tip or a higher power iron. My preference is to stick with the Antex irons, and I prefer ""precision"" bits like the on in my current iron, so, what are the recommendations?",2011/09/25,"['https://electronics.stackexchange.com/questions/19995', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/5702/']","Your tip is dead since you have now sanded off the special coating. It will of course still get hot, but will oxidize rapidly so that solder won't wick onto it. This will make it very difficult to solder with. + +You say the tip is supposed to be 370C (700F), but is that temperature controlled or just some open loop guess? 12W sounds very low for a temperature controlled soldering station, and also not enough to heat much beyond a little solder and a wire or two at the same time. For example, my Weller WES51 temperature controller soldering station has a 50W iron. Of course most of the time it's not run at 50W, but that's what the control algorithm can cause it to put out when it senses low tip temperature. + +Since you just destroyed your tip (and the iron if it has a fixed tip), maybe it's time to get a real one that has temperature control.","A 12w iron is way under-powered for leadfree. You need a temerature-controlled iron, 40-60W minimum" +38380164,"My project demo as link: + +I use AngularJS. + +If a movie is not found, old values should not appear in the following code + +``` +
+
    +
  • Title: {{result().name}}

  • +
  • Release Date: {{result().release}}

  • +
  • Length: {{result().length}}

  • +
  • Description: {{result().description}}

  • +
  • IMDb Rating: {{result().rating}}

  • +
+
+ +``` + +When I write something in text value and click the button, if the movie is not found, the result page is not updated, so the old values are still showing. + +For example I wrote 'x-men' in text and clicked button, I can see about X-men movie. + +Then I wrote 'asdfg' and clicked the button, I can see `alert('Movie not found')` but old value is still writing in html page. + +I tried `ng-if`, `ng-show` , `$state.reload()` etc. but I could not get it to work. + +Code as snippet: + +```js +var app = angular.module('myApp', []); + + app.controller('searchMovieController', function ($scope, $http, resultFactory) { + $scope.searchMovieF = function () { + if ($scope.searchMovie.length > 0) { + $scope.api = 'http://www.omdbapi.com/?t=' + $scope.searchMovie + '&y=&plot=short&r=json'; + $http.get($scope.api) + .success(function (data) { + $(""#movie-name"").autocomplete({ + source: data.Title + }); + if ((data.Error != ""Movie not found!"") && ( data.Error != ""Must provide more than one character."")) { + var details = { + name:data.Title, + release: data.Released, + length: data.Runtime, + description: data.Plot, + rating: data.imdbRating + } + resultFactory.set(details) + + } + else { + alert(""Movie not found !"") + } + }); + } else { + alert(""Please write somethings !"") + } + } + }); + app.controller('resultMovieController', function ($scope,resultFactory) { + $scope.result = function() { + return resultFactory.details + } + }); + + app.factory('resultFactory', function() { + var details = { + + } + var set = function(obj) { + var objKeys = Object.keys(obj); + for(var i=0; i < objKeys.length; i++) { + details[objKeys[i]] = obj[objKeys[i]]; + } + } + return { + details: details, + set: set + } + }) +``` + +```html + + + +
+
+
+ Search Movie +
+
+ + + + + Search + +
+
+
    +
  • Title: {{name}}

  • +
  • Release Date: {{release}}

  • +
  • Length: {{length}}

  • +
  • Description: {{description}}

  • +
  • IMDb Rating: {{rating}}

  • +
+
+ +





+ +
+
+
+ Result for Search Movie +
+
+
    +
  • Title: {{result().name}}

  • +
  • Release Date: {{result().release}}

  • +
  • Length: {{result().length}}

  • +
  • Description:{{result().description}}

  • +
  • IMDb Rating: {{result().rating}}

  • +
+ + Back to Search Page + +
+```",2016/07/14,"['https://Stackoverflow.com/questions/38380164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5257578/']","It would appear that the resultFactory is not being set with new values unless a film is actually found. You'll have to make sure that your resultFactory is being set even when a film does not match the user's search entry. + +You can simply move your resultFactory.set outside of the `if` statement and set each key to an empty string if the key is not defined in `data`. This can be done quickly per key by using two pipes (`||`) in resultFactory.set + +``` +resultFactory.set({ + name:data.Title || '', + release: data.Released || '', + length: data.Runtime || '', + description: data.Plot || '', + rating: data.imdbRating || '' +}); + +``` + +[Here's a link to the updated JSFiddle](http://jsfiddle.net/f6uomqja/) including the fix.","You need to add this + +``` +var details = { + name:"""", + release: """", + length: """", + description: """", + rating: """" + } + resultFactory.set(details) + +``` + +in the else block + +add the entire code: + +``` +var app = angular.module('myApp', []); + + app.controller('searchMovieController', function ($scope, $http, resultFactory) { + $scope.searchMovieF = function () { + if ($scope.searchMovie.length > 0) { + $scope.api = 'http://www.omdbapi.com/?t=' + $scope.searchMovie + '&y=&plot=short&r=json'; + $http.get($scope.api) + .success(function (data) { + $(""#movie-name"").autocomplete({ + source: data.Title + }); + if ((data.Error != ""Movie not found!"") && ( data.Error != ""Must provide more than one character."")) { + var details = { + name:data.Title, + release: data.Released, + length: data.Runtime, + description: data.Plot, + rating: data.imdbRating + } + resultFactory.set(details) + + } + else { + alert(""Movie not found !"") + var details = { + name:"""", + release: """", + length: """", + description: """", + rating: """" + } + resultFactory.set(details) + } + }); + } else { + alert(""Please write somethings !"") + } + } + }); + app.controller('resultMovieController', function ($scope,resultFactory) { + $scope.result = function() { + return resultFactory.details + } + }); + + app.factory('resultFactory', function() { + var details = { + + } + var set = function(obj) { + var objKeys = Object.keys(obj); + for(var i=0; i < objKeys.length; i++) { + details[objKeys[i]] = obj[objKeys[i]]; + } + } + return { + details: details, + set: set + } + }) + +```" +4583801,"This is a classical Sangaku problem, also known as old Japanese geometry problems, that I found out just recently. The figure shows a semicircle with a smaller circle and an equilateral triangle inscribed inside it. Note that the semicircle can be *any* general semicircle, but in this case it has a radius of $1$ unit. Also note that one of the vertices of the equilateral triangle lies on the center of the semicircle. I have solved this problem and I'll post my approach as an answer, in order to not clutter up this space. Please share your own approaches as well! + +[![enter image description here](https://i.stack.imgur.com/48a0g.png)](https://i.stack.imgur.com/48a0g.png)",2022/11/23,"['https://math.stackexchange.com/questions/4583801', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1092912/']","A slightly quicker step (2) skips the quadratic formula: Observe that the hypotenuse shared by your two 30-60-90 triangles has length $\frac 2{\sqrt 3} r$ (since the side lengths are proportional to $1:\sqrt 3:2$), hence +$$r + \frac 2{\sqrt 3}r = 1$$ +which yields $r=2\sqrt 3-3$.","Here's my approach for the problem: + +Please note that my answer uses a lemma that can be proven easily, that is, [the radii of two externally or internally tangent circles are collinear](https://youtu.be/0whTkdGBNn0). + +[![enter image description here](https://i.stack.imgur.com/R518H.png)](https://i.stack.imgur.com/R518H.png) + +1.) First, we join the center of the semicircle with that of the circle, and draw a perpendicular from the center of the circle to the tangent points (semicircle and the vertex of the equilateral triangle). Notice that the two triangles that are formed are congruent via the SSS property, therefore we can conclude that the line connecting two centers is an angle sector. This proves that the two triangles are in fact ""$30-60-90$"" triangle. + +2.) Now, using the fact proven above, we can say that the base of those triangles (i.e. the side opposite to the $30^\circ$ angle) is $\frac{r}{\sqrt3}$. Finally, we can finish off the problem: + +$$(1-r)^2=r^2+(\frac{r}{\sqrt3})^2$$ + +$$1-2r+r^2=r^2+\frac{r^2}{3}$$ + +$$r^2+6r-3=0$$ + +Since this isn't factorable, we can use the quadratic formula: + +$$r=\frac{-6±\sqrt{48}}{2}$$ + +Since $\frac{-6-\sqrt{48}}{2}$ would be negative, we must reject that. Therefore: + +$$r=-3+2\sqrt{3}$$" +6856491,"There is a file named \*.iso, where `*` is any string (dot, numbers, alphabets, spl characters). + +\*.iso is located at /dm2/www/html/isos/preFCS5.3/ + +I want to get this filename into $filename. I know it's very simple. How can I do this in Perl?",2011/07/28,"['https://Stackoverflow.com/questions/6856491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713200/']","Destructor of the Base class will be automatically called by the compiler, when your objet life time ends. you do not need to call it explicitly. + +``` +TMyObject::TMyObject() : TObject() + +``` + +Does not inherit the constructor. + +It is called as **[Member initializer list](https://stackoverflow.com/questions/6724626/c-constructor/6724639#6724639)** and it initializes the Base class object with a particular value. + +When you create the object. + +``` +TMyObject obj; + +``` + +The constructors will be called in order: + +``` +constructor of TObject +constructor of TMyObject + +``` + +When the object life time ends the destructors will be called in the order: + +``` +destructor of TMyObject +destructr of TObject + +``` + +The compiler will do so for you, do not need to call it explicitly.","If you destroy a `TMyObject` through a reference of type `TMyObject` you don't have to do anything. In case you have a pointer/reference of type `TObject` to a `TMyObject` things will go wrong. *Only* the `TObject` destructor will be called, not the `TMyObject` one: + +``` +TObject* p = new TMyObject; +delete p; // Only the TObject::~TObject is called, not TMyObject::~TMyObject. + +``` + +To have the decision on what destructor to call deferred to runtime, you need to specify the destructor as `virtual` in `TObject`. Whenever you have a class that is intended to be derived from, the destructor should be virtual. Otherwise there is always a risk for resource leaks when the derived class destructor isn't called properly." +6856491,"There is a file named \*.iso, where `*` is any string (dot, numbers, alphabets, spl characters). + +\*.iso is located at /dm2/www/html/isos/preFCS5.3/ + +I want to get this filename into $filename. I know it's very simple. How can I do this in Perl?",2011/07/28,"['https://Stackoverflow.com/questions/6856491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713200/']","Destructor of the Base class will be automatically called by the compiler, when your objet life time ends. you do not need to call it explicitly. + +``` +TMyObject::TMyObject() : TObject() + +``` + +Does not inherit the constructor. + +It is called as **[Member initializer list](https://stackoverflow.com/questions/6724626/c-constructor/6724639#6724639)** and it initializes the Base class object with a particular value. + +When you create the object. + +``` +TMyObject obj; + +``` + +The constructors will be called in order: + +``` +constructor of TObject +constructor of TMyObject + +``` + +When the object life time ends the destructors will be called in the order: + +``` +destructor of TMyObject +destructr of TObject + +``` + +The compiler will do so for you, do not need to call it explicitly.","What's causing the confusion to you is that you can specifically mention ""which"" constructor of the base class you want to use as in the following example. But you can't/ don't need to specify the destructor. + +``` +TMyObject::TMyObject() : TObject() + +``` + +You could use a different constructor, say `TObject (int i)` by writing + +``` +TMyObject::TMyObject() : TObject (3) + +``` + +An object can be destructed in only one way but it can be constructed in several ways (by having different constructors). + +So, in short, you don't need to mention the name of the base class destructor in the derived class destructor. As soon as you destroy the derived object (say, by doing `delete derivedObj`), it will first call the derived class destructor and then base class destructor by itself." +6856491,"There is a file named \*.iso, where `*` is any string (dot, numbers, alphabets, spl characters). + +\*.iso is located at /dm2/www/html/isos/preFCS5.3/ + +I want to get this filename into $filename. I know it's very simple. How can I do this in Perl?",2011/07/28,"['https://Stackoverflow.com/questions/6856491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713200/']","This can be solved at `TObject`'s level. Its destructor has to be virtual: + +``` +#include +class TObject +{ + __fastcall TObject(); + virtual __fastcall ~TObject(); +}; + +``` + +This way you can either do: + +``` +TObject * pobj = new TMyObject(); +delete pobj; + +``` + +or + +``` +TMyObject * pobj = new TMyObject(); +delete pobj; + +``` + +Both destructors will be called (`~TMyObject()` first and then `~TObject()`) and you will have no leak.","Destructor of the Base class will be automatically called by the compiler, when your objet life time ends. you do not need to call it explicitly. + +``` +TMyObject::TMyObject() : TObject() + +``` + +Does not inherit the constructor. + +It is called as **[Member initializer list](https://stackoverflow.com/questions/6724626/c-constructor/6724639#6724639)** and it initializes the Base class object with a particular value. + +When you create the object. + +``` +TMyObject obj; + +``` + +The constructors will be called in order: + +``` +constructor of TObject +constructor of TMyObject + +``` + +When the object life time ends the destructors will be called in the order: + +``` +destructor of TMyObject +destructr of TObject + +``` + +The compiler will do so for you, do not need to call it explicitly." +6856491,"There is a file named \*.iso, where `*` is any string (dot, numbers, alphabets, spl characters). + +\*.iso is located at /dm2/www/html/isos/preFCS5.3/ + +I want to get this filename into $filename. I know it's very simple. How can I do this in Perl?",2011/07/28,"['https://Stackoverflow.com/questions/6856491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713200/']","This can be solved at `TObject`'s level. Its destructor has to be virtual: + +``` +#include +class TObject +{ + __fastcall TObject(); + virtual __fastcall ~TObject(); +}; + +``` + +This way you can either do: + +``` +TObject * pobj = new TMyObject(); +delete pobj; + +``` + +or + +``` +TMyObject * pobj = new TMyObject(); +delete pobj; + +``` + +Both destructors will be called (`~TMyObject()` first and then `~TObject()`) and you will have no leak.","If you destroy a `TMyObject` through a reference of type `TMyObject` you don't have to do anything. In case you have a pointer/reference of type `TObject` to a `TMyObject` things will go wrong. *Only* the `TObject` destructor will be called, not the `TMyObject` one: + +``` +TObject* p = new TMyObject; +delete p; // Only the TObject::~TObject is called, not TMyObject::~TMyObject. + +``` + +To have the decision on what destructor to call deferred to runtime, you need to specify the destructor as `virtual` in `TObject`. Whenever you have a class that is intended to be derived from, the destructor should be virtual. Otherwise there is always a risk for resource leaks when the derived class destructor isn't called properly." +6856491,"There is a file named \*.iso, where `*` is any string (dot, numbers, alphabets, spl characters). + +\*.iso is located at /dm2/www/html/isos/preFCS5.3/ + +I want to get this filename into $filename. I know it's very simple. How can I do this in Perl?",2011/07/28,"['https://Stackoverflow.com/questions/6856491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/713200/']","This can be solved at `TObject`'s level. Its destructor has to be virtual: + +``` +#include +class TObject +{ + __fastcall TObject(); + virtual __fastcall ~TObject(); +}; + +``` + +This way you can either do: + +``` +TObject * pobj = new TMyObject(); +delete pobj; + +``` + +or + +``` +TMyObject * pobj = new TMyObject(); +delete pobj; + +``` + +Both destructors will be called (`~TMyObject()` first and then `~TObject()`) and you will have no leak.","What's causing the confusion to you is that you can specifically mention ""which"" constructor of the base class you want to use as in the following example. But you can't/ don't need to specify the destructor. + +``` +TMyObject::TMyObject() : TObject() + +``` + +You could use a different constructor, say `TObject (int i)` by writing + +``` +TMyObject::TMyObject() : TObject (3) + +``` + +An object can be destructed in only one way but it can be constructed in several ways (by having different constructors). + +So, in short, you don't need to mention the name of the base class destructor in the derived class destructor. As soon as you destroy the derived object (say, by doing `delete derivedObj`), it will first call the derived class destructor and then base class destructor by itself." +5321883,"I am very new to spring security . I picked up [this](https://rads.stackoverflow.com/amzn/click/com/1847199747) book and trying to execute the code . + +While I do this I am getting + +``` +org.springframework.beans.NotReadablePropertyException: Invalid property +'principal.username' of bean class +[org.springframework.security.authentication.AnonymousAuthenticationToken]: +Bean property 'principal.username' is not readable or has an invalid getter +method: +Does the return type of the getter match the parameter type of the setter? + +``` + +My spring-security xml config : + +``` + + + + + + + + + + + + + + + + + +``` + +Am I missing something ? + +Let me know if you need any additional information.",2011/03/16,"['https://Stackoverflow.com/questions/5321883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/571718/']","What the error message seems to be indicating is that something is trying to access a non-existent property on an `AnonymousAuthenticationToken` ; i.e. the authentication token that spring security uses when the session is not logged in. + +I suspect that the problem is actually occurring either in your servlet code, or in a JSP that is trying to access the name of the current user via a spring security tag. + +The complete stacktrace for the error might give us more clues. At least it should tell us where the exception is coming from. + +(For what it is worth, an `AnonymousAuthenticationToken` does have a `principal` property, but that property is not normally an object that has a `username` property. Indeed, it is often just a String.)","I am reading/following the ""Spring Security 3"" book. Just add the following lines to the header.jsp The problem is that principal.username does not exists if you are not logged in. + +``` +
+ Welcome, + + + +
+ +```" +5321883,"I am very new to spring security . I picked up [this](https://rads.stackoverflow.com/amzn/click/com/1847199747) book and trying to execute the code . + +While I do this I am getting + +``` +org.springframework.beans.NotReadablePropertyException: Invalid property +'principal.username' of bean class +[org.springframework.security.authentication.AnonymousAuthenticationToken]: +Bean property 'principal.username' is not readable or has an invalid getter +method: +Does the return type of the getter match the parameter type of the setter? + +``` + +My spring-security xml config : + +``` + + + + + + + + + + + + + + + + + +``` + +Am I missing something ? + +Let me know if you need any additional information.",2011/03/16,"['https://Stackoverflow.com/questions/5321883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/571718/']","What the error message seems to be indicating is that something is trying to access a non-existent property on an `AnonymousAuthenticationToken` ; i.e. the authentication token that spring security uses when the session is not logged in. + +I suspect that the problem is actually occurring either in your servlet code, or in a JSP that is trying to access the name of the current user via a spring security tag. + +The complete stacktrace for the error might give us more clues. At least it should tell us where the exception is coming from. + +(For what it is worth, an `AnonymousAuthenticationToken` does have a `principal` property, but that property is not normally an object that has a `username` property. Indeed, it is often just a String.)","Prerequisites as follows: + +1. Add spring security taglib in jsp page you want to show username, + +``` +<%@ taglib prefix=""sec"" uri=""http://www.springframework.org/security/tags"" %> + +``` +2. Add spring security jars, use + +``` + + +``` + +in jsp where you want to show the username + +Following will show up: + +1. **anonymousUser**, means user is not logged in +2. **string representation of object**, means user is logged in + +But do not print string representation of object on page. + +Here's a pseudo code: + +``` +if principal==anonymousUser + show login button +else (do not use principal here too) + show username with logout button + +```" +5321883,"I am very new to spring security . I picked up [this](https://rads.stackoverflow.com/amzn/click/com/1847199747) book and trying to execute the code . + +While I do this I am getting + +``` +org.springframework.beans.NotReadablePropertyException: Invalid property +'principal.username' of bean class +[org.springframework.security.authentication.AnonymousAuthenticationToken]: +Bean property 'principal.username' is not readable or has an invalid getter +method: +Does the return type of the getter match the parameter type of the setter? + +``` + +My spring-security xml config : + +``` + + + + + + + + + + + + + + + + + +``` + +Am I missing something ? + +Let me know if you need any additional information.",2011/03/16,"['https://Stackoverflow.com/questions/5321883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/571718/']","I am reading/following the ""Spring Security 3"" book. Just add the following lines to the header.jsp The problem is that principal.username does not exists if you are not logged in. + +``` +
+ Welcome, + + + +
+ +```","Prerequisites as follows: + +1. Add spring security taglib in jsp page you want to show username, + +``` +<%@ taglib prefix=""sec"" uri=""http://www.springframework.org/security/tags"" %> + +``` +2. Add spring security jars, use + +``` + + +``` + +in jsp where you want to show the username + +Following will show up: + +1. **anonymousUser**, means user is not logged in +2. **string representation of object**, means user is logged in + +But do not print string representation of object on page. + +Here's a pseudo code: + +``` +if principal==anonymousUser + show login button +else (do not use principal here too) + show username with logout button + +```" +67863,"The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language?",2015/08/31,"['https://rpg.stackexchange.com/questions/67863', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/21781/']","If it was physically capable of speaking, it would be able to speak the languages it knew in life. It still retains its knowledge of them, so *knowing* how to speak a language is not the problem. The problem is that a skeleton lacks lips, a tongue, vocal cords, a voicebox, and lungs. Speaking is simply impossible. + +The Monster Manual entry on skeletons says: + +> +> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point. +> +> +> + +From this, it seems clear that it is meant to be impossible for skeletons to communicate in **any** way other than the given nodding, shaking, and pointing.",Isn't this why we have Speak with Dead spells? The skeleton has no way of making vocalizations so cannot speak audibly but can understand language due to the magic that animates it. +67863,"The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language?",2015/08/31,"['https://rpg.stackexchange.com/questions/67863', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/21781/']","If it was physically capable of speaking, it would be able to speak the languages it knew in life. It still retains its knowledge of them, so *knowing* how to speak a language is not the problem. The problem is that a skeleton lacks lips, a tongue, vocal cords, a voicebox, and lungs. Speaking is simply impossible. + +The Monster Manual entry on skeletons says: + +> +> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point. +> +> +> + +From this, it seems clear that it is meant to be impossible for skeletons to communicate in **any** way other than the given nodding, shaking, and pointing.","By RAW default, no. +=================== + +As explained by others it has no basic, default, means of expressing language. It's not about learning the language, it's the capability of the spell/energy powering the skeleton(s). Undeath is not in itself an impediment to speech (see: Liches). + +Therefore you need to extrapolate a bit. The RAW description quoted above seems to imply the power source provides bare-minimum world interaction capabilities. And does not extend to advanced capabilities like mimicking a voice (disembodied or otherwise). + +But, the ""talking skull/skeleton"" trope is incredibly common. So... + +By customization, yes. (Possibly with the aid of a magic item.) +=============================================================== + +It is your game, after all. And creativity is a core value of the gaming experience. + +A skeleton is already magically animated, so if you wanted a **specific skeleton** to have the ability to speak, there are several creative ways you could explain the phenomenon. + +* A magic item equipped by its creator, or even left over from its previous life. (An enchanted ring or amulet?) +* A slightly more powerful skeleton who gained the ability to speak over time via wild magic or the like. +* A skeleton created with extra riders on the creation spell by its creator. So maybe it was imbued with a secondary spell to allow a disembodied voice. + +You could have all skeletons speak of that's how you want to run your world, but that'd be your own custom flavoring. + +A speaking skeleton, otherwise, would be **special for some reason**." +67863,"The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language?",2015/08/31,"['https://rpg.stackexchange.com/questions/67863', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/21781/']","If it was physically capable of speaking, it would be able to speak the languages it knew in life. It still retains its knowledge of them, so *knowing* how to speak a language is not the problem. The problem is that a skeleton lacks lips, a tongue, vocal cords, a voicebox, and lungs. Speaking is simply impossible. + +The Monster Manual entry on skeletons says: + +> +> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point. +> +> +> + +From this, it seems clear that it is meant to be impossible for skeletons to communicate in **any** way other than the given nodding, shaking, and pointing."," said + +> +> You've managed to control the energies that sustain you to allow you speak. You can speak, read and write Common, as well as the language of your creator. A Giant Skeleton may speak Giant, a God Touched may know Celestial, a Magic Fluke may randomly grant you a language and a Raised Minion may know their wizard master's draconic. +> +> +> + +so im guessing you can but i think it's for players thats race is skeleton" +67863,"The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language?",2015/08/31,"['https://rpg.stackexchange.com/questions/67863', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/21781/']","If it was physically capable of speaking, it would be able to speak the languages it knew in life. It still retains its knowledge of them, so *knowing* how to speak a language is not the problem. The problem is that a skeleton lacks lips, a tongue, vocal cords, a voicebox, and lungs. Speaking is simply impossible. + +The Monster Manual entry on skeletons says: + +> +> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point. +> +> +> + +From this, it seems clear that it is meant to be impossible for skeletons to communicate in **any** way other than the given nodding, shaking, and pointing.","It is true, on pg 272 of the 5e Monster Manual, it states: + +> +> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point. +> +> +> + +... and D&D Beyond - [Skeleton entry](https://www.dndbeyond.com/monsters/skeleton) states ... + +> +> Understands all languages it knew in life but can't speak +> +> +> + +... but both of these interpretations seem to be relatively 'new' 5e expansions to d&d skeleton lore. Wrt Habitual Behaviors in the 5e MM, if ""skeletons of nobles might continue in an eternally unfinished dance"" && ""can load and fire a catapult or trebuchet"". +Also, wrt D&D Beyond, it appears to be poorly worded. If taken literally, that it simply cannot speak; then it would be able to use sign language, portions of thieves cant, or write & still communicate. + +I think all of the older versions are more consistent wrt skeletons in this respect; in that the creator can command them via magic (and it ignores the medium of the command.) + +Therefore we need to break up your question: + +1. Can it not speak because of its undeath? + +If you look at all the lore in total, the answer here would be the skeleton cannot ""communicate"", speaking or otherwise. If you look at 5e literally, then the two sources are possibly contradictory & you'll have to subjectively decide for your world/campaign. + +2. Could it learn to speak a language? + +The simple answer is no... however, again looking at all the lore, should a different necromancer, demon, etc gain control of the skeleton; the method of control would give the ability to command irrespective of language. + +Relatedly, an item of consideration is whether or not skeletons are deaf, & how their ""vison"" works.?. In my campaigns, skeletons are ""unintelligent"", and are deaf; with their ""vision"" being more animalistic/primitive in nature (they can't read, or understand complex items )... + +This isn't to say a specific necromancer couldn't craft a ""unique breed"" of skeletons that have different features, including higher intelligence; but just that the ""average"" skeleton does not." +67863,"The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language?",2015/08/31,"['https://rpg.stackexchange.com/questions/67863', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/21781/']","By RAW default, no. +=================== + +As explained by others it has no basic, default, means of expressing language. It's not about learning the language, it's the capability of the spell/energy powering the skeleton(s). Undeath is not in itself an impediment to speech (see: Liches). + +Therefore you need to extrapolate a bit. The RAW description quoted above seems to imply the power source provides bare-minimum world interaction capabilities. And does not extend to advanced capabilities like mimicking a voice (disembodied or otherwise). + +But, the ""talking skull/skeleton"" trope is incredibly common. So... + +By customization, yes. (Possibly with the aid of a magic item.) +=============================================================== + +It is your game, after all. And creativity is a core value of the gaming experience. + +A skeleton is already magically animated, so if you wanted a **specific skeleton** to have the ability to speak, there are several creative ways you could explain the phenomenon. + +* A magic item equipped by its creator, or even left over from its previous life. (An enchanted ring or amulet?) +* A slightly more powerful skeleton who gained the ability to speak over time via wild magic or the like. +* A skeleton created with extra riders on the creation spell by its creator. So maybe it was imbued with a secondary spell to allow a disembodied voice. + +You could have all skeletons speak of that's how you want to run your world, but that'd be your own custom flavoring. + +A speaking skeleton, otherwise, would be **special for some reason**.",Isn't this why we have Speak with Dead spells? The skeleton has no way of making vocalizations so cannot speak audibly but can understand language due to the magic that animates it. +67863,"The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language?",2015/08/31,"['https://rpg.stackexchange.com/questions/67863', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/21781/']","It is true, on pg 272 of the 5e Monster Manual, it states: + +> +> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point. +> +> +> + +... and D&D Beyond - [Skeleton entry](https://www.dndbeyond.com/monsters/skeleton) states ... + +> +> Understands all languages it knew in life but can't speak +> +> +> + +... but both of these interpretations seem to be relatively 'new' 5e expansions to d&d skeleton lore. Wrt Habitual Behaviors in the 5e MM, if ""skeletons of nobles might continue in an eternally unfinished dance"" && ""can load and fire a catapult or trebuchet"". +Also, wrt D&D Beyond, it appears to be poorly worded. If taken literally, that it simply cannot speak; then it would be able to use sign language, portions of thieves cant, or write & still communicate. + +I think all of the older versions are more consistent wrt skeletons in this respect; in that the creator can command them via magic (and it ignores the medium of the command.) + +Therefore we need to break up your question: + +1. Can it not speak because of its undeath? + +If you look at all the lore in total, the answer here would be the skeleton cannot ""communicate"", speaking or otherwise. If you look at 5e literally, then the two sources are possibly contradictory & you'll have to subjectively decide for your world/campaign. + +2. Could it learn to speak a language? + +The simple answer is no... however, again looking at all the lore, should a different necromancer, demon, etc gain control of the skeleton; the method of control would give the ability to command irrespective of language. + +Relatedly, an item of consideration is whether or not skeletons are deaf, & how their ""vison"" works.?. In my campaigns, skeletons are ""unintelligent"", and are deaf; with their ""vision"" being more animalistic/primitive in nature (they can't read, or understand complex items )... + +This isn't to say a specific necromancer couldn't craft a ""unique breed"" of skeletons that have different features, including higher intelligence; but just that the ""average"" skeleton does not.",Isn't this why we have Speak with Dead spells? The skeleton has no way of making vocalizations so cannot speak audibly but can understand language due to the magic that animates it. +67863,"The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language?",2015/08/31,"['https://rpg.stackexchange.com/questions/67863', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/21781/']","By RAW default, no. +=================== + +As explained by others it has no basic, default, means of expressing language. It's not about learning the language, it's the capability of the spell/energy powering the skeleton(s). Undeath is not in itself an impediment to speech (see: Liches). + +Therefore you need to extrapolate a bit. The RAW description quoted above seems to imply the power source provides bare-minimum world interaction capabilities. And does not extend to advanced capabilities like mimicking a voice (disembodied or otherwise). + +But, the ""talking skull/skeleton"" trope is incredibly common. So... + +By customization, yes. (Possibly with the aid of a magic item.) +=============================================================== + +It is your game, after all. And creativity is a core value of the gaming experience. + +A skeleton is already magically animated, so if you wanted a **specific skeleton** to have the ability to speak, there are several creative ways you could explain the phenomenon. + +* A magic item equipped by its creator, or even left over from its previous life. (An enchanted ring or amulet?) +* A slightly more powerful skeleton who gained the ability to speak over time via wild magic or the like. +* A skeleton created with extra riders on the creation spell by its creator. So maybe it was imbued with a secondary spell to allow a disembodied voice. + +You could have all skeletons speak of that's how you want to run your world, but that'd be your own custom flavoring. + +A speaking skeleton, otherwise, would be **special for some reason**."," said + +> +> You've managed to control the energies that sustain you to allow you speak. You can speak, read and write Common, as well as the language of your creator. A Giant Skeleton may speak Giant, a God Touched may know Celestial, a Magic Fluke may randomly grant you a language and a Raised Minion may know their wizard master's draconic. +> +> +> + +so im guessing you can but i think it's for players thats race is skeleton" +67863,"The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language?",2015/08/31,"['https://rpg.stackexchange.com/questions/67863', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/21781/']","By RAW default, no. +=================== + +As explained by others it has no basic, default, means of expressing language. It's not about learning the language, it's the capability of the spell/energy powering the skeleton(s). Undeath is not in itself an impediment to speech (see: Liches). + +Therefore you need to extrapolate a bit. The RAW description quoted above seems to imply the power source provides bare-minimum world interaction capabilities. And does not extend to advanced capabilities like mimicking a voice (disembodied or otherwise). + +But, the ""talking skull/skeleton"" trope is incredibly common. So... + +By customization, yes. (Possibly with the aid of a magic item.) +=============================================================== + +It is your game, after all. And creativity is a core value of the gaming experience. + +A skeleton is already magically animated, so if you wanted a **specific skeleton** to have the ability to speak, there are several creative ways you could explain the phenomenon. + +* A magic item equipped by its creator, or even left over from its previous life. (An enchanted ring or amulet?) +* A slightly more powerful skeleton who gained the ability to speak over time via wild magic or the like. +* A skeleton created with extra riders on the creation spell by its creator. So maybe it was imbued with a secondary spell to allow a disembodied voice. + +You could have all skeletons speak of that's how you want to run your world, but that'd be your own custom flavoring. + +A speaking skeleton, otherwise, would be **special for some reason**.","It is true, on pg 272 of the 5e Monster Manual, it states: + +> +> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point. +> +> +> + +... and D&D Beyond - [Skeleton entry](https://www.dndbeyond.com/monsters/skeleton) states ... + +> +> Understands all languages it knew in life but can't speak +> +> +> + +... but both of these interpretations seem to be relatively 'new' 5e expansions to d&d skeleton lore. Wrt Habitual Behaviors in the 5e MM, if ""skeletons of nobles might continue in an eternally unfinished dance"" && ""can load and fire a catapult or trebuchet"". +Also, wrt D&D Beyond, it appears to be poorly worded. If taken literally, that it simply cannot speak; then it would be able to use sign language, portions of thieves cant, or write & still communicate. + +I think all of the older versions are more consistent wrt skeletons in this respect; in that the creator can command them via magic (and it ignores the medium of the command.) + +Therefore we need to break up your question: + +1. Can it not speak because of its undeath? + +If you look at all the lore in total, the answer here would be the skeleton cannot ""communicate"", speaking or otherwise. If you look at 5e literally, then the two sources are possibly contradictory & you'll have to subjectively decide for your world/campaign. + +2. Could it learn to speak a language? + +The simple answer is no... however, again looking at all the lore, should a different necromancer, demon, etc gain control of the skeleton; the method of control would give the ability to command irrespective of language. + +Relatedly, an item of consideration is whether or not skeletons are deaf, & how their ""vison"" works.?. In my campaigns, skeletons are ""unintelligent"", and are deaf; with their ""vision"" being more animalistic/primitive in nature (they can't read, or understand complex items )... + +This isn't to say a specific necromancer couldn't craft a ""unique breed"" of skeletons that have different features, including higher intelligence; but just that the ""average"" skeleton does not." +67863,"The skeleton description says that while it cannot speak it, it can understand the languages it knew in life. Can it not speak because of its undeath or could it learn to speak a language?",2015/08/31,"['https://rpg.stackexchange.com/questions/67863', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/21781/']","It is true, on pg 272 of the 5e Monster Manual, it states: + +> +> They can't read, speak, emote, or communicate in any way except to nod, shake their heads, or point. +> +> +> + +... and D&D Beyond - [Skeleton entry](https://www.dndbeyond.com/monsters/skeleton) states ... + +> +> Understands all languages it knew in life but can't speak +> +> +> + +... but both of these interpretations seem to be relatively 'new' 5e expansions to d&d skeleton lore. Wrt Habitual Behaviors in the 5e MM, if ""skeletons of nobles might continue in an eternally unfinished dance"" && ""can load and fire a catapult or trebuchet"". +Also, wrt D&D Beyond, it appears to be poorly worded. If taken literally, that it simply cannot speak; then it would be able to use sign language, portions of thieves cant, or write & still communicate. + +I think all of the older versions are more consistent wrt skeletons in this respect; in that the creator can command them via magic (and it ignores the medium of the command.) + +Therefore we need to break up your question: + +1. Can it not speak because of its undeath? + +If you look at all the lore in total, the answer here would be the skeleton cannot ""communicate"", speaking or otherwise. If you look at 5e literally, then the two sources are possibly contradictory & you'll have to subjectively decide for your world/campaign. + +2. Could it learn to speak a language? + +The simple answer is no... however, again looking at all the lore, should a different necromancer, demon, etc gain control of the skeleton; the method of control would give the ability to command irrespective of language. + +Relatedly, an item of consideration is whether or not skeletons are deaf, & how their ""vison"" works.?. In my campaigns, skeletons are ""unintelligent"", and are deaf; with their ""vision"" being more animalistic/primitive in nature (they can't read, or understand complex items )... + +This isn't to say a specific necromancer couldn't craft a ""unique breed"" of skeletons that have different features, including higher intelligence; but just that the ""average"" skeleton does not."," said + +> +> You've managed to control the energies that sustain you to allow you speak. You can speak, read and write Common, as well as the language of your creator. A Giant Skeleton may speak Giant, a God Touched may know Celestial, a Magic Fluke may randomly grant you a language and a Raised Minion may know their wizard master's draconic. +> +> +> + +so im guessing you can but i think it's for players thats race is skeleton" +30072278,"I am having trouble with reading in a text file full of names (some are repeated) and inputting the first and last names together on 1 line. The program works and deletes repeated names but outputs them in alphabetical order with first and last names being treated as 2 different names. Am I outputting the names wrong with: + +``` +string name; +while (partyList >> name) +{ + NamesList.insert(name); +} + +cout << ""Here is the party list without repetion: "" << endl; +while (!NamesList.empty()) { + cout << ' ' << *NamesList.begin() << endl; + NamesList.erase(NamesList.begin()); +} + +``` + +? + +The text file is PartyList.txt and it contains: + +``` +Daniel Walrus +Amy Giester +Jim Carry +Gregg Lunch +Irony Max +Jim Carry +Daniel Walrus +Gregg Lunch + +``` + +Currently my output is: + +``` +Amy +Carrey +Daniel +Giester +Gregg +Irony +Jim +Lunch +Max +Walrus + +``` + +Here is my code (this is part of a larger assignment which is completed besides making the first and last names go together): + +``` +#include +#include +#include +#include + +using namespace std; +void PartyList(); + +int main() +{ +PartyList(); +system(""PAUSE""); +return 0; +} + +void PartyList() +{ +fstream partyList; +partyList.open(""PartyList.txt"", fstream::in); + +if (!partyList) +{ + cout << ""Couldn't open file!"" << endl; +} + +set NamesList; +string name; +while (partyList >> name) +{ + NamesList.insert(name); +} + +cout << ""Here is the party list without repetion: "" << endl; +while(!NamesList.empty()) { cout << ' ' << *NamesList.begin() << endl; + NamesList.erase(NamesList.begin()); +} +//cout << name << endl; + +cout << endl; +} + +```",2015/05/06,"['https://Stackoverflow.com/questions/30072278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4110090/']","The `>>` operator in `partyList >> name` only reads from `partyList` until whitespace, which includes spaces, so `name` gets the values `""Daniel""`, `""Walrus""`, `""Amy""`, etc. on iteration. If you want to read one line at a time, use + +``` +while (std::getline(partyList, name)) + +``` + +which gets you `""Daniel Walrus""` etc.","``` +while (partyList >> name) + +``` + +The `>>` operator is looking here for a first blank character. That's why your names are split this way." +47278674,"I recently started study opencv. I only have a bachelor's degree on engineering. I am having a hard time of understanding these 2 morphological transformation: Black Hat, Top Hat. the official documents is [here](https://docs.opencv.org/master/d9/d61/tutorial_py_morphological_ops.html) + +Can some one give some advice of what is the intuition of these operation and what is it for?",2017/11/14,"['https://Stackoverflow.com/questions/47278674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6898439/']","Hopefully you understand *”morphological opening”*. If so, the (white) Top Hat tells you the pixels that would be removed by *”opening”*. + +Likewise, the Black Hat tells you the pixels that would be added by *”morphological closing”*.","See the image for explanation. Simple algebra will help here. + +> +> Top hat +> +> +> + +top hat = image - opening = image - (image - false +ves) = false +ves + +> +> Black hat +> +> +> + +black hat = image - closing = image - (image - false -ves) = false -ves + +[Explanation](https://i.stack.imgur.com/3Y15r.jpg)" +11615082,"I'm trying to run a macro that will delete rows that don't contain a particular value in column B. Here's my code: + +``` +Sub deleteRows() + Dim count As Integer + count = Application.WorksheetFunction.CountA(Range(""AF:AF"")) + Dim i As Integer + i = 21 + Do While i <= count + If (Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search(""OSR Platform"", Range(""B"" & i))) = False) Then + If (Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search(""IAM"", Range(""B"" & i))) = False) Then + Rows(i).EntireRow.Delete + i = i - 1 + count = count - 1 + End If + End If + i = i + 1 + Loop +End Sub + +``` + +Now what it SHOULD be doing is the following: + +1.) Find the number of rows to go through and set that as count (this works) + +2.) Start at row 21 and look for ""OSR Platform"" and ""IAM"" in column B [this kind of works (see below)] + +3.) If it finds neither, delete the entire row and adjust the count and row number as necessary (this works) + +For some reason, whenever the code gets to the first If statement, an error window with a red X pops up that just says ""400."" As far as I can tell, I have written everything syntactically soundly, but clearly there's something wrong.",2012/07/23,"['https://Stackoverflow.com/questions/11615082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1512308/']","You may want to start by looping the other way. When you delete a line, all the previous lines are shifted. You account for this, but a reverse loop is simpler (*for me anyways*) to understand than keeping track of when I've offset the current position within the loop: + +`For i = count To 21 Step -1` + +Also, you're relying too much on `Application.WorksheetFunction`: + +`(Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search(""OSR Platform"", Range(""B"" & i))) = False)` + +to + +`InStr(Range(""B"" & i).value, ""OSR Platform"") > 0` + +`Application.WorksheetFunction` takes much more processing power, and depending on what you are trying to accomplish, this can take a significantly longer amount of time. Also for this suggested change, the code size is reduced and becomes easier to read without it. + +Your `count` can also be obtained without `A.WF`: + +* Excel 2000/03: `count = Range(""AF65536"").End(xlUp).Row` +* Excel 2007/10: `count = Range(""AF1048576"").End(xlUp).Row` +* Version independent: `count = Range(""AF"" & Rows.Count).End(xlUp).Row` + +One more thing is that you can do (and *should* do in this case) is combine your `If` statements into one. + +Making these changes, you end up with: + +``` +Sub deleteRows() + Dim count As Integer + count = Range(""AF"" & Rows.Count).End(xlUp).Row + Dim i As Integer + For i = count To 21 Step -1 + If Len(Range(""B"" & i).value) > 0 Then + If InStr(Range(""B"" & i).value, ""OSR Platform"") > 0 Or InStr(Range(""B"" & i).value, ""IAM"") > 0 Then + Range(""B"" & i).Interior.Color = RGB(255, 0, 0) + End If + End If + Next i +End Sub + +``` + +If this does not help, then can you step through the code line by line. Add a breakpoint, and step through with `F8`. Highlight the variables in your code, right-click, choose ""add Watch..."", click ""OK"", ([Here's an excellent resource to help you with your debugging in general](http://www.cpearson.com/excel/debug.htm)) and note the following: + +* Which line hits the error? +* What is the value of `i` and `count` when that happens? (add a watch on these variables to help)","This worked for me. It uses AutoFilter, does not require looping or worksheet functions. + +``` +Sub DeleteRows() + +Dim currentSheet As Excel.Worksheet +Dim rngfilter As Excel.Range +Dim lastrow As Long, lastcolumn As Long + +Set currentSheet = ActiveSheet + +' get range +lastrow = currentSheet.Cells(Excel.Rows.Count, ""AF"").End(xlUp).Row +lastcolumn = currentSheet.Cells(1, Excel.Columns.Count).End(xlToLeft).Column +Set rngfilter = currentSheet.Range(""A1"", currentSheet.Cells(lastrow, lastcolumn)) + +' filter by column B criteria +rngfilter.AutoFilter Field:=2, Criteria1:=""<>*OSR Platform*"", Operator:= _ + xlAnd, Criteria2:=""<>*IAM*"" + +' delete any visible row greater than row 21 which does not meet above criteria +rngfilter.Offset(21).SpecialCells(xlCellTypeVisible).EntireRow.Delete + +' remove autofilter arrows +currentSheet.AutoFilterMode = False +End Sub + +``` + +This code applies AutoFilter to column B to see which rows contain neither ""OSR Platform"" nor ""IAM"" in column B. Then it simply deletes the remaining rows greater than 21. Test it on a copy of your workbook first. + +With a huge nod to [this OzGrid](http://www.ozgrid.com/forum/showthread.php?t=153994) thread, because I can never remember the proper syntax for selecting visible cells after filtering." +81217,"If you don't know that it has been sacrificed to idols, then it is okay, +1 Corinthians 10: + +> +> 25Eat whatever is sold in the meat market **without raising any question** on the ground of conscience. +> +> +> + +Don't ask. Just eat. + +> +> 26For “the earth is the Lord’s, and the fullness thereof.” 27If one of the unbelievers invites you to dinner and you are disposed to go, eat whatever is set before you **without raising any question** on the ground of conscience. +> +> +> + +Again, don't ask. + +> +> 28But if someone says to you, “This has been offered in sacrifice,” then **do not eat it**, for the sake of the one who informed you, and for the sake of conscience— +> +> +> + +If you know that it has been sacrificed to idols, then don't eat it in front of them. + +> +> 29I do not mean your conscience, but his. For why should my liberty be determined by someone else’s conscience? 30If I partake with thankfulness, why am I denounced because of that for which I give thanks? +> +> +> + +What if you know that it has been sacrificed to idols and no one else is around, is it okay to eat?",2023/01/31,"['https://hermeneutics.stackexchange.com/questions/81217', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/35953/']","**First,** this section of scripture first appeared nearly 2,000 years ago, and was written to Christians who were surrounded by pagans who had a practice of presenting (offering) meat to their idols before taking it to the market to be sold as food. Therefore, when you ask, ""Should ***we*** eat food sacrificed to idols?"" you have jumped nearly 2,000 years to this day and age, I presume. I take it that you are asking Christians in the Year of our Lord 2023 whether to eat food sacrificed to idols, or not. + +**Second**, where I live, I have no awareness of any food being presented before idols prior to being made available to anyone to buy. If you know of such practices, it would be helpful to either state a case (as an example of the pertinence of this question today) or to give a list of modern-day countries where this happens. + +**Third,** ***the simple answer to your question*** (irrespective of any time from the middle of the first century A.D. until today) ***is ""No, Christians should not.""*** The matter is known to God, even if no other human knows you have eaten food that had been offered before an idol. ***Once you know, you are culpable, and God knows.*** Christians are to do everything (including their eating and drinking) for the glory of God. But, as the passage shows, there's no need to first hold an inquisition about it, asking questions, ferreting out individuals who might be suspected of the pagan practice and checking if a particular piece of food had been handled by them. + +That section of scripture, however, has more to say on the matter than just that bit about food presented before an idol. It speaks of not eating meat that has not first been bled. But you do not ask about that, so I will end my answer here.","The rationale for Paul's advice comes from the principle in v21; ""You cannot partake of the table of the Lord and [also] of the table of demons"". + +This follows on from vv 18-20. Israel were ""partners in the altar"" (v18, RSV) when they sacrificed, in that God and the worshippers both had their own shares in most of the sacrificed animals. Conversely, those who shared in the communal sacrificial meals of other gods were ""partners with demons"" (v20). It was necessary to choose. The same choice remains for Christians in that we now share in the ""Lord's Supper"", at the table over which the Lord presides. We must choose one or the other. The point is that we must avoid sharing in the worship of other gods, by participating in the their communal meals, and we must also avoid giving other people the impression that we are particpating indirectly. + +If nobody else is involved, it seems to me that the deciding factor is what you yourself think you are doing if you get hold of meat which was previously ""dedicated"" to some other god. If you think you are participating in the original sacrificial meal, you are in the position of ch8 v7; ""Some... eat food as really offered to an idol; and their conscience, being weak, is defiled."" + +But if you are giving thanks to God for your food (ch10 v30) and are confident that its previous history doesn't affect its value in the sight of God, then you are in the position of ""liberty"" in ch8 v8; ""Food will not commend us to God"". The dictum of ch10 v25, ""Eat whatever is sold"", can still apply even if we have asked the question anyway. In other words, it makes no difference one way or the other, unless we think it makes a difference. See the principle that runs through Galatians; we are living in liberty, not under law." +81217,"If you don't know that it has been sacrificed to idols, then it is okay, +1 Corinthians 10: + +> +> 25Eat whatever is sold in the meat market **without raising any question** on the ground of conscience. +> +> +> + +Don't ask. Just eat. + +> +> 26For “the earth is the Lord’s, and the fullness thereof.” 27If one of the unbelievers invites you to dinner and you are disposed to go, eat whatever is set before you **without raising any question** on the ground of conscience. +> +> +> + +Again, don't ask. + +> +> 28But if someone says to you, “This has been offered in sacrifice,” then **do not eat it**, for the sake of the one who informed you, and for the sake of conscience— +> +> +> + +If you know that it has been sacrificed to idols, then don't eat it in front of them. + +> +> 29I do not mean your conscience, but his. For why should my liberty be determined by someone else’s conscience? 30If I partake with thankfulness, why am I denounced because of that for which I give thanks? +> +> +> + +What if you know that it has been sacrificed to idols and no one else is around, is it okay to eat?",2023/01/31,"['https://hermeneutics.stackexchange.com/questions/81217', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/35953/']","**TL;DR:** There is no reason we should care whether our food has been sacrificed to idols. + +The underlying idea here is whether one is committing idolatry, which is the belief that anything, other than God or his agents, has any supernatural power or attribute. + +Believing that a rabbit's foot provides good luck is a form of idolatry, but so is believing that food that has been sacrificed to an idol is somehow different from food that hasn't. +Neither the rabbit's foot nor the food have any supernatural attributes. + +To avoid something because it is reputed to have a non-existent attribute is equivalent to admitting that it *does* have that attribute. + +For you, it shouldn't matter at all whether the food was sacrificed, any more than you should care what the phase of the Moon is today, or what constellation was in the sky at your birth. + +But, if someone gives you something and explicitly or implicitly tells you it has supernatural attributes, *then* you should refuse it. +Not because it makes any difference to you, but because it makes a difference to the other person. +By taking it, you are implicitly endorsing and encouraging false beliefs, rather than providing the good example that every Christian should be. + +> +> But if someone says to you, “This has been offered in sacrifice,” then do not eat it, for the sake of the one who informed you, and for the sake of conscience — +> **I do not mean your conscience, but his.** For why should my liberty be determined by someone else’s conscience? +> +> +> + +Here ""conscience"" means: + +> +> as distinguishing between what is morally good and bad, prompting to do the former and shun the latter, commending the one, condemning the other +> +> +> + +Rejecting the offered food shows the other person that you are condemning the act of sacrificing to idols. + +--- + +Consider a non-religious analogy. + +You are visiting Bavaria and when the waiter pours your coffee he proudly tells you that the pot he is holding was used by Hitler himself when he visited the inn in 1942. + +What message does it send if you smile, say danke schön, and proceed to drink it? + +What message does it send if you refuse the coffee?","The rationale for Paul's advice comes from the principle in v21; ""You cannot partake of the table of the Lord and [also] of the table of demons"". + +This follows on from vv 18-20. Israel were ""partners in the altar"" (v18, RSV) when they sacrificed, in that God and the worshippers both had their own shares in most of the sacrificed animals. Conversely, those who shared in the communal sacrificial meals of other gods were ""partners with demons"" (v20). It was necessary to choose. The same choice remains for Christians in that we now share in the ""Lord's Supper"", at the table over which the Lord presides. We must choose one or the other. The point is that we must avoid sharing in the worship of other gods, by participating in the their communal meals, and we must also avoid giving other people the impression that we are particpating indirectly. + +If nobody else is involved, it seems to me that the deciding factor is what you yourself think you are doing if you get hold of meat which was previously ""dedicated"" to some other god. If you think you are participating in the original sacrificial meal, you are in the position of ch8 v7; ""Some... eat food as really offered to an idol; and their conscience, being weak, is defiled."" + +But if you are giving thanks to God for your food (ch10 v30) and are confident that its previous history doesn't affect its value in the sight of God, then you are in the position of ""liberty"" in ch8 v8; ""Food will not commend us to God"". The dictum of ch10 v25, ""Eat whatever is sold"", can still apply even if we have asked the question anyway. In other words, it makes no difference one way or the other, unless we think it makes a difference. See the principle that runs through Galatians; we are living in liberty, not under law." +81217,"If you don't know that it has been sacrificed to idols, then it is okay, +1 Corinthians 10: + +> +> 25Eat whatever is sold in the meat market **without raising any question** on the ground of conscience. +> +> +> + +Don't ask. Just eat. + +> +> 26For “the earth is the Lord’s, and the fullness thereof.” 27If one of the unbelievers invites you to dinner and you are disposed to go, eat whatever is set before you **without raising any question** on the ground of conscience. +> +> +> + +Again, don't ask. + +> +> 28But if someone says to you, “This has been offered in sacrifice,” then **do not eat it**, for the sake of the one who informed you, and for the sake of conscience— +> +> +> + +If you know that it has been sacrificed to idols, then don't eat it in front of them. + +> +> 29I do not mean your conscience, but his. For why should my liberty be determined by someone else’s conscience? 30If I partake with thankfulness, why am I denounced because of that for which I give thanks? +> +> +> + +What if you know that it has been sacrificed to idols and no one else is around, is it okay to eat?",2023/01/31,"['https://hermeneutics.stackexchange.com/questions/81217', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/35953/']","**First,** this section of scripture first appeared nearly 2,000 years ago, and was written to Christians who were surrounded by pagans who had a practice of presenting (offering) meat to their idols before taking it to the market to be sold as food. Therefore, when you ask, ""Should ***we*** eat food sacrificed to idols?"" you have jumped nearly 2,000 years to this day and age, I presume. I take it that you are asking Christians in the Year of our Lord 2023 whether to eat food sacrificed to idols, or not. + +**Second**, where I live, I have no awareness of any food being presented before idols prior to being made available to anyone to buy. If you know of such practices, it would be helpful to either state a case (as an example of the pertinence of this question today) or to give a list of modern-day countries where this happens. + +**Third,** ***the simple answer to your question*** (irrespective of any time from the middle of the first century A.D. until today) ***is ""No, Christians should not.""*** The matter is known to God, even if no other human knows you have eaten food that had been offered before an idol. ***Once you know, you are culpable, and God knows.*** Christians are to do everything (including their eating and drinking) for the glory of God. But, as the passage shows, there's no need to first hold an inquisition about it, asking questions, ferreting out individuals who might be suspected of the pagan practice and checking if a particular piece of food had been handled by them. + +That section of scripture, however, has more to say on the matter than just that bit about food presented before an idol. It speaks of not eating meat that has not first been bled. But you do not ask about that, so I will end my answer here.","Underlying the OP question is an issue of reconciling the attitude of Acts (and Revelation) with that of Paul. Acts and Revelation forbid eating food offered to idols. For Paul, the pagan deities are not real, and their idols have no power. So he says: + +> +> As to the eating of food offered to idols, we know that an idol has +> no real existence and that there is no God but one... We are no +> worse off if we do not eat, and no better off if we do. (1 Cor. 8:4,7) +> +> +> + +But Acts is quite clear that for Christians, abstaining from such for is a requirement: + +> +> For it has seemed good to the Holy Spirit and to us to lay upon you no +> greater burden than these necessary things: that you abstain from +> what has been sacrificed to idols and from blood and from what is +> strangled and from unchastity. If you keep yourselves from these, you +> will do well. (Acts 15:28-29) +> +> +> + +And the Book of Revelation condemns eating such foods in no uncertain terms: + +> +> You tolerate the woman Jez′ebel, who +> calls herself a prophetess and is teaching and beguiling my servants +> to practice immorality and to eat food sacrificed to idols. (Rev. 2:20) +> +> +> + +Paul's solution to the problem was although no food is forbidden, a person should also respect the sensitivities of believers who think the pagan deities have real power. So he says: + +> +> Only take care lest this liberty of yours somehow become a stumbling +> block to the weak. For if any one sees you, a man of knowledge, at +> table in an idol’s temple, might he not be encouraged, if his +> conscience is weak, to 'eat food offered to idols?' And so by your +> knowledge this weak man is destroyed, the brother for whom Christ +> died. Thus, sinning against your brethren and wounding their +> conscience when it is weak, you sin against Christ. Therefore, if food +> is a cause of my brother’s falling, I will never eat meat, lest I +> cause my brother to fall. (1 Cor. 8:9-13) +> +> +> + +[![Photo of a Buddhist service with food on a table along with a statue of Buddha](https://i.stack.imgur.com/cruQS.jpg ""Photo of a Buddhist service with food on a table along with a statue of Buddha"")](https://i.stack.imgur.com/cruQS.jpg ""Photo of a Buddhist service with food on a table along with a statue of Buddha"") + +In the first century, Christians had to decide whether to follow the letter of the rule given in Acts or to accept Paul's teaching that since idols have no power, we are free to eat foods offered to idols unless a fellow Christian's faith is threatened by such a thing. Today, the issue is generally moot. But when a fellow believer might be offended if I were to eat food offered to Krishna or Buddha, I need to decide whether it is a greater sin to turn down the food my host presents or to, in Paul's words, ""tempt"" fellow Christian to eat a supposedly forbidden food and thereby compromise his faith." +81217,"If you don't know that it has been sacrificed to idols, then it is okay, +1 Corinthians 10: + +> +> 25Eat whatever is sold in the meat market **without raising any question** on the ground of conscience. +> +> +> + +Don't ask. Just eat. + +> +> 26For “the earth is the Lord’s, and the fullness thereof.” 27If one of the unbelievers invites you to dinner and you are disposed to go, eat whatever is set before you **without raising any question** on the ground of conscience. +> +> +> + +Again, don't ask. + +> +> 28But if someone says to you, “This has been offered in sacrifice,” then **do not eat it**, for the sake of the one who informed you, and for the sake of conscience— +> +> +> + +If you know that it has been sacrificed to idols, then don't eat it in front of them. + +> +> 29I do not mean your conscience, but his. For why should my liberty be determined by someone else’s conscience? 30If I partake with thankfulness, why am I denounced because of that for which I give thanks? +> +> +> + +What if you know that it has been sacrificed to idols and no one else is around, is it okay to eat?",2023/01/31,"['https://hermeneutics.stackexchange.com/questions/81217', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/35953/']","**TL;DR:** There is no reason we should care whether our food has been sacrificed to idols. + +The underlying idea here is whether one is committing idolatry, which is the belief that anything, other than God or his agents, has any supernatural power or attribute. + +Believing that a rabbit's foot provides good luck is a form of idolatry, but so is believing that food that has been sacrificed to an idol is somehow different from food that hasn't. +Neither the rabbit's foot nor the food have any supernatural attributes. + +To avoid something because it is reputed to have a non-existent attribute is equivalent to admitting that it *does* have that attribute. + +For you, it shouldn't matter at all whether the food was sacrificed, any more than you should care what the phase of the Moon is today, or what constellation was in the sky at your birth. + +But, if someone gives you something and explicitly or implicitly tells you it has supernatural attributes, *then* you should refuse it. +Not because it makes any difference to you, but because it makes a difference to the other person. +By taking it, you are implicitly endorsing and encouraging false beliefs, rather than providing the good example that every Christian should be. + +> +> But if someone says to you, “This has been offered in sacrifice,” then do not eat it, for the sake of the one who informed you, and for the sake of conscience — +> **I do not mean your conscience, but his.** For why should my liberty be determined by someone else’s conscience? +> +> +> + +Here ""conscience"" means: + +> +> as distinguishing between what is morally good and bad, prompting to do the former and shun the latter, commending the one, condemning the other +> +> +> + +Rejecting the offered food shows the other person that you are condemning the act of sacrificing to idols. + +--- + +Consider a non-religious analogy. + +You are visiting Bavaria and when the waiter pours your coffee he proudly tells you that the pot he is holding was used by Hitler himself when he visited the inn in 1942. + +What message does it send if you smile, say danke schön, and proceed to drink it? + +What message does it send if you refuse the coffee?","Underlying the OP question is an issue of reconciling the attitude of Acts (and Revelation) with that of Paul. Acts and Revelation forbid eating food offered to idols. For Paul, the pagan deities are not real, and their idols have no power. So he says: + +> +> As to the eating of food offered to idols, we know that an idol has +> no real existence and that there is no God but one... We are no +> worse off if we do not eat, and no better off if we do. (1 Cor. 8:4,7) +> +> +> + +But Acts is quite clear that for Christians, abstaining from such for is a requirement: + +> +> For it has seemed good to the Holy Spirit and to us to lay upon you no +> greater burden than these necessary things: that you abstain from +> what has been sacrificed to idols and from blood and from what is +> strangled and from unchastity. If you keep yourselves from these, you +> will do well. (Acts 15:28-29) +> +> +> + +And the Book of Revelation condemns eating such foods in no uncertain terms: + +> +> You tolerate the woman Jez′ebel, who +> calls herself a prophetess and is teaching and beguiling my servants +> to practice immorality and to eat food sacrificed to idols. (Rev. 2:20) +> +> +> + +Paul's solution to the problem was although no food is forbidden, a person should also respect the sensitivities of believers who think the pagan deities have real power. So he says: + +> +> Only take care lest this liberty of yours somehow become a stumbling +> block to the weak. For if any one sees you, a man of knowledge, at +> table in an idol’s temple, might he not be encouraged, if his +> conscience is weak, to 'eat food offered to idols?' And so by your +> knowledge this weak man is destroyed, the brother for whom Christ +> died. Thus, sinning against your brethren and wounding their +> conscience when it is weak, you sin against Christ. Therefore, if food +> is a cause of my brother’s falling, I will never eat meat, lest I +> cause my brother to fall. (1 Cor. 8:9-13) +> +> +> + +[![Photo of a Buddhist service with food on a table along with a statue of Buddha](https://i.stack.imgur.com/cruQS.jpg ""Photo of a Buddhist service with food on a table along with a statue of Buddha"")](https://i.stack.imgur.com/cruQS.jpg ""Photo of a Buddhist service with food on a table along with a statue of Buddha"") + +In the first century, Christians had to decide whether to follow the letter of the rule given in Acts or to accept Paul's teaching that since idols have no power, we are free to eat foods offered to idols unless a fellow Christian's faith is threatened by such a thing. Today, the issue is generally moot. But when a fellow believer might be offended if I were to eat food offered to Krishna or Buddha, I need to decide whether it is a greater sin to turn down the food my host presents or to, in Paul's words, ""tempt"" fellow Christian to eat a supposedly forbidden food and thereby compromise his faith." +34833269,"Im trying to compare 2 Lists of the type Results, and it constantly just returns the entire list of results, it doesnt seem to filter anything out. + +This is the code : + +``` + List Veranderingen = resultaten2.Except(resultaten).ToList(); + + foreach(Results x in Veranderingen) + { + MessageBox.Show(""Nieuwe Data gevonden: "" + x.titel + ""Van de website"" + x.url + """"); + } + +``` + +The code where the lists gets filled is this ( Less important ) : + +``` + private void Lijst2invullen() + { + + OleDbConnection connection = new OleDbConnection(); + connection.ConnectionString = @""Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\martijn\Dropbox\Proftaak Periode 2 Identity\Database11.accdb; + Persist Security Info=False;""; + connection.Open(); + + OleDbCommand cmd2 = new OleDbCommand(); + cmd2.Connection = connection; + cmd2.CommandText = ""SELECT ZoekcriteriaID from Zoekcriteria WHERE ZoekCriteria = '"" + Convert.ToString(cbzoektermselecteren.Text) + ""';""; + OleDbDataReader reader2 = cmd2.ExecuteReader(); + + if (reader2.Read()) + { + refreshid2 = Convert.ToInt32(reader2[""ZoekcriteriaID""]); + } + + OleDbCommand command5 = new OleDbCommand(); + command5.Connection = connection; + command5.CommandText = ""SELECT Titel, Webadress from Resultaat WHERE ZoekcriteriaID = "" + refreshid2 + "";""; + OleDbDataReader reader3 = command5.ExecuteReader(); + + while (reader3.Read()) + { + Results result = new Results(); + result.url = Convert.ToString(reader3[""Webadress""]); + result.titel = Convert.ToString(reader3[""Titel""]); + + resultaten2.Add(result); + } + reader3.Close(); + label1.Text = ""Ziet er goed uit!""; + } + + private void Lijst1invullen() + { + OleDbConnection connection = new OleDbConnection(); + connection.ConnectionString = @""Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\martijn\Dropbox\Proftaak Periode 2 Identity\Database11.accdb; + Persist Security Info=False;""; + connection.Open(); + + OleDbCommand cmd1 = new OleDbCommand(); + cmd1.Connection = connection; + cmd1.CommandText = ""SELECT ZoekcriteriaID from Zoekcriteria WHERE ZoekCriteria = '"" + Convert.ToString(cbzoektermselecteren.Text) + ""';""; + OleDbDataReader reader1 = cmd1.ExecuteReader(); + + if (reader1.Read()) + { + refreshid = Convert.ToInt32(reader1[""ZoekcriteriaID""]); + } + + OleDbCommand command = new OleDbCommand(); + command.Connection = connection; + command.CommandText = ""SELECT Titel, Webadress from Resultaat WHERE ZoekcriteriaID = "" + refreshid + "";""; + OleDbDataReader reader = command.ExecuteReader(); + + while (reader.Read()) + { + Results result = new Results(); + result.url = Convert.ToString(reader[""Webadress""]); + result.titel = Convert.ToString(reader[""Titel""]); + + resultaten.Add(result); + } + reader.Close(); + reader1.Close(); + + OleDbCommand command2 = new OleDbCommand(); + command2.Connection = connection; + command2.CommandText = ""DELETE * FROM Resultaat WHERE ZoekcriteriaID = "" + refreshid + "";""; + command2.ExecuteNonQuery(); + + OleDbCommand command3 = new OleDbCommand(); + command3.Connection = connection; + command3.CommandText = ""DELETE * FROM Zoekcriteria WHERE ZoekCriteriaID = "" + refreshid + "";""; + command3.ExecuteNonQuery(); + + search.zoekterm = cbzoektermselecteren.Text; + search.InsertZoekcriteria(); + search.searchding(); + + } + +``` + +I think I'm doing something wrong in the syntax of the Except method could anyone help me out?",2016/01/16,"['https://Stackoverflow.com/questions/34833269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5789654/']","There are two ways to compare (for equality) two `Results` objects (and all reference type objects in general): + +* The first way is to compare the values of the properties of the two `Results` objects. +* The second way is to compare the references themselves. And by that I mean that two `Results` objects are equal if they are actually a single object but you have two references to it. For example, you can create a single `Results` object and put it in two lists. + +The objects in the two lists are clearly different objects, so I am guessing that you want to use the first way of comparison. + +By default, equality check of reference type objects in C# is of the second type. However, you can override this behavior if you want. + +One way of overriding this behavior is to override the `Equals` and `GetHashCode` methods in the class. Here is an example: + +``` +public class Results +{ + public string url { get; set; } + public string title { get; set; } + + public override bool Equals(object obj) + { + Results other = obj as Results; + + if (other == null) + return false; + + return other.url == this.url && other.title == this.title; + } + + public override int GetHashCode() + { + return new {url, title}.GetHashCode(); + } +} + +``` + +This way, we are telling the system how it should test equality for objects of this type.","I'm sure Yacoub's answer would work and is probably the preferred solution in most cases, but in case you can't modify the Results class, here is another way to do it. Define an implementation of IEqualityComparer for Results, and then pass it as the second argument of the Except method. +EDIT: + +``` +class Results { + public string FirstName { get; set; } + public string LastName { get; set; } +} + +class ResultsEqualityComparer : IEqualityComparer { + + public bool Equals(Results res1, Results res2) { + return (res1.FirstName == res2.FirstName && res1.LastName == res2.LastName); + } + + public int GetHashCode(Results res) { + return new { res.FirstName, res.LastName }.GetHashCode(); + } + +} + +``` + +// and here's the example of code passing the ResultsComparer to Except: + +``` + var resultaten = new List() { + new Results() {FirstName=""Bob"", LastName=""Smith""}, + new Results() {FirstName=""Ted"", LastName=""Wilson""}, + new Results() {FirstName=""Alice"", LastName=""Wilson""}, + new Results() {FirstName=""Carol"", LastName=""Smith""} + }; + + var resultaten2 = new List() { + new Results() {FirstName=""William"", LastName=""Smith""}, + new Results() {FirstName=""Ted"", LastName=""Wilson""}, + new Results() {FirstName=""Gerhardt"", LastName=""Wilson""}, + new Results() {FirstName=""Carol"", LastName=""Smith""} + }; + + var comparer = new ResultsEqualityComparer(); + + List Veranderingen = resultaten2.Except(resultaten, comparer).ToList(); + + foreach (var x in Veranderingen) { + Console.WriteLine(x.FirstName + "" "" + x.LastName); + } + +``` + +// prints out: +William Smith +Gerhardt Wilson" +6290013,"I have a class that takes a List in the constructor; + +``` +public class MyClass { + + private List structures; + + public MyClass(List structures) { + this.structures = structures; + } +} + +``` + +that I need to instantiate via reflection. How do I define the call to class.getConstructor() to find this? + +Regards",2011/06/09,"['https://Stackoverflow.com/questions/6290013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/497087/']","This should work: + +``` +Constructor constructor = MyClass.class.getConstructor(List.class); + +``` + +or + +``` +Constructor constructor = MyClass.class.getConstructor(new Class[]{List.class}); + +``` + +for Java 1.4.x or less","You can find it just by passing in `List.class`. For example: + +``` +import java.util.*; +import java.lang.reflect.*; + +public class Test { + public static void main(String[] args) throws Exception { + Class clazz = MyClass.class; + Constructor ctor = clazz.getConstructor(List.class); + + ctor.newInstance(new Object[] { null }); + } +} + +``` + +If you need to validate the generic parameter types, you can use [`getGenericParameterTypes`](http://download.oracle.com/javase/6/docs/api/java/lang/reflect/Constructor.html#getGenericParameterTypes%28%29) and examine the `Type[]` which it returns. For example: + +``` +Type[] types = ctor.getGenericParameterTypes(); +System.out.println(types[0]); // Prints java.util.List + +``` + +You don't need to specify the type argument when you call `getConstructor` because you can't overload the constructor by using parameters with *just* different type parameters. Those parameter types would have the same *type erasure*. For example, if you try to add another constructor with this signature: + +``` +public MyClass(List structures) + +``` + +you'll get an error like this: + +> +> MyClass.java:7: name clash: `MyClass(java.util.List)` and +> `MyClass(java.util.List)` have the same erasure +> +> +>" +15718694,"I am trying to cast varchar to bigint. Then inserting it into an int column. I found that I am not getting expected value. Then I tried the following statements: + +``` +DECLARE @varData VARCHAR(50) + +SET @varData = '0000019.33' + +select cast(@varData *cast(100 as float) as bigint) + +select cast(@varData *cast(100 as float) as varchar) + +select cast(cast(@varData *cast(100 as float) as varchar) as float) + +``` + +Results: + +``` +1932 + +1933 + +1933 + +``` + +I am not able to understand why this difference is coming. But when I change the value to `0000029.33` then there is no difference in results. + +I am stuck and do not have any idea why it's so happening. Help needed..!!!",2013/03/30,"['https://Stackoverflow.com/questions/15718694', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2227059/']","please see this [Difference between numeric,float and decimal in sql server](https://stackoverflow.com/questions/1056323/difference-between-numeric-float-and-decimal-in-sql-server) + +For you question, you should try CAST @vardata as numeric, like this + +``` +SELECT CAST(CAST(@varData AS numeric(27,9)) * 100 AS bigint) + +```","it happens because sql round the data, so lets say if u pick the wrong integer instead of 2.97 u will get 3. +now try to imagine how much data will be lost if u want to convert just 0.000002 :) +hope u understand better now + +``` +DECLARE @varData VARCHAR(50), + @float float, + @bigint bigint + +SET @varData = '0000019.33' +set @bigint = convert ( bigint, (convert ( float, @vardata )) ) +print @bigint +--or +set @float= convert ( float, @vardata ) +set @bigint=convert ( bigint, @float) +print @bigint + +```" +76907,"What's the meaning of fasts, is it only a physical deed of abstain from food and drinks? Because often in scriptures it's listed or placed in context of prayer, repentance, mourning or done to show a certain depending on HaShem. What has a physical deed of abstaining from food and drinks has to do with all of this? It helps us humble ourselves or afflict ourselves but where does this lead to, what is it's meaning to do this through fasting?",2016/10/14,"['https://judaism.stackexchange.com/questions/76907', 'https://judaism.stackexchange.com', 'https://judaism.stackexchange.com/users/4762/']","I come from the mindset that no law is strictly physical/spiritual. They blur into one another and provide benefits which merge those aspects. + +Fasting is powerful in a spiritual sense because you are choosing to take control of a baser instinct. Hunger is as basic as breathing or sleepiness, so by choosing to overrule that instinct in reflection of a spiritual observance/exercise you are strengthening your divine traits and suppressing primal traits. Torah teaches that the **Nefesh HaBehamit** ""animal soul"" is in conflict with our **Nefesh Ha'elokit** (divine soul) + +If you are interested in a more detailed explanation of the parts of the soul, you can read more in the Tanya at this link: + +**** + +These comprise two different sections of our soul which are in a battle for control. By doing spiritual exercises (such as fasting) you can drive down the animalistic urges and raise yourself to a higher state of craving. You can move from craving that which is harmful to craving that which is beneficial if you practice and focus your time/energy. Fasting is just one of those exercises. + +Fasting also has a symbolism associated with it in relation to the pain that hunger causes. When we observe **Tisha B'Av** (just one example) we fast. This holiday is a memorial in reflection various wrongs of Jewish history. One of the main reflections is on the loss of the holy temples (first and second). + +Some reading regarding Tisha B'Av and the tradition of the observance: + +**** + +This hunger pain is symbolic of the spiritual pain of our people. We sit in hunger and reflect on this pain and attach that pain to the wrongs and errors of Jewish history. By doing that, we take an impersonal history and we connect to it. I can't know what it was like to lose the holy temple because I never had the holy temple. That doesn't mean I can't reflect on what that loss has done to my ancestors and my peers of today. + +By connecting the pain of our people to a pain which is rooted in our biology, we groom ourselves to make the suffering of our past a part of who we are. That strengthens us and drives us to honor the past, make peace with the present, and overcome the trials and tribulations of the future. + +A very detailed reading regarding the purpose of fasting in relation to Judaism: + +**** + +**From a physical/scientific standpoint.** + +Fasting has been found to promote health benefits when done in a controlled manner over regulated periods of time. They recently discovered that if an individual fasts for a period of three days, their immune system resets itself. + +**** + +Your body uses the time without food to correct issues on a biological level. + +Keep in mind, these are controlled fasts which are not extended beyond this period of time. Going beyond this period of time can harm you if you withhold sustenance for too long. Our bodies need nutrition to function correctly.","Fasting is a way of attaining a more spiritual state/frame of mind by disconnecting from physical pleasures. This more spiritual state is more conducive to Teshuva. See Nesivos Olam: Nesiv Hateshuva chapter 7 (beginning from the second paragraph) and Derech Hashem part 4 chapter 8:5 (regarding Yom Kippur). + +However, today it is not recommended to fast (apart from the biblically/rabbinically mandated fasts) because it weakens the body and impairs the ability to think and learn Torah (Krina D'igrissa 1:16,17)." +76907,"What's the meaning of fasts, is it only a physical deed of abstain from food and drinks? Because often in scriptures it's listed or placed in context of prayer, repentance, mourning or done to show a certain depending on HaShem. What has a physical deed of abstaining from food and drinks has to do with all of this? It helps us humble ourselves or afflict ourselves but where does this lead to, what is it's meaning to do this through fasting?",2016/10/14,"['https://judaism.stackexchange.com/questions/76907', 'https://judaism.stackexchange.com', 'https://judaism.stackexchange.com/users/4762/']","R' Hirsch writes in Horeb that the purpose of all fast days is Teshuva, and gives the following explanation (ch. 33, Dayan Grunfeld's translation): + +> +> Fasting, i.e. abstaining from all kinds of nourishment for one day, should help in mastering the animal in man, in calling a halt to striving for self-gratification and in showing that a firm will can well remain the victor. It should also bring home the thought whether what made it possible for us to control our impulses and cravings - or, at any rate, the most pressing ones - for one day, could not make it possible for every day; and if we cannot control all such impulses, then at least we should shun the impure, the exuberant and the forbidden. Fasting, therefore, should contribute towards the eradication of one of the sources of sin, pleasure-seeking. +> +> +> + +Fasting is meant to demonstrate to ourselves the ability and purpose of not indulging in the physicality which leads to sin.","Fasting is a way of attaining a more spiritual state/frame of mind by disconnecting from physical pleasures. This more spiritual state is more conducive to Teshuva. See Nesivos Olam: Nesiv Hateshuva chapter 7 (beginning from the second paragraph) and Derech Hashem part 4 chapter 8:5 (regarding Yom Kippur). + +However, today it is not recommended to fast (apart from the biblically/rabbinically mandated fasts) because it weakens the body and impairs the ability to think and learn Torah (Krina D'igrissa 1:16,17)." +40211,"Как правильно говорить ""Ты хотел опята?"" или ""Ты хотел опят?"". Есть ли какое-то правило употребления в том или ином случае?",2014/10/08,"['https://rus.stackexchange.com/questions/40211', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4200/']","Конечно ""опят"". Мн.ч. р.п. ""Нет опят"". Ещё эти грибы во множественном числе могут называться ""опёнки"". +Ваш вопрос напомнил мне приезжих отдыхающих, которые на пляже говорят: ""Я хочу раки, а ты будешь раки?"". Это же изнасилование русского языка. + +Хотя, поразмыслив, дополню, зависит от контекста: + +Можно сказать, например: ""Я слышал, что ты проголодался. Ты хотел опят? Жаль, но они кончились"". Тут будет родительный падеж. + +А можно сказать: ""Какие грибы ты думал увидеть в лесу? Слышал, ты хотел найти опята? Извини, они тут не растут"". Тогда будет винительный падеж.","Не все так просто. +""*Ты же сама приготовила из крабов, а я так люблю **крабы**!*"" – цитата из всем известного фильма. +Чем крабы хуже опят? Люблю крабы, хочу опята... + +Думаю, что оба варианта верны. Что с крабами, что с опятами." +40211,"Как правильно говорить ""Ты хотел опята?"" или ""Ты хотел опят?"". Есть ли какое-то правило употребления в том или ином случае?",2014/10/08,"['https://rus.stackexchange.com/questions/40211', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4200/']","***""Ты хочешь опят?""*** и ***""Ты хочешь опята?""*** - оба варианта возможны. Первое сейчас употребляется много чаще. Но это частота определяется не столько даже разницей в смысле (она есть, но не четкая), сколько традицией и аналогией. + +//====== + +Попробую пояснить, хотя это довольно муторно... + +Вообще-то вопрос этот из серии ""если кит - и вдруг на слона - кто кого сборет?"" + +Глагол ""хотеть"" может управлять и родительным, и винительным падежом. + +Давайте разберемся сначала с единственным числом. + +Для одушевленных существительных падежи совпадают: *""Ты хочешь щенка?""* - и никаких вопросов не порождают. + +Для неодушевленного уже сложнее. Глагол ""хотеть"", возможно как раз под влиянием формы для одушевленных объектов, опционально изменил управление с винительного на родительный - оставаясь при этом глаголом переходным. Первая тенденция требует одной формы, второй факт - другой. ""*Ты хочешь ножик?*"" - *""Ты хочешь **о**рдена?""*. Между этими двумя случаями есть небольшая смысловая разница, грамматисты её прекрасно знают, я здесь полный разбор опускаю, ограничусь частным указанием, что первое тут означает конкретное реальное желание, второе - отдаленное, абстрактное или несбыточное. Но это не строго. + +Множественное число в принципе работает по тем же правилам, но в силу традиции частота родительного падежа сильно перевешивает. В тех же контекстах *""Ты хочешь ножиков""* будет употребляться чаще, чем *""ты хочешь ножики?""*. Возможно потому, что категория конкретности у множественного числа заметно ниже, чем у единственного. Тем не менее винительный падеж все еще вполне возможен, особенно в тех случаях, когда множественное число имеет смысловой (не грамматический!) оттенок собирательности: *""Ты хочешь помидоры?""* и *""Ты хочешь помидоров?""* равноправны. А смысловое различие идет уже не по линии ""конкретное""-""абстрактное"", а по разделу ""общее-частное"". + +Перейдем к грибам. Тоже издали. + +*""Ты хочешь (жареные) подосиновики, подберезовики, шампиньоны, маслята?""* - никаких проблем. Как блюдо, кушанье... Шампиньоны, вроде, не жарят, но с грамматикой все в порядке. + +*""Ты хочешь (жареных) подосиновиков, шампиньонов, подберезовиков, маслят?""* - тем более все ОК. Особенно, если речь идет о небольшой порции. + +С ""лисичками"" хуже. Лисичка - слово грамматически одушевленное. Поэтому форма ""лисичек"" преобладает, хотя и *""хочешь лисички?""* вполне возможна. + +Что ж такого происходит с опятами-опенками, что заставляет большинство носителей языка говорить именно *""Хочешь опят?""* вопреки всем вышевысказанным грамматическим соображениям? + +Попробуем разобраться. Как было показано, сами по себе соображения о падеже и/или одушевленности ничего не определяют. Но, как совершенно верно заметила Екатерина, ""опята"" - это форма особая. Исторически ""опята"" было неправильным, слово ""опенок"" не имеет суффикса ""-енок-"": ""-ен-"" - от ""пня"", корень - ""пен"". Это абсолютно препятствовало образованию формы ""опята"", нормативным считалось ""опенки"" - и этим они отличались от ""маслят"". Поэтому *""хочешь опенки?""* (В.п) вполне успешно конкурировало с *""хочешь опенков""* (Р.п.)- и, видимо, даже преобладало. + +Но дальше под влиянием *""масленок""-""маслята""* и т.п. де-факто произошло переразложение слова *""опенок""*, *""-енок-""* стало восприниматься как суффикс, порождающий во множественном числе новую форму ""опята"". И вот для этой-то новой формы, для которой соверешенно отсутствовала грамматическая традиция разделения родительного и винительного падежей, равно как само ощущение её неодушевленности, появилось закрепленное простой использования *""хочешь опят""* - как субъективно единственная возможная форма в обоих падежах и всех значениях. Но грамматически более правильную *""Хочешь опята?""* для винительного падежа (равно как и саму возможность использования винительного падежа для неодушевленных существительных) никто не отменял. Поэтому *""Ты хочешь опята?""* никак нельзя лишать прав на нормативность. + +И в заключение. Разговоры про форму винительного падежа для всякой снеди редко проходят мимо ставшей знаменитой у филологов фразы ""А я так люблю крабы"" из ""Иронии судьбы"". +Так вот, будьте уверены, герой Мягкова сказал все правильно. Во всяком случае - с точки зрения грамматики. + +Я здесь этим заявлением и ограничусь.","Правильно: ты хочешь/хотел опят (Р.п.). Неправильно: ты хочешь/хотел опята (В.п.) + +ПОЯСНЕНИЕ + +Ряд глаголов: хотеть, ждать, требовать, желать, просить - имеют колеблющуюся переходность. Это означает, что объект, которым управляет глагол, может употребляться в В.п.(переходный глагол) и в Р.п. (непереходный глагол). + +Винительный падеж обозначает полный охват предмета действием, а родительный падеж обозначает действие, касающееся границ предмета (отложительно-достигательное значение Р.падежа). + +Сравним: я хочу конфету (В.п., эту конкретную конфету) - я хочу конфет (Р.п., не все конфеты, которые существуют, а вообще конфет)." +40211,"Как правильно говорить ""Ты хотел опята?"" или ""Ты хотел опят?"". Есть ли какое-то правило употребления в том или ином случае?",2014/10/08,"['https://rus.stackexchange.com/questions/40211', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4200/']","Конечно ""опят"". Мн.ч. р.п. ""Нет опят"". Ещё эти грибы во множественном числе могут называться ""опёнки"". +Ваш вопрос напомнил мне приезжих отдыхающих, которые на пляж�� говорят: ""Я хочу раки, а ты будешь раки?"". Это же изнасилование русского языка. + +Хотя, поразмыслив, дополню, зависит от контекста: + +Можно сказать, например: ""Я слышал, что ты проголодался. Ты хотел опят? Жаль, но они кончились"". Тут будет родительный падеж. + +А можно сказать: ""Какие грибы ты думал увидеть в лесу? Слышал, ты хотел найти опята? Извини, они тут не растут"". Тогда будет винительный падеж.","..Падежи.. + +В данном случае - винительный." +40211,"Как правильно говорить ""Ты хотел опята?"" или ""Ты хотел опят?"". Есть ли какое-то правило употребления в том или ином случае?",2014/10/08,"['https://rus.stackexchange.com/questions/40211', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4200/']","Правильно: ***Ты хотел опят?*** + +Дело в том, что существительное ОПЯТА (ед.ОПЁНОК) не совсем обычное. Оно склоняется так же, как существительные КОТЯТА, МЕДВЕЖАТА и другие одушевлённые существительные с суффиксом -ат, ят. Существительные МАСЛЁНОК - МАСЛЯТА относятся к этой же группе. + +***Ср.: Ты видел котят. - Ты хотел опят.***","Не все так просто. +""*Ты же сама приготовила из крабов, а я так люблю **крабы**!*"" – цитата из всем известного фильма. +Чем крабы хуже опят? Люблю крабы, хочу опята... + +Думаю, что оба варианта верны. Что с крабами, что с опятами." +40211,"Как правильно говорить ""Ты хотел опята?"" или ""Ты хотел опят?"". Есть ли какое-то правило употребления в том или ином случае?",2014/10/08,"['https://rus.stackexchange.com/questions/40211', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4200/']","***""Ты хочешь опят?""*** и ***""Ты хочешь опята?""*** - оба варианта возможны. Первое сейчас употребляется много чаще. Но это частота определяется не столько даже разницей в смысле (она есть, но не четкая), сколько традицией и аналогией. + +//====== + +Попробую пояснить, хотя это довольно муторно... + +Вообще-то вопрос этот из серии ""если кит - и вдруг на слона - кто кого сборет?"" + +Глагол ""хотеть"" может управлять и родительным, и винительным падежом. + +Давайте разберемся сначала с единственным числом. + +Для одушевленных существительных падежи совпадают: *""Ты хочешь щенка?""* - и никаких вопросов не порождают. + +Для неодушевленного уже сложнее. Глагол ""хотеть"", возможно как раз под влиянием формы для одушевленных объектов, опционально изменил управление с винительного на родительный - оставаясь при этом глаголом переходным. Первая тенденция требует одной формы, второй факт - другой. ""*Ты хочешь ножик?*"" - *""Ты хочешь **о**рдена?""*. Между этими двумя случаями есть небольшая смысловая разница, грамматисты её прекрасно знают, я здесь полный разбор опускаю, ограничусь частным указанием, что первое тут означает конкретное реальное желание, второе - отдаленное, абстрактное или несбыточное. Но это не строго. + +Множественное число в принципе работает по тем же правилам, но в силу традиции частота родительного падежа сильно перевешивает. В тех же контекстах *""Ты хочешь ножиков""* будет употребляться чаще, чем *""ты хочешь ножики?""*. Возможно потому, что категория конкретности у множественного числа заметно ниже, чем у единственного. Тем не менее винительный падеж все еще вполне возможен, особенно в тех случаях, когда множественное число имеет смысловой (не грамматический!) оттенок собирательности: *""Ты хочешь помидоры?""* и *""Ты хочешь помидоров?""* равноправны. А смысловое различие идет уже не по линии ""конкретное""-""абстрактное"", а по разделу ""общее-частное"". + +Перейдем к грибам. Тоже издали. + +*""Ты хочешь (жареные) подосиновики, подберезовики, шампиньоны, маслята?""* - никаких проблем. Как блюдо, кушанье... Шампиньоны, вроде, не жарят, но с грамматикой все в порядке. + +*""Ты хочешь (жареных) подосиновиков, шампиньонов, подберезовиков, маслят?""* - тем более все ОК. Особенно, если речь идет о небольшой порции. + +С ""лисичками"" хуже. Лисичка - слово грамматически одушевленное. Поэтому форма ""лисичек"" преобладает, хотя и *""хочешь лисички?""* вполне возможна. + +Что ж такого происходит с опятами-опенками, что заставляет большинство носителей языка говорить именно *""Хочешь опят?""* вопреки всем вышевысказанным грамматическим соображениям? + +Попробуем разобраться. Как было показано, сами по себе соображения о падеже и/или одушевленности ничего не определяют. Но, как совершенно верно заметила Екатерина, ""опята"" - это форма особая. Исторически ""опята"" было неправильным, слово ""опенок"" не имеет суффикса ""-енок-"": ""-ен-"" - от ""пня"", корень - ""пен"". Это абсолютно препятствовало образованию формы ""опята"", нормативным считалось ""опенки"" - и этим они отличались от ""маслят"". Поэтому *""хочешь опенки?""* (В.п) вполне успешно конкурировало с *""хочешь опенков""* (Р.п.)- и, видимо, даже преобладало. + +Но дальше под влиянием *""масленок""-""маслята""* и т.п. де-факто произошло переразложение слова *""опенок""*, *""-енок-""* стало восприниматься как суффикс, порождающий во множественном числе новую форму ""опята"". И вот для этой-то новой формы, для которой соверешенно отсутствовала грамматическая традиция разделения родительного и винительного падежей, равно как само ощущение её неодушевленности, появилось закрепленное простой использования *""хочешь опят""* - как субъективно единственная возможная форма в обоих падежах и всех значениях. Но грамматически более правильную *""Хочешь опята?""* для винительного падежа (равно как и саму возможность использования винительного падежа для неодушевленных существительных) никто не отменял. Поэтому *""Ты хочешь опята?""* никак нельзя лишать прав на нормативность. + +И в заключение. Разговоры про форму винительного падежа для всякой снеди редко проходят мимо ставшей знаменитой у филологов фразы ""А я так люблю крабы"" из ""Иронии судьбы"". +Так вот, будьте уверены, герой Мягкова сказал все правильно. Во всяком случае - с точки зрения грамматики. + +Я здесь этим заявлением и ограничусь.","..Падежи.. + +В данном случае - винительный." +40211,"Как правильно говорить ""Ты хотел опята?"" или ""Ты хотел опят?"". Есть ли какое-то правило употребления в том или ином случае?",2014/10/08,"['https://rus.stackexchange.com/questions/40211', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4200/']","Правильно: ты хочешь/хотел опят (Р.п.). Неправильно: ты хочешь/хотел опята (В.п.) + +ПОЯСНЕНИЕ + +Ряд глаголов: хотеть, ждать, требовать, желать, просить - имеют колеблющуюся переходность. Это означает, что объект, которым управляет глагол, может употребляться в В.п.(переходный глагол) и в Р.п. (непереходный глагол). + +Винительный падеж обозначает полный охват предмета действием, а родительный падеж обозначает действие, касающееся границ предмета (отложительно-достигательное значение Р.падежа). + +Сравним: я хочу конфету (В.п., эту конкретную конфету) - я хочу конфет (Р.п., не все конфеты, которые существуют, а вообще конфет).","..Падежи.. + +В данном случае - винительный." +40211,"Как правильно говорить ""Ты хотел опята?"" или ""Ты хотел опят?"". Есть ли какое-то правило употребления в том или ином случае?",2014/10/08,"['https://rus.stackexchange.com/questions/40211', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4200/']","Не все так просто. +""*Ты же сама приготовила из крабов, а я так люблю **крабы**!*"" – цитата из всем известного фильма. +Чем крабы хуже опят? Люблю крабы, хочу опята... + +Думаю, что оба варианта верны. Что с крабами, что с опятами.","..Падежи.. + +В данном случае - винительный." +40211,"Как правильно говорить ""Ты хотел опята?"" или ""Ты хотел опят?"". Есть ли какое-то правило употребления в том или ином случае?",2014/10/08,"['https://rus.stackexchange.com/questions/40211', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4200/']","Правильно: ***Ты хотел опят?*** + +Дело в том, что существительное ОПЯТА (ед.ОПЁНОК) не совсем обычное. Оно склоняется так же, как существительные КОТЯТА, МЕДВЕЖАТА и другие одушевлённые существительные с суффиксом -ат, ят. Существительные МАСЛЁНОК - МАСЛЯТА относятся к этой же группе. + +***Ср.: Ты видел котят. - Ты хотел опят.***","Правильно: ты хочешь/хотел опят (Р.п.). Неправильно: ты хочешь/хотел опята (В.п.) + +ПОЯСНЕНИЕ + +Ряд глаголов: хотеть, ждать, требовать, желать, просить - имеют колеблющуюся переходность. Это означает, что объект, которым управляет глагол, может употребляться в В.п.(переходный глагол) и в Р.п. (непереходный глагол). + +Винительный падеж обозначает полный охват предмета действием, а родительный падеж обозначает действие, касающееся границ предмета (отложительно-достигательное значение Р.падежа). + +Сравним: я хочу конфету (В.п., эту конкретную конфету) - я хочу конфет (Р.п., не все конфеты, которые существуют, а вообще конфет)." +40211,"Как правильно говорить ""Ты хотел опята?"" или ""Ты хотел опят?"". Есть ли какое-то правило употребления в том или ином случае?",2014/10/08,"['https://rus.stackexchange.com/questions/40211', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4200/']","Конечно ""опят"". Мн.ч. р.п. ""Нет опят"". Ещё эти грибы во множественном числе могут называться ""опёнки"". +Ваш вопрос напомнил мне приезжих отдыхающих, которые на пляже говорят: ""Я хочу раки, а ты будешь раки?"". Это же изнасилование русского языка. + +Хотя, поразмыслив, дополню, зависит от контекста: + +Можно сказать, например: ""Я слышал, что ты проголодался. Ты хотел опят? Жаль, но они кончились"". Тут будет родительный падеж. + +А можно сказать: ""Какие грибы ты думал увидеть в лесу? Слышал, ты хотел найти опята? Извини, они тут не растут"". Тогда будет винительный падеж.","Правильно: ты хочешь/хотел опят (Р.п.). Неправильно: ты хочешь/хотел опята (В.п.) + +ПОЯСНЕНИЕ + +Ряд глаголов: хотеть, ждать, требовать, желать, просить - имеют колеблющуюся переходность. Это означает, что объект, которым управляет глагол, может употребляться в В.п.(переходный глагол) и в Р.п. (непереходный глагол). + +Винительный падеж обозначает полный охват предмета действием, а родительный падеж обозначает действие, касающееся границ предмета (отложительно-достигательное значение Р.падежа). + +Сравним: я хочу конфету (В.п., эту конкретную конфету) - я хочу конфет (Р.п., не все конфеты, которые существуют, а вообще конфет)." +40211,"Как правильно говорить ""Ты хотел опята?"" или ""Ты хотел опят?"". Есть ли какое-то правило употребления в том или ином случае?",2014/10/08,"['https://rus.stackexchange.com/questions/40211', 'https://rus.stackexchange.com', 'https://rus.stackexchange.com/users/4200/']","***""Ты хочешь опят?""*** и ***""Ты хочешь опята?""*** - оба варианта возможны. Первое сейчас употребляется много чаще. Но это частота определяется не столько даже разницей в смысле (она есть, но не четкая), сколько традицией и аналогией. + +//====== + +Попробую пояснить, хотя это довольно муторно... + +Вообще-то вопрос этот из серии ""если кит - и вдруг на слона - кто кого сборет?"" + +Глагол ""хотеть"" может управлять и родительным, и винительным падежом. + +Давайте разберемся сначала с единственным числом. + +Для одушевленных существительных падежи совпадают: *""Ты хочешь щенка?""* - и никаких вопросов не порождают. + +Для неодушевленного уже сложнее. Глагол ""хотеть"", возможно как раз под влиянием формы для одушевленных объектов, опционально изменил управление с винительного на родительный - оставаясь при этом глаголом переходным. Первая тенденция требует одной формы, второй факт - другой. ""*Ты хочешь ножик?*"" - *""Ты хочешь **о**рдена?""*. Между этими двумя случаями есть небольшая смысловая разница, грамматисты её прекрасно знают, я здесь полный разбор опускаю, ограничусь частным указанием, что первое тут означает конкретное реальное желание, второе - отдаленное, абстрактное или несбыточное. Но это не строго. + +Множественное число в принципе работает по тем же правилам, но в силу традиции частота родительного падежа сильно перевешивает. В тех же контекстах *""Ты хочешь ножиков""* будет употребляться чаще, чем *""ты хочешь ножики?""*. Возможно потому, что категория конкретности у множественного числа зам��тно ниже, чем у единственного. Тем не менее винительный падеж все еще вполне возможен, особенно в тех случаях, когда множественное число имеет смысловой (не грамматический!) оттенок собирательности: *""Ты хочешь помидоры?""* и *""Ты хочешь помидоров?""* равноправны. А смысловое различие идет уже не по линии ""конкретное""-""абстрактное"", а по разделу ""общее-частное"". + +Перейдем к грибам. Тоже издали. + +*""Ты хочешь (жареные) подосиновики, подберезовики, шампиньоны, маслята?""* - никаких проблем. Как блюдо, кушанье... Шампиньоны, вроде, не жарят, но с грамматикой все в порядке. + +*""Ты хочешь (жареных) подосиновиков, шампиньонов, подберезовиков, маслят?""* - тем более все ОК. Особенно, если речь идет о небольшой порции. + +С ""лисичками"" хуже. Лисичка - слово грамматически одушевленное. Поэтому форма ""лисичек"" преобладает, хотя и *""хочешь лисички?""* вполне возможна. + +Что ж такого происходит с опятами-опенками, что заставляет большинство носителей языка говорить именно *""Хочешь опят?""* вопреки всем вышевысказанным грамматическим соображениям? + +Попробуем разобраться. Как было показано, сами по себе соображения о падеже и/или одушевленности ничего не определяют. Но, как совершенно верно заметила Екатерина, ""опята"" - это форма особая. Исторически ""опята"" было неправильным, слово ""опенок"" не имеет суффикса ""-енок-"": ""-ен-"" - от ""пня"", корень - ""пен"". Это абсолютно препятствовало образованию формы ""опята"", нормативным считалось ""опенки"" - и этим они отличались от ""маслят"". Поэтому *""хочешь опенки?""* (В.п) вполне успешно конкурировало с *""хочешь опенков""* (Р.п.)- и, видимо, даже преобладало. + +Но дальше под влиянием *""масленок""-""маслята""* и т.п. де-факто произошло переразложение слова *""опенок""*, *""-енок-""* стало восприниматься как суффикс, порождающий во множественном числе новую форму ""опята"". И вот для этой-то новой формы, для которой соверешенно отсутствовала грамматическая традиция разделения родительного и винительного падежей, равно как само ощущение её неодушевленности, появилось закрепленное простой использования *""хочешь опят""* - как субъективно единственная возможная форма в обоих падежах и всех значениях. Но грамматически более правильную *""Хочешь опята?""* для винительного падежа (равно как и саму возможность использования винительного падежа для неодушевленных существительных) никто не отменял. Поэтому *""Ты хочешь опята?""* никак нельзя лишать прав на нормативность. + +И в заключение. Разговоры про форму винительного падежа для всякой снеди редко проходят мимо ставшей знаменитой у филологов фразы ""А я так люблю крабы"" из ""Иронии судьбы"". +Так вот, будьте уверены, герой Мягкова сказал все правильно. Во всяком случае - с точки зрения грамматики. + +Я здесь этим заявлением и ограничусь.","Не все так просто. +""*Ты же сама приготовила из крабов, а я так люблю **крабы**!*"" – цитата ��з всем известного фильма. +Чем крабы хуже опят? Люблю крабы, хочу опята... + +Думаю, что оба варианта верны. Что с крабами, что с опятами." +14749629,"``` + + +``` + +above stylesheet is enclosed in `` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like which I think is very valid reference)",2013/02/07,"['https://Stackoverflow.com/questions/14749629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1684670/']",This is done to avoid displaying the script content in some (old) browsers which don't know about ` + +``` + +above stylesheet is enclosed in `` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like which I think is very valid reference)",2013/02/07,"['https://Stackoverflow.com/questions/14749629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1684670/']","that's not a comment... it's a way to hide such text block from old browsers parser (mainly IE6-) + +It's the same as using the [CDATA](http://en.wikipedia.org/wiki/CDATA) technique on the ` + +``` + +using `CDATA` in both cases is the **correct and safe way**, the *comment* way it's just a trick to accomplish the same end result. + +--- + +Now, regarding your **I think is very valid reference** when pointing out W3Schools, have a look at this: + +> +> +> +> +>",This is done to avoid displaying the script content in some (old) browsers which don't know about ` + +``` + +above stylesheet is enclosed in `` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like which I think is very valid reference)",2013/02/07,"['https://Stackoverflow.com/questions/14749629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1684670/']","It is an antiquated method of hiding content from browsers who are older than the standard that introduced ` + +``` + +above stylesheet is enclosed in `` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like which I think is very valid reference)",2013/02/07,"['https://Stackoverflow.com/questions/14749629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1684670/']",It's a hack for older browsers that didn't support CSS/style tag... See ,Few browsers consider the `non-HTML` codes as plain text. This comment is used to guide that browser i.e the code is commented so that `browsers` will not display it as html output. +14749629,"``` + + +``` + +above stylesheet is enclosed in `` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like which I think is very valid reference)",2013/02/07,"['https://Stackoverflow.com/questions/14749629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1684670/']","that's not a comment... it's a way to hide such text block from old browsers parser (mainly IE6-) + +It's the same as using the [CDATA](http://en.wikipedia.org/wiki/CDATA) technique on the ` + +``` + +using `CDATA` in both cases is the **correct and safe way**, the *comment* way it's just a trick to accomplish the same end result. + +--- + +Now, regarding your **I think is very valid reference** when pointing out W3Schools, have a look at this: + +> +> +> +> +>",Few browsers consider the `non-HTML` codes as plain text. This comment is used to guide that browser i.e the code is commented so that `browsers` will not display it as html output. +14749629,"``` + + +``` + +above stylesheet is enclosed in `` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like which I think is very valid reference)",2013/02/07,"['https://Stackoverflow.com/questions/14749629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1684670/']","It is an antiquated method of hiding content from browsers who are older than the standard that introduced ` + +``` + +above stylesheet is enclosed in `` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like which I think is very valid reference)",2013/02/07,"['https://Stackoverflow.com/questions/14749629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1684670/']","that's not a comment... it's a way to hide such text block from old browsers parser (mainly IE6-) + +It's the same as using the [CDATA](http://en.wikipedia.org/wiki/CDATA) technique on the ` + +``` + +using `CDATA` in both cases is the **correct and safe way**, the *comment* way it's just a trick to accomplish the same end result. + +--- + +Now, regarding your **I think is very valid reference** when pointing out W3Schools, have a look at this: + +> +> +> +> +>",It's a hack for older browsers that didn't support CSS/style tag... See +14749629,"``` + + +``` + +above stylesheet is enclosed in `` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like which I think is very valid reference)",2013/02/07,"['https://Stackoverflow.com/questions/14749629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1684670/']","It is an antiquated method of hiding content from browsers who are older than the standard that introduced ` + +``` + +above stylesheet is enclosed in `` html comments tag. why? I can't get valid explanation for this; some tutorials do this while some doesn't (like which I think is very valid reference)",2013/02/07,"['https://Stackoverflow.com/questions/14749629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1684670/']","that's not a comment... it's a way to hide such text block from old browsers parser (mainly IE6-) + +It's the same as using the [CDATA](http://en.wikipedia.org/wiki/CDATA) technique on the ` + +``` + +using `CDATA` in both cases is the **correct and safe way**, the *comment* way it's just a trick to accomplish the same end result. + +--- + +Now, regarding your **I think is very valid reference** when pointing out W3Schools, have a look at this: + +> +> +> +> +>","It is an antiquated method of hiding content from browsers who are older than the standard that introduced ` + + +
+
+ +"" . ""File "". $_FILES['filename']['name'] ."" uploaded successfully."" . """"; + echo ""

Displaying contents:

""; + readfile($_FILES['filename']['tmp_name']); + } + + //Import uploaded file to Database + $handle = fopen($_FILES['filename']['tmp_name'], ""r""); + + while (($data = fgetcsv($handle, 1000, "","")) !== FALSE) { + $import=""INSERT into tablename(item1,item2,item3,item4,item5) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')""; + + mysql_query($import) or die(mysql_error()); + } + + fclose($handle); + + print ""Import done""; + + //view upload form +}else { + + print ""Upload new csv by browsing to file and clicking on Upload
\n""; + + print ""
""; + + print ""File name to import:
\n""; + + print ""
\n""; + + print ""
""; + +} + +?> + +
+
+ + + +```" +36251112,"I have a list of files: + +``` +PS S:\temp> dir + + Directory: S:\temp + +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 3/28/2016 2:07 AM 0 00001_asdfasdfsa df.txt +-a--- 3/28/2016 2:07 AM 0 00002_asdfasdfsa df - Copy (3).txt +-a--- 3/28/2016 2:07 AM 0 00003_asdfasdfsa df - Copy.txt +-a--- 3/28/2016 2:07 AM 0 00004_asdfasdfsa df - Copy (6).txt +-a--- 3/28/2016 2:07 AM 0 00005_asdfasdfsa df - Copy (5).txt +-a--- 3/28/2016 2:07 AM 0 00006_asdfasdfsa df - Copy (4).txt +-a--- 3/28/2016 2:07 AM 0 00007_asdfasdfsa df - Copy (2).txt +-a--- 3/28/2016 2:07 AM 0 700006_asdfasdfsa df - Copy (4) - Copy.txt + +PS S:\temp> + +``` + +I want to renamem those that start with five numbers and an underline. The new name will add a number I specified to the leading numbers of those file names. For example, if I add 10, the new names would be: + +``` +PS S:\temp> dir + + Directory: S:\temp + +Mode LastWriteTime Length Name +---- ------------- ------ ---- +-a--- 3/28/2016 2:07 AM 0 00011_asdfasdfsa df.txt +-a--- 3/28/2016 2:07 AM 0 00012_asdfasdfsa df - Copy (3).txt +-a--- 3/28/2016 2:07 AM 0 00013_asdfasdfsa df - Copy.txt +-a--- 3/28/2016 2:07 AM 0 00014_asdfasdfsa df - Copy (6).txt +-a--- 3/28/2016 2:07 AM 0 00015_asdfasdfsa df - Copy (5).txt +-a--- 3/28/2016 2:07 AM 0 00016_asdfasdfsa df - Copy (4).txt +-a--- 3/28/2016 2:07 AM 0 00017_asdfasdfsa df - Copy (2).txt +-a--- 3/28/2016 2:07 AM 0 700006_asdfasdfsa df - Copy (4) - Copy.txt + +PS S:\temp> + +``` + +Now my PowerShell code is: + +``` +dir * | ?{$_.name -match '^\d{5}_.+'} | Rename-Item -NewName {$_.name -replace '^(\d{5})(_.+)', ((([convert]::ToInt32('$1', 10) + 12).ToString(""00000"")) + '$2')} -whatif + +``` + +I can't find any errors in my code. But when I run it, I got the following error message: + +``` +Rename-Item : The input to the script block for parameter 'NewName' failed. Exception calling ""ToInt32"" with ""2"" argument(s): ""Could not find any recognizable digits."" +At line:1 char:62 ++ dir * | ?{$_.name -match '^\d{5}_.+'} | Rename-Item -NewName {$_.name -replace ' ... ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + CategoryInfo : InvalidArgument: (S:\temp\00001_asdfasdfsa df.txt:PSObject) [Rename-Item], ParameterBindingException + + FullyQualifiedErrorId : ScriptBlockArgumentInvocationFailed,Microsoft.PowerShell.Commands.RenameItemCommand + +``` + +My question is, where I am wrong? Is it because I should not use functions in the replacement part of the `replace` operator? If so, how to write complex logic in `-newname{}`? Thanks.",2016/03/27,"['https://Stackoverflow.com/questions/36251112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170931/']","You cannot use `-replace` and massage the data at the time of the substitution. Your replacement was failing as the string literal `$1` cannot be converted to integer. As discussed in a similar question: [Passing a function to Powershell's (replace) function](https://stackoverflow.com/questions/8163061/passing-a-function-to-powershells-replace-function) you can use a scriptblock and the .nNet regex static method `Replace`. + +``` +$replaceBlock = { + # Groups 0 contains the whole match. 1 is the first group... and so on. + ([convert]::ToInt32($args[0].Groups[1],10) + 12).ToString(""00000"") + $args[0].Groups[2] +} + +Get-ChildItem | Where-Object{$_.name -match '^\d{5}_.+'} | Rename-Item -NewName { + [Regex]::Replace($_.name, '^(\d{5})(_.+)', $replaceBlock) +} -whatif + +``` + +You can use the script block inline but getting it out makes for a little cleaner code. However I would likely use `-match` and the returned `$matches` object to do the same thing. + +``` +Get-ChildItem | Where-Object{$_.name -match '^(\d{5})(_.+)'} | Rename-Item -NewName { + ([int]$Matches[1] + 12).ToString(""00000"") + $Matches[2] +} -whatif + +``` + +Note that I updated the `where-object` to have capture groups.","Haha, I got an answer. + +``` +dir * | ?{$_.name -match '^\d{5}_.+'} | Rename-Item -NewName {(([convert]::toint32($_.name.substring(0, 5), 10) + 12).ToString(""00000"")) + $_.name.substring(5)} -whatif + +``` + +Just found that I can use any code in the `-newname{}` block. But I still don't understand why my `-replace` way did not work." +25457631,"Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image. + +But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image. + +And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why. + +![enter image description here](https://i.stack.imgur.com/I325u.png) + +Do you know how can I have an effect like this my image below? + +![enter image description here](https://i.stack.imgur.com/kL9DV.png) + +**I forget to create a fiddle with my issue:** + +**My Html:** + +``` +
+

Title of news

+ 20/10/2014
+ +

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.

+
+
+

Links

+
    +
  • Link 1
  • +
  • Link 2
  • http://jsfiddle.net/#tidy +
  • Link 3
  • +
+
+
+ +```",2014/08/23,"['https://Stackoverflow.com/questions/25457631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026353/']",Just add **float:right; position:relative** for your paragraph and adjust the width of paragraph if it is positioning below the image.,Add `overflow:hidden` to your paragraph’s formatting. +25457631,"Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image. + +But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image. + +And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why. + +![enter image description here](https://i.stack.imgur.com/I325u.png) + +Do you know how can I have an effect like this my image below? + +![enter image description here](https://i.stack.imgur.com/kL9DV.png) + +**I forget to create a fiddle with my issue:** + +**My Html:** + +``` +
+

Title of news

+ 20/10/2014
+ +

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.

+
+
+

Links

+
    +
  • Link 1
  • +
  • Link 2
  • http://jsfiddle.net/#tidy +
  • Link 3
  • +
+
+
+ +```",2014/08/23,"['https://Stackoverflow.com/questions/25457631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026353/']","You can set the left margin of `

` equal to the width of the image + +html + +``` + +

...

+ +``` + +css + +``` +img { + float: left; + width: 100px; +} + +p { + margin-left: 100px; +} + +```",Add `overflow:hidden` to your paragraph’s formatting. +25457631,"Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image. + +But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image. + +And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why. + +![enter image description here](https://i.stack.imgur.com/I325u.png) + +Do you know how can I have an effect like this my image below? + +![enter image description here](https://i.stack.imgur.com/kL9DV.png) + +**I forget to create a fiddle with my issue:** + +**My Html:** + +``` +
+

Title of news

+ 20/10/2014
+ +

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.

+
+
+

Links

+
    +
  • Link 1
  • +
  • Link 2
  • http://jsfiddle.net/#tidy +
  • Link 3
  • +
+
+
+ +```",2014/08/23,"['https://Stackoverflow.com/questions/25457631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026353/']","DEMO: +------------------------------------- + +Uses box-sizing:border-box, padding and negative margin. Assumes, as in the OP, that the image is fixed to 200px wide, which means with a 5px border, you add the actual width you want it since border-box includes the borders and padding. Regarding the gap below it on the other screen shot, if you change your paragraph line-height to 24px, it won't be there or you can manipulate the image height. Google vertical rhythm and images. + +![enter image description here](https://i.stack.imgur.com/KfA5P.png) + +``` +.modal .img { + width:210px; + height:230px; + border:5px solid #f3f3f3; + margin:18px -220px 0 0; + box-sizing:border-box; + float:left; +} + +.modal p{ + box-sizing:border-box; + font-size: 16px; + text-align:left; + line-height:25px; + float:left; + padding:0 10px 0 230px; +} + +```","You can set the left margin of `

` equal to the width of the image + +html + +``` + +

...

+ +``` + +css + +``` +img { + float: left; + width: 100px; +} + +p { + margin-left: 100px; +} + +```" +25457631,"Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image. + +But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image. + +And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why. + +![enter image description here](https://i.stack.imgur.com/I325u.png) + +Do you know how can I have an effect like this my image below? + +![enter image description here](https://i.stack.imgur.com/kL9DV.png) + +**I forget to create a fiddle with my issue:** + +**My Html:** + +``` +
+

Title of news

+ 20/10/2014
+ +

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.

+
+
+

Links

+
    +
  • Link 1
  • +
  • Link 2
  • http://jsfiddle.net/#tidy +
  • Link 3
  • +
+
+
+ +```",2014/08/23,"['https://Stackoverflow.com/questions/25457631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026353/']","DEMO: +------------------------------------- + +Uses box-sizing:border-box, padding and negative margin. Assumes, as in the OP, that the image is fixed to 200px wide, which means with a 5px border, you add the actual width you want it since border-box includes the borders and padding. Regarding the gap below it on the other screen shot, if you change your paragraph line-height to 24px, it won't be there or you can manipulate the image height. Google vertical rhythm and images. + +![enter image description here](https://i.stack.imgur.com/KfA5P.png) + +``` +.modal .img { + width:210px; + height:230px; + border:5px solid #f3f3f3; + margin:18px -220px 0 0; + box-sizing:border-box; + float:left; +} + +.modal p{ + box-sizing:border-box; + font-size: 16px; + text-align:left; + line-height:25px; + float:left; + padding:0 10px 0 230px; +} + +```","You could wrap the paragraph in a div tag: + +``` + +

...

+ +``` + +Then you could set the div to a width of 100% - width of image and float it to the right. + +``` +img { + float: left; + width: 20%; +} +div { + display: block; + width: 80%; + float: right; +} + +``` + +It would look like this: +" +25457631,"Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image. + +But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image. + +And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why. + +![enter image description here](https://i.stack.imgur.com/I325u.png) + +Do you know how can I have an effect like this my image below? + +![enter image description here](https://i.stack.imgur.com/kL9DV.png) + +**I forget to create a fiddle with my issue:** + +**My Html:** + +``` +
+

Title of news

+ 20/10/2014
+ +

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.

+
+
+

Links

+
    +
  • Link 1
  • +
  • Link 2
  • http://jsfiddle.net/#tidy +
  • Link 3
  • +
+
+
+ +```",2014/08/23,"['https://Stackoverflow.com/questions/25457631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026353/']","You could wrap the paragraph in a div tag: + +``` + +

...

+ +``` + +Then you could set the div to a width of 100% - width of image and float it to the right. + +``` +img { + float: left; + width: 20%; +} +div { + display: block; + width: 80%; + float: right; +} + +``` + +It would look like this: +",Add `overflow:hidden` to your paragraph’s formatting. +25457631,"Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image. + +But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image. + +And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why. + +![enter image description here](https://i.stack.imgur.com/I325u.png) + +Do you know how can I have an effect like this my image below? + +![enter image description here](https://i.stack.imgur.com/kL9DV.png) + +**I forget to create a fiddle with my issue:** + +**My Html:** + +``` +
+

Title of news

+ 20/10/2014
+ +

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.

+
+
+

Links

+
    +
  • Link 1
  • +
  • Link 2
  • http://jsfiddle.net/#tidy +
  • Link 3
  • +
+
+
+ +```",2014/08/23,"['https://Stackoverflow.com/questions/25457631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026353/']","DEMO: +------------------------------------- + +Uses box-sizing:border-box, padding and negative margin. Assumes, as in the OP, that the image is fixed to 200px wide, which means with a 5px border, you add the actual width you want it since border-box includes the borders and padding. Regarding the gap below it on the other screen shot, if you change your paragraph line-height to 24px, it won't be there or you can manipulate the image height. Google vertical rhythm and images. + +![enter image description here](https://i.stack.imgur.com/KfA5P.png) + +``` +.modal .img { + width:210px; + height:230px; + border:5px solid #f3f3f3; + margin:18px -220px 0 0; + box-sizing:border-box; + float:left; +} + +.modal p{ + box-sizing:border-box; + font-size: 16px; + text-align:left; + line-height:25px; + float:left; + padding:0 10px 0 230px; +} + +```",Just add **float:right; position:relative** for your paragraph and adjust the width of paragraph if it is positioning below the image. +25457631,"Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image. + +But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image. + +And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why. + +![enter image description here](https://i.stack.imgur.com/I325u.png) + +Do you know how can I have an effect like this my image below? + +![enter image description here](https://i.stack.imgur.com/kL9DV.png) + +**I forget to create a fiddle with my issue:** + +**My Html:** + +``` +
+

Title of news

+ 20/10/2014
+ +

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.

+
+
+

Links

+
    +
  • Link 1
  • +
  • Link 2
  • http://jsfiddle.net/#tidy +
  • Link 3
  • +
+
+
+ +```",2014/08/23,"['https://Stackoverflow.com/questions/25457631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026353/']","DEMO: +------------------------------------- + +Uses box-sizing:border-box, padding and negative margin. Assumes, as in the OP, that the image is fixed to 200px wide, which means with a 5px border, you add the actual width you want it since border-box includes the borders and padding. Regarding the gap below it on the other screen shot, if you change your paragraph line-height to 24px, it won't be there or you can manipulate the image height. Google vertical rhythm and images. + +![enter image description here](https://i.stack.imgur.com/KfA5P.png) + +``` +.modal .img { + width:210px; + height:230px; + border:5px solid #f3f3f3; + margin:18px -220px 0 0; + box-sizing:border-box; + float:left; +} + +.modal p{ + box-sizing:border-box; + font-size: 16px; + text-align:left; + line-height:25px; + float:left; + padding:0 10px 0 230px; +} + +```","Add a div for your image in html file and add this in your css + +``` + #image{ + width:210px; + height:1000px; + float:left; + } + +```" +25457631,"Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image. + +But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image. + +And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why. + +![enter image description here](https://i.stack.imgur.com/I325u.png) + +Do you know how can I have an effect like this my image below? + +![enter image description here](https://i.stack.imgur.com/kL9DV.png) + +**I forget to create a fiddle with my issue:** + +**My Html:** + +``` +
+

Title of news

+ 20/10/2014
+ +

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.

+
+
+

Links

+
    +
  • Link 1
  • +
  • Link 2
  • http://jsfiddle.net/#tidy +
  • Link 3
  • +
+
+
+ +```",2014/08/23,"['https://Stackoverflow.com/questions/25457631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026353/']","DEMO: +------------------------------------- + +Uses box-sizing:border-box, padding and negative margin. Assumes, as in the OP, that the image is fixed to 200px wide, which means with a 5px border, you add the actual width you want it since border-box includes the borders and padding. Regarding the gap below it on the other screen shot, if you change your paragraph line-height to 24px, it won't be there or you can manipulate the image height. Google vertical rhythm and images. + +![enter image description here](https://i.stack.imgur.com/KfA5P.png) + +``` +.modal .img { + width:210px; + height:230px; + border:5px solid #f3f3f3; + margin:18px -220px 0 0; + box-sizing:border-box; + float:left; +} + +.modal p{ + box-sizing:border-box; + font-size: 16px; + text-align:left; + line-height:25px; + float:left; + padding:0 10px 0 230px; +} + +```",Add `overflow:hidden` to your paragraph’s formatting. +25457631,"Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image. + +But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image. + +And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why. + +![enter image description here](https://i.stack.imgur.com/I325u.png) + +Do you know how can I have an effect like this my image below? + +![enter image description here](https://i.stack.imgur.com/kL9DV.png) + +**I forget to create a fiddle with my issue:** + +**My Html:** + +``` +
+

Title of news

+ 20/10/2014
+ +

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.

+
+
+

Links

+
    +
  • Link 1
  • +
  • Link 2
  • http://jsfiddle.net/#tidy +
  • Link 3
  • +
+
+
+ +```",2014/08/23,"['https://Stackoverflow.com/questions/25457631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026353/']",Just add **float:right; position:relative** for your paragraph and adjust the width of paragraph if it is positioning below the image.,"Add a div for your image in html file and add this in your css + +``` + #image{ + width:210px; + height:1000px; + float:left; + } + +```" +25457631,"Im having a problem with my css, when my paragraph is long, I want that my text continues aligned with my test that are alongside the image. + +But Im not having this, Im having my text to go left when it exceeds the image height, as you see in my image. + +And also, I'm having a blank space, marked by the circle in my picture below, and I'm not understand why. + +![enter image description here](https://i.stack.imgur.com/I325u.png) + +Do you know how can I have an effect like this my image below? + +![enter image description here](https://i.stack.imgur.com/kL9DV.png) + +**I forget to create a fiddle with my issue:** + +**My Html:** + +``` +
+

Title of news

+ 20/10/2014
+ +

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ""de Finibus Bonorum et Malorum"" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, ""Lorem ipsum dolor sit amet.."", comes from a line in section 1.10.32.

+
+
+

Links

+
    +
  • Link 1
  • +
  • Link 2
  • http://jsfiddle.net/#tidy +
  • Link 3
  • +
+
+
+ +```",2014/08/23,"['https://Stackoverflow.com/questions/25457631', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3026353/']","You could wrap the paragraph in a div tag: + +``` + +

...

+ +``` + +Then you could set the div to a width of 100% - width of image and float it to the right. + +``` +img { + float: left; + width: 20%; +} +div { + display: block; + width: 80%; + float: right; +} + +``` + +It would look like this: +","Add a div for your image in html file and add this in your css + +``` + #image{ + width:210px; + height:1000px; + float:left; + } + +```" +1860155,"If the name is like ""david"" it comes within the allotted space.... +but if the name is like ""john pal abraham desouza"" the allotted space increases automatically.. + +So i need to have the name occupied in the allotted space by auto resizing the font.. +Suggest me a solution..",2009/12/07,"['https://Stackoverflow.com/questions/1860155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174796/']","It sounds to me like what you want to do is roll your own Custom .NET Membership Provider. + +It will allow you to use the built-in ASP.NET Authentication/Authorization attributes on your Controller Actions while giving you complete control over the implementation inside the provider (which will allow you to code it to meet the requirements stated above). + +Direct from MSDN... + +[Implementing a Membership Provider](http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx)","If you go ahead and create your own custom solution, you will have a better idea of how difficult it is and what features you want. This will help you to evaluate off-the-shelf solutions for future projects. + +OTOH, spending time developing functionality that is already readily available means you won't be spending that time working on the major functionality of your project. Unless authentication and authorization are a major component of your project, you might consider investing your time, and expanding your knowledge, in another area." +1860155,"If the name is like ""david"" it comes within the allotted space.... +but if the name is like ""john pal abraham desouza"" the allotted space increases automatically.. + +So i need to have the name occupied in the allotted space by auto resizing the font.. +Suggest me a solution..",2009/12/07,"['https://Stackoverflow.com/questions/1860155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174796/']","It sounds to me like what you want to do is roll your own Custom .NET Membership Provider. + +It will allow you to use the built-in ASP.NET Authentication/Authorization attributes on your Controller Actions while giving you complete control over the implementation inside the provider (which will allow you to code it to meet the requirements stated above). + +Direct from MSDN... + +[Implementing a Membership Provider](http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx)","I think you recognize where the thin parts in your consideration are: namely in that you've included how to do what you're doing as motive in why you're doing it and the NIH (funny: I'd never seen that before) issue. + +Putting those aside, your provider is something that you could potentially reuse and it may simplify some of your future efforts. It should also serve to familiarize you further with the issue. As long as you understand the ASP.NET framework so you can work with it too if you need to (and aren't specialized such that you don't know what you're doing if you're not using your tool) then I believe you've already crafted your defense. + +As DOK mentioned, be cautious that you're not rolling your own here to avoid a larger task at hand in whatever your other functionality is. Don't let this be a distraction: it should be something your application really needs. If it's not, then I'd lean towards focusing on your software's core mission instead." +1860155,"If the name is like ""david"" it comes within the allotted space.... +but if the name is like ""john pal abraham desouza"" the allotted space increases automatically.. + +So i need to have the name occupied in the allotted space by auto resizing the font.. +Suggest me a solution..",2009/12/07,"['https://Stackoverflow.com/questions/1860155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174796/']","It sounds to me like what you want to do is roll your own Custom .NET Membership Provider. + +It will allow you to use the built-in ASP.NET Authentication/Authorization attributes on your Controller Actions while giving you complete control over the implementation inside the provider (which will allow you to code it to meet the requirements stated above). + +Direct from MSDN... + +[Implementing a Membership Provider](http://msdn.microsoft.com/en-us/library/f1kyba5e.aspx)","I too am working on a pet Project using ASP.net MVC and db4o and did the same thing, so you're at least not alone in going down that route :). One of the biggest reasons for me to start playing around with db4o as persistence layer is that especially authorization on field level (i.e I'm allowed to see Person A's first name but not Person B's first name) is though to achieve if you're forced into complex SQL statements and an anemic domain model. + +Since I had complex authorization needs that needed to be persisted (and synchronized) in both db4o and Solr indexes I started working on rolling out my own, but only because I knew up front it was one of the key features of my pet project that I wanted 100% control over. + +Now I might still use the .Net Membership provider for authentication but not (solely) for authorization of objects but only after i POC'd my authorization needs using my own." +2568467,"In our organization, we are still on .net 1.1 environment, using javascript, a few open source applications/widgets. Development is done using Visual Studio 2003, grid view, and iframes. Our application works in Internet Explorer 7 and IE 8 (in compatibilily mode). Can anyone give any basic steps we can take to get our application to work cross browsers? What are the starting locations we can get at to start making existing code work in different browsers?",2010/04/02,"['https://Stackoverflow.com/questions/2568467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","Use jQuery for reliable cross browser JavaScript + +Was it VS 2k or VS 2k3 that ""helped"" the developer by rewriting their HTML (in all CAPS no less)?","Make your HTML markup standards compliant. I find that developing my website following W3C standards ensure that my sites work in all major browsers. + +I also develop in Firefox and then fix IE using conditional stylesheets. + +The .NET version does not matter on browser compatibility." +2568467,"In our organization, we are still on .net 1.1 environment, using javascript, a few open source applications/widgets. Development is done using Visual Studio 2003, grid view, and iframes. Our application works in Internet Explorer 7 and IE 8 (in compatibilily mode). Can anyone give any basic steps we can take to get our application to work cross browsers? What are the starting locations we can get at to start making existing code work in different browsers?",2010/04/02,"['https://Stackoverflow.com/questions/2568467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","Use jQuery for reliable cross browser JavaScript + +Was it VS 2k or VS 2k3 that ""helped"" the developer by rewriting their HTML (in all CAPS no less)?",".Net in its 2.0 iteration got *a lot* better (compared to 1.1) at producing cross-browser, and certainly *more* standards-compliant code (although not perfect by any means). + +If you can upgrade to 2.0 this will get you a lot of progress on the standards compliance front for free (unless your own controls / html render as non-cross-browser html and/or javascript; then that would be the first main problem to tackle). + +In .Net 2.0 don't forget to appropriately set the `xhtmlconformance` [attribute](http://msdn.microsoft.com/en-us/library/ms228268.aspx) in your `web.config` (if you're for example aiming for xhtml). This globally affects the produced html your controls produce." +2568467,"In our organization, we are still on .net 1.1 environment, using javascript, a few open source applications/widgets. Development is done using Visual Studio 2003, grid view, and iframes. Our application works in Internet Explorer 7 and IE 8 (in compatibilily mode). Can anyone give any basic steps we can take to get our application to work cross browsers? What are the starting locations we can get at to start making existing code work in different browsers?",2010/04/02,"['https://Stackoverflow.com/questions/2568467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","Use jQuery for reliable cross browser JavaScript + +Was it VS 2k or VS 2k3 that ""helped"" the developer by rewriting their HTML (in all CAPS no less)?","1. Install and Run Firefox (and get the Firebug addon). +2. Enter your application and open the Firebug console (F12) to see what issues your application is encountering. (in the Console Tab) +3. Start with the Errors. + 1. Change any JavaScript that is doing things like *document.all.xxxx* to use **document.getElementById()** or **document.forms['name'].elements['name']** etc. + 2. Change any CSS that is using IE only styles. e.g. ""*cursor:hand*"" should be ""**cursor:pointer**"" etc. +4. Repeat for Warnings once all the Errors are gone +5. If your app was running in Quirks mode, consider adding a doctype so that you can render in Standards mode (makes CSS/JS much more compliant)... however note that this will very likely ""screw up"" your pages for a bit until you iron out the kinks. +6. In the future, be sure to test in all major browsers. I'd recommend developing in Firefox or Chrome first, then tweaking if needed for IE." +2568467,"In our organization, we are still on .net 1.1 environment, using javascript, a few open source applications/widgets. Development is done using Visual Studio 2003, grid view, and iframes. Our application works in Internet Explorer 7 and IE 8 (in compatibilily mode). Can anyone give any basic steps we can take to get our application to work cross browsers? What are the starting locations we can get at to start making existing code work in different browsers?",2010/04/02,"['https://Stackoverflow.com/questions/2568467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","Make your HTML markup standards compliant. I find that developing my website following W3C standards ensure that my sites work in all major browsers. + +I also develop in Firefox and then fix IE using conditional stylesheets. + +The .NET version does not matter on browser compatibility.",".Net in its 2.0 iteration got *a lot* better (compared to 1.1) at producing cross-browser, and certainly *more* standards-compliant code (although not perfect by any means). + +If you can upgrade to 2.0 this will get you a lot of progress on the standards compliance front for free (unless your own controls / html render as non-cross-browser html and/or javascript; then that would be the first main problem to tackle). + +In .Net 2.0 don't forget to appropriately set the `xhtmlconformance` [attribute](http://msdn.microsoft.com/en-us/library/ms228268.aspx) in your `web.config` (if you're for example aiming for xhtml). This globally affects the produced html your controls produce." +2568467,"In our organization, we are still on .net 1.1 environment, using javascript, a few open source applications/widgets. Development is done using Visual Studio 2003, grid view, and iframes. Our application works in Internet Explorer 7 and IE 8 (in compatibilily mode). Can anyone give any basic steps we can take to get our application to work cross browsers? What are the starting locations we can get at to start making existing code work in different browsers?",2010/04/02,"['https://Stackoverflow.com/questions/2568467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","1. Install and Run Firefox (and get the Firebug addon). +2. Enter your application and open the Firebug console (F12) to see what issues your application is encountering. (in the Console Tab) +3. Start with the Errors. + 1. Change any JavaScript that is doing things like *document.all.xxxx* to use **document.getElementById()** or **document.forms['name'].elements['name']** etc. + 2. Change any CSS that is using IE only styles. e.g. ""*cursor:hand*"" should be ""**cursor:pointer**"" etc. +4. Repeat for Warnings once all the Errors are gone +5. If your app was running in Quirks mode, consider adding a doctype so that you can render in Standards mode (makes CSS/JS much more compliant)... however note that this will very likely ""screw up"" your pages for a bit until you iron out the kinks. +6. In the future, be sure to test in all major browsers. I'd recommend developing in Firefox or Chrome first, then tweaking if needed for IE.",".Net in its 2.0 iteration got *a lot* better (compared to 1.1) at producing cross-browser, and certainly *more* standards-compliant code (although not perfect by any means). + +If you can upgrade to 2.0 this will get you a lot of progress on the standards compliance front for free (unless your own controls / html render as non-cross-browser html and/or javascript; then that would be the first main problem to tackle). + +In .Net 2.0 don't forget to appropriately set the `xhtmlconformance` [attribute](http://msdn.microsoft.com/en-us/library/ms228268.aspx) in your `web.config` (if you're for example aiming for xhtml). This globally affects the produced html your controls produce." +9699529,"In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form. + +Data expected to be big in the database and records are spread over several tables in a very normalized fashion. + +Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries? + +Thank you",2012/03/14,"['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']","The purpose of `final` but non-`static` variables is to have an object-wide constant. It should be initialized in the constructor: + +``` +class Passenger { + final int b; + + Passenger(int b) { + this.b = b; + } +} + +``` + +If you are always assigning a constant literal value (`0`) to the `final` variable, it doesn't make much sense. Using `static` is preferred so that you are only having a single copy of `b`: + +``` +static final int b = 0; + +``` + +BTW I don't think having default access modifier was your intention.","If you have multiple instances of `Passenger` class, I would go for making it static. While this has little benefit when talking about an `int` variable, this could save some memory if you have complex objects. This is because a static variable belongs to a class, not to an instance, thus memory space for it will be reserved only once, and it will be referred by the class object itself, not by the instances. Of course, you should be aware that having `b` as a static variable means that the changes made on this variable will be reflected on all the classes that access this variable, but since you made it `final` this won't be the case. + +Note also that with the code you've written, classes in the same package as `Passenger` will be able to read the `b` value by accessing it via `Passenger.b` (if static)." +9699529,"In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form. + +Data expected to be big in the database and records are spread over several tables in a very normalized fashion. + +Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries? + +Thank you",2012/03/14,"['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']","If you have multiple instances of `Passenger` class, I would go for making it static. While this has little benefit when talking about an `int` variable, this could save some memory if you have complex objects. This is because a static variable belongs to a class, not to an instance, thus memory space for it will be reserved only once, and it will be referred by the class object itself, not by the instances. Of course, you should be aware that having `b` as a static variable means that the changes made on this variable will be reflected on all the classes that access this variable, but since you made it `final` this won't be the case. + +Note also that with the code you've written, classes in the same package as `Passenger` will be able to read the `b` value by accessing it via `Passenger.b` (if static).","A `final` primitive is the same as a `static final` primitive (except more efficient) + +A `final` reference to an immutable object the same as a `static final` reference of the same. + +A `final` reference to a mutable object is NOT the same as a `static final` reference of the same. + +``` +final int i = 0; +// same as +static final int = 0; + +final String hi = ""Hello""; +// same as +static final String hi = ""Hello""; + +final List list = new ArrayList(); +// is NOT the same as +static final List list = new ArrayList(); + +``` + +The only time the last example is the same is when you have a singleton. It is fairly common for singletons to be written with a confusion of static and non static fields and methods as the difference is not obvious. :|" +9699529,"In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form. + +Data expected to be big in the database and records are spread over several tables in a very normalized fashion. + +Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries? + +Thank you",2012/03/14,"['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']","The purpose of `final` but non-`static` variables is to have an object-wide constant. It should be initialized in the constructor: + +``` +class Passenger { + final int b; + + Passenger(int b) { + this.b = b; + } +} + +``` + +If you are always assigning a constant literal value (`0`) to the `final` variable, it doesn't make much sense. Using `static` is preferred so that you are only having a single copy of `b`: + +``` +static final int b = 0; + +``` + +BTW I don't think having default access modifier was your intention.","A `final` primitive is the same as a `static final` primitive (except more efficient) + +A `final` reference to an immutable object the same as a `static final` reference of the same. + +A `final` reference to a mutable object is NOT the same as a `static final` reference of the same. + +``` +final int i = 0; +// same as +static final int = 0; + +final String hi = ""Hello""; +// same as +static final String hi = ""Hello""; + +final List list = new ArrayList(); +// is NOT the same as +static final List list = new ArrayList(); + +``` + +The only time the last example is the same is when you have a singleton. It is fairly common for singletons to be written with a confusion of static and non static fields and methods as the difference is not obvious. :|" +9699529,"In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form. + +Data expected to be big in the database and records are spread over several tables in a very normalized fashion. + +Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries? + +Thank you",2012/03/14,"['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']",It depends on the purpose of b. Usually constants are there for a specific purpose. If you make it static you could accidentally change it in some instance of that class and that will affect all the others.,"In java, the `static` attribute basically means: **associated with the type itself, rather than an instance of the type**. + +In other words you can reference a static variable without creating instances of that type... Whereas in the case of just using `final` you'd need to instantiate the class. + +So, yes, to answer your question, I'd say that you're right. :)" +9699529,"In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form. + +Data expected to be big in the database and records are spread over several tables in a very normalized fashion. + +Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries? + +Thank you",2012/03/14,"['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']","The purpose of `final` but non-`static` variables is to have an object-wide constant. It should be initialized in the constructor: + +``` +class Passenger { + final int b; + + Passenger(int b) { + this.b = b; + } +} + +``` + +If you are always assigning a constant literal value (`0`) to the `final` variable, it doesn't make much sense. Using `static` is preferred so that you are only having a single copy of `b`: + +``` +static final int b = 0; + +``` + +BTW I don't think having default access modifier was your intention.","In java, the `static` attribute basically means: **associated with the type itself, rather than an instance of the type**. + +In other words you can reference a static variable without creating instances of that type... Whereas in the case of just using `final` you'd need to instantiate the class. + +So, yes, to answer your question, I'd say that you're right. :)" +9699529,"In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form. + +Data expected to be big in the database and records are spread over several tables in a very normalized fashion. + +Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries? + +Thank you",2012/03/14,"['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']",It depends on the purpose of b. Usually constants are there for a specific purpose. If you make it static you could accidentally change it in some instance of that class and that will affect all the others.,"A `final` variable is defined when you need a constant, so you can assign a value just once. +Using `static`, instead, you are defining a variable shared by all the objects of that type (like a global variable) and it is not associated with a certain object itself." +9699529,"In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form. + +Data expected to be big in the database and records are spread over several tables in a very normalized fashion. + +Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries? + +Thank you",2012/03/14,"['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']","The purpose of `final` but non-`static` variables is to have an object-wide constant. It should be initialized in the constructor: + +``` +class Passenger { + final int b; + + Passenger(int b) { + this.b = b; + } +} + +``` + +If you are always assigning a constant literal value (`0`) to the `final` variable, it doesn't make much sense. Using `static` is preferred so that you are only having a single copy of `b`: + +``` +static final int b = 0; + +``` + +BTW I don't think having default access modifier was your intention.",It depends on the purpose of b. Usually constants are there for a specific purpose. If you make it static you could accidentally change it in some instance of that class and that will affect all the others. +9699529,"In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form. + +Data expected to be big in the database and records are spread over several tables in a very normalized fashion. + +Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries? + +Thank you",2012/03/14,"['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']",It depends on the purpose of b. Usually constants are there for a specific purpose. If you make it static you could accidentally change it in some instance of that class and that will affect all the others.,"A `final` primitive is the same as a `static final` primitive (except more efficient) + +A `final` reference to an immutable object the same as a `static final` reference of the same. + +A `final` reference to a mutable object is NOT the same as a `static final` reference of the same. + +``` +final int i = 0; +// same as +static final int = 0; + +final String hi = ""Hello""; +// same as +static final String hi = ""Hello""; + +final List list = new ArrayList(); +// is NOT the same as +static final List list = new ArrayList(); + +``` + +The only time the last example is the same is when you have a singleton. It is fairly common for singletons to be written with a confusion of static and non static fields and methods as the difference is not obvious. :|" +9699529,"In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form. + +Data expected to be big in the database and records are spread over several tables in a very normalized fashion. + +Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries? + +Thank you",2012/03/14,"['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']","The purpose of `final` but non-`static` variables is to have an object-wide constant. It should be initialized in the constructor: + +``` +class Passenger { + final int b; + + Passenger(int b) { + this.b = b; + } +} + +``` + +If you are always assigning a constant literal value (`0`) to the `final` variable, it doesn't make much sense. Using `static` is preferred so that you are only having a single copy of `b`: + +``` +static final int b = 0; + +``` + +BTW I don't think having default access modifier was your intention.","A `final` variable is defined when you need a constant, so you can assign a value just once. +Using `static`, instead, you are defining a variable shared by all the objects of that type (like a global variable) and it is not associated with a certain object itself." +9699529,"In a website I am working on, there is an advanced search form with several fields, some of them dynamic that show up / hide depending on what is being selected on the search form. + +Data expected to be big in the database and records are spread over several tables in a very normalized fashion. + +Is there a recommendation on using a 3rd part search engine, sql server full text search, lucene.net, etc ... other than using SELECT / JOIN queries? + +Thank you",2012/03/14,"['https://Stackoverflow.com/questions/9699529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248665/']","If you have multiple instances of `Passenger` class, I would go for making it static. While this has little benefit when talking about an `int` variable, this could save some memory if you have complex objects. This is because a static variable belongs to a class, not to an instance, thus memory space for it will be reserved only once, and it will be referred by the class object itself, not by the instances. Of course, you should be aware that having `b` as a static variable means that the changes made on this variable will be reflected on all the classes that access this variable, but since you made it `final` this won't be the case. + +Note also that with the code you've written, classes in the same package as `Passenger` will be able to read the `b` value by accessing it via `Passenger.b` (if static).","A `final` variable is defined when you need a constant, so you can assign a value just once. +Using `static`, instead, you are defining a variable shared by all the objects of that type (like a global variable) and it is not associated with a certain object itself." +64261847,"So I wrote a model that computes results over various parameters via a nested loop. Each computation returns a list of `len(columns) = 10` elements, which is added to a list of lists (`res`). + +Say I compute my results for some parameters `len(alpha) = 2`, `len(gamma) = 2`, `rep = 3`, where rep is the number of repetitions that I run. This yields results in the form of a list of lists like this: + +``` +res = [ [elem_1, ..., elem_10], ..., [elem_1, ..., elem_10] ] + +``` + +I know that `len(res) = len(alpha) * len(gamma) * repetitions = 12` and that each inner list has `len(columns) = 10` elements. I also know that every 3rd list in `res` is going to be a repetition (which I know from the way I set up my nested loops to iterate over all parameter combinations, in fact I am using itertools). + +I now want to average the result list of lists. What I need to do is to take every `(len(res) // repetitions) = 4`th list , add them together element-wise, and divide by the number of repetitions (3). Sounded easier than done, for me. + +Here is my ugly attempt to do so: + +``` +# create a list of lists of lists, where the inner list of lists are lists of the runs with the identical parameters alpha and gamma +res = [res[i::(len(res)//rep)] for i in range(len(res)//rep)] + +avg_res = [] +for i in res: + result = [] + for j in (zip(*i)): + result.append(sum(j)) + avg_res.append([i/repetitions for i in result]) + +print(len(result_list), avg_res) + +``` + +This actually yields, what I want, but it surely is not the pythonic way to do it. Ugly as hell and 5 minutes later I can hardly make sense of my own code... + +What would be the most pythonic way to do it? Thanks in advance!",2020/10/08,"['https://Stackoverflow.com/questions/64261847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11436649/']","In some cases a pythonic code is a matter of style, one of its idioms is using list comprehension instead of loop so writing `result = [sum(j) for j in (zip(*i))]` is simpler than iterating over `zip(*i)`. + +On the other hand nested list comprehension looks more complex so **don't** do + +``` +avg_res = [[i/repetitions for i in [sum(j) for j in (zip(*j))]] for j in res] + +``` + +You can write: + +``` +res = [res[i::(len(res)//rep)] for i in range(len(res)//rep)] + +avg_res = [] +for i in res: + result = [sum(j) for j in (zip(*i))] + avg_res.append([i/repetitions for i in result]) + +print(len(result_list), avg_res) + +``` + +Another idiom in Programming in general (and in python in particular) is naming operations with functions, and variable names, to make the code more **readable**: + +``` +def sum_columns(list_of_rows): + return [sum(col) for col in (zip(*list_of_rows))] +def align_alpha_and_gamma(res): + return [res[i::(len(res)//rep)] for i in range(len(res)//rep)] + +aligned_lists = align_alpha_and_gamma(res) + +avg_res = [] +for aligned_list in aligned_lists: + sums_of_column= sum_columns(aligned_list) + avg_res.append([sum_of_column/repetitions for sum_of_column in sums_of_column]) + +print(len(result_list), avg_res) + +``` + +Off course you can choose better names according to what you want to do in the code.","It was a bit hard to follow your instructions, but as I caught, you attempt to try sum over all element in N'th list and divide it by repetitions. + +``` +res = [list(range(i,i+10)) for i in range(10)] +N = 4 +repetitions = 3 +average_of_Nth_lists = sum([num for iter,item in enumerate(res) for num in item if iter%N==0])/repetitions +print(average_of_Nth_lists) + +``` + +output: + +``` +85.0 + +``` + +explanation for the result: equals to `sum(0-9)+sum(4-13)+sum(8-17) = 255` --> `255/3=85.0` + +created `res` as a list of lists, iterate over N'th list (in my case, 1,5,9 you can transform it to 4,8 etc if that what you are wish, find out where in the code or ask for help if you don't get it), sum them up and divide by `repetitions`" +9450204,"I need create a link to `users/id/microposts` where `id` is the user id. I was wondering how I could do that with `link_to`? + +The HTML code is I am using for the moment is : + +``` +/microposts"">Microposts <%= user.microposts.count %> + +``` + +Which renders the following : + +``` +Microposts + +```",2012/02/26,"['https://Stackoverflow.com/questions/9450204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146764/']","Python uses dictionaries to keep local and global variables in. When looking up a variable reference, it will look into the local dict first. If you want to reference a variable in the global dictionary, put the global keyword in front of it. + +Also see answers to [this](https://stackoverflow.com/questions/370357/python-variable-scope-question) question for more elaborate info.","I agree with user18044, however, is your confusion about the ’f(f)’? I agree that can be really confusing, especially in a non typed language. The argument to ’f’ is a function handle that has a local type scope with name ’f’. The way python decides which ’f’ gets used is explained by 18044. Python looks at the name ’f’ on the function definition and the local parameter ’f’ takes precidence over the global name ’f’ just like would be done if we had a global variable ’dude’ and a local variable ’dude’ in a function. The local overrides the global. Hopes this helps, and makes sense. :-)" +9450204,"I need create a link to `users/id/microposts` where `id` is the user id. I was wondering how I could do that with `link_to`? + +The HTML code is I am using for the moment is : + +``` +/microposts"">Microposts <%= user.microposts.count %> + +``` + +Which renders the following : + +``` +Microposts + +```",2012/02/26,"['https://Stackoverflow.com/questions/9450204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146764/']","Python uses dictionaries to keep local and global variables in. When looking up a variable reference, it will look into the local dict first. If you want to reference a variable in the global dictionary, put the global keyword in front of it. + +Also see answers to [this](https://stackoverflow.com/questions/370357/python-variable-scope-question) question for more elaborate info.","The locals for a function consist of everything that was passed in, and every variable that is assigned to and not explicitly tagged as `global` (or `nonlocal` in 3.x). + +The globals consist of everything that can be seen at global scope, including the function itself. + +When a name is referenced, it is looked up in the locals first, and then in the globals if not found in the locals. + +When the statement `f(g)` is run, the statement itself is at global scope, so there are no locals. `f` and `g` are both found in the globals: they are both functions. The function defined by `def f...` is called, with the function defined by `def g...` being passed as an argument. + +When `f(f)` runs, `f` is in the locals for the function. It is bound to the passed-in value, which is the function defined by `def g...`. The body of the function has the statement `f(1)`. `1` is a constant and no lookup is required. `f` is looked up in the locals, and the passed-in function is found. It - being the function known at global scope as `g` - is called. + +Thus `g` is, likewise, run with the value `1` bound to the local variable `x`. That is forwarded to the function `print` (in 3.x; in 2.x, `print` is a keyword, so `print x` is a statement), which prints the value `1`." +56877001,"As I clarify code, I rename and edit a file *so much* that git doesn't recognize it as a rename. + +A fix: commit rename of old file; then, commit the new file. + +How can I do this nicely with git, *after* all the editing? + +--- + +`git stash` doesn't recognize the new filename. + +Currently I do this: + +* move the new file elsewhere +-`git reset oldfile` to get the old file +* rename it +* commit it +* now, get the new file back, overwriting the above +* commit that + +I've described that as one file, but usually it's many files, in different directories. I don't know about you, but for me it's so easy to accidently overwrite and lose the new versions... which aren't commited yet, so no `reflog` rescue. + +This seems *just* the kind of thing git could help me with... + +*EDIT* I could commit it to a temp branch, for `reflog` safety.",2019/07/03,"['https://Stackoverflow.com/questions/56877001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4930344/']","Git doesn't provide a really nice way to do this, but this works. Assumptions: + +* `foo` is the old name of the file, and the name the modified file still has on disk +* `bar` is the new name you want it to have +* There are no changes staged in the index + +Then do: + +``` +git update-index --add --cacheinfo ""$(git ls-files --full-name -s foo \ + | awk '{print $1 "","" $2 "",bar""}')"" +git rm --cached foo +git commit -m ""rename foo to bar"" +mv foo bar +git add bar +git commit -m ""make changes to bar"" + +``` + +The `git update-index` tells git to stage a new file in the index with the same hash and mode as the indexed version `foo`, but a new name `bar`. It doesn't consult the disk, it just assumes an object exists with that hash (which it does). The `git rm --cached` tells git to stage a removal of `foo` without touching the disk. Together, they make up a rename, which we can commit. Then we move the file for real, use `git add` to inform git about its new contents, and commit again. Naturally you can also add other changes to this commit. + +in between the `git update-index` and the `mv`, `git status` will show an un-staged change of `deleted: bar` because the file exists in the index but not on disk (at least not yet under that name), but this isn't a problem. + +Note that the name `bar` has to be a path relative to the root of the repository, even if you're operating from a sub-directory. For simplicity, operate from the repo root and use the full path for both `foo` and `bar`. + +None of this is really *simpler* than what you're doing, but it does avoid the need to revert changes from your working tree.","I guess it will sound simplistic, but the simplest solution is: When you're editing a file, and have a bunch of pending edits, and you decide the file needs to be renamed, + +(1) make a note that you need to rename it +(2) get the file to a state where you can commit the changes you have +(3) commit it +(4) rename it +(5) commit the rename +(6) if necessary, continue editing + +That is - if you don't want to commit a rename at the same time as you commit changes to the affected file... then don't. + +In a very few cases, there may be a reason to commit a rename with a change. For example, a public class name in Java should match its filename. But that's fine - the rename detection change threshold isn't (by default) 100% match anyway. Small changes will rarely hurt anything. But that's not really the issue, because you've already decided you want to do separate commits. + +So the issue is just a little bit of planning ahead. At the moment you're going to rename a significantly edited file (or significantly edit a renamed file), that's the moment to decide ""oh, I'll want to separate this next step into a different commit from what I've already done"". + +If you really can't do that, then stash is actually fine. Stash your edits, rename the file, commit, pop the stash. Yes, the popped file will be at the wrong path, so rename it again (overwriting the original). + +By the way, depending on your workflow this may all be for naught. A merge will not look at the individual commits and will see exactly the same situation as if you had done everything in one commit. If you use a rebase-driven workflow you might find that it really does help (though that has other costs). But overall I'd say there are other strategies that do more to reduce this problem - such as making sure divergent branches are short lived so taht any conflict resolution is kept to a minimum even when rename detection is not successful." +58065328,"I'm using NuxtJS's auth module and trying to get the Bearer token and a custom cookie that contains a sessionType on nuxtServerInit so I can update the `store` with a `mutation`, but it only works when I reload the page. + +If I close the browser and go directly to my app url, I keep getting undefined for auth.\_token.local because `nuxtServerInit` executes before the cookies are ready. + +My code in store/index.js looks like this: + +``` +export const actions = { + async nuxtServerInit({ commit, dispatch }, { req }) { + // Parse cookies with cookie-universal-nuxt + const token = this.$cookies.get('token') + const sessionType = this.$cookies.get('sessionType') + + // Check if Cookie user and token exists to set them in 'auth' + if (token && user) { + commit('auth/SET_TOKEN', token) + commit('auth/SET_SESSION_TYPE', user) + } + } +} + +``` + +I'm using nuxt-universal-cookies library. + +What's the way to execute the action after the cookies are loaded on the browser?",2019/09/23,"['https://Stackoverflow.com/questions/58065328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7666951/']","Having it work with F5 and not by hitting enter makes me suspect that it just works sometimes and sometimes it doesn't, because `F5` and `Enter` should trigger same behaviour on Nuxt (apart from some cache headers). + +The only suspicious thing about you code is the usage of an `async` function when the function is not returning or awaiting any promise. + +So you either `await` for an `action` + +``` +export const actions = { + async nuxtServerInit({ commit, dispatch }, { req }) { + // Parse cookies with cookie-universal-nuxt + const token = this.$cookies.get('token') + const sessionType = this.$cookies.get('sessionType') + + // Check if Cookie user and token exists to set them in 'auth' + if (token && user) { + await dispatch('SET_SESSION', {token, user}) + //commit('auth/SET_TOKEN', token) + //commit('auth/SET_SESSION_TYPE', user) + } + } +} + +``` + +or you remove the async from the declaration + +``` +export const actions = { + nuxtServerInit({ commit, dispatch }, { req }) { + // Parse cookies with cookie-universal-nuxt + const token = this.$cookies.get('token') + const sessionType = this.$cookies.get('sessionType') + + // Check if Cookie user and token exists to set them in 'auth' + if (token && user) { + commit('auth/SET_TOKEN', token) + commit('auth/SET_SESSION_TYPE', user) + } + } +} + +```",I've had the same issue and found out that `nuxtServerInit` is triggered first before the cookie was set like via a express middleware. +140021,How to get number of subsites in a site collection using Powershell?,2015/04/29,"['https://sharepoint.stackexchange.com/questions/140021', 'https://sharepoint.stackexchange.com', 'https://sharepoint.stackexchange.com/users/41443/']","or simply: + +``` +$site = Get-SPSite http://YourSharePointSite +$site.AllWebs.Count + +```","``` +if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = ""ReuseThread""} +if ((Get-PSSnapin ""Microsoft.SharePoint.PowerShell"" -ErrorAction SilentlyContinue) -eq $null) +{ + Add-PSSnapin ""Microsoft.SharePoint.PowerShell"" +} + +$sites = Get-SPSite +$noOfWebs = 0 + +foreach ($web in $sites.AllWebs) +{ + $noOfWebs++ +} + +If ($sites -ne $null) +{ + $sites.Dispose(); +} + +If ($web -ne $null) +{ + $web.Dispose(); +} + +Write-Host ""Total No of Subsites: "" $noOfWebs + +```" +140021,How to get number of subsites in a site collection using Powershell?,2015/04/29,"['https://sharepoint.stackexchange.com/questions/140021', 'https://sharepoint.stackexchange.com', 'https://sharepoint.stackexchange.com/users/41443/']","``` +if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = ""ReuseThread""} +if ((Get-PSSnapin ""Microsoft.SharePoint.PowerShell"" -ErrorAction SilentlyContinue) -eq $null) +{ + Add-PSSnapin ""Microsoft.SharePoint.PowerShell"" +} + +$sites = Get-SPSite +$noOfWebs = 0 + +foreach ($web in $sites.AllWebs) +{ + $noOfWebs++ +} + +If ($sites -ne $null) +{ + $sites.Dispose(); +} + +If ($web -ne $null) +{ + $web.Dispose(); +} + +Write-Host ""Total No of Subsites: "" $noOfWebs + +```","Using the following code, within the SharePoint Management Shell, you can get the count of Web Applications in the Farm, Site Collections in Web Application, Sites in Site Collection. + +``` +Write-Host ""Web Applications in Farm"" +$WebApplications = Get-SPWebApplication +$WebApplications | Measure-Object | Format-List Count + +ForEach($WebApplication in $WebApplications) { + Write-Host ""Site Collections in the Web Application named "" $WebApplication.Name + $WebApplication.Sites | Measure-Object | Format-List Count + + ForEach($SiteCollection in $WebApplication.Sites) { + Write-Host ""Webs (Sub-Sites) in the Site Collection with the URL "" $SiteCollection.Url + Write-Host ""`nCount : "" $SiteCollection.AllWebs.Count ""`n`n`n"" + } +} + +```" +140021,How to get number of subsites in a site collection using Powershell?,2015/04/29,"['https://sharepoint.stackexchange.com/questions/140021', 'https://sharepoint.stackexchange.com', 'https://sharepoint.stackexchange.com/users/41443/']","or simply: + +``` +$site = Get-SPSite http://YourSharePointSite +$site.AllWebs.Count + +```","Using the following code, within the SharePoint Management Shell, you can get the count of Web Applications in the Farm, Site Collections in Web Application, Sites in Site Collection. + +``` +Write-Host ""Web Applications in Farm"" +$WebApplications = Get-SPWebApplication +$WebApplications | Measure-Object | Format-List Count + +ForEach($WebApplication in $WebApplications) { + Write-Host ""Site Collections in the Web Application named "" $WebApplication.Name + $WebApplication.Sites | Measure-Object | Format-List Count + + ForEach($SiteCollection in $WebApplication.Sites) { + Write-Host ""Webs (Sub-Sites) in the Site Collection with the URL "" $SiteCollection.Url + Write-Host ""`nCount : "" $SiteCollection.AllWebs.Count ""`n`n`n"" + } +} + +```" +20010268,"I have base structure as given below + +``` +Sales.Customers Sales.Orders Sales.OrderDetails +--------------- ------------ ------------------ +country orderid orderid +custid custid qty + +``` + +So I need return United States customers, and for each customer return the total number of orders and total quantities. I wrote such query: + +``` +SELECT +C.custid, SUM(O.orderid) as numorders, +SUM(OD.qty) as totalqty + +FROM Sales.Customers AS C +JOIN Sales.Orders AS O +ON C.custid = O.custid + JOIN Sales.OrderDetails AS OD + ON O.orderid = OD.orderid + +WHERE country = 'USA' +GROUP BY C.custid; + +``` + +Unfortunately I get such result: + +``` +custid numorders totalqty +----------- ----------- ----------- +32 235946 345 +36 94228 122 +43 21027 20 +....... ..... .... + +``` + +Instead of + +``` +custid numorders totalqty +----------- ----------- ----------- +32 11 345 +36 5 122 + +``` + +I can`t understand where mistake is.",2013/11/15,"['https://Stackoverflow.com/questions/20010268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1739325/']","This should do: + +``` +SELECT C.custid, + COUNT(DISTINCT O.orderid) as numorders, + SUM(OD.qty) as totalqty +FROM Sales.Customers AS C +INNER JOIN Sales.Orders AS O + ON C.custid = O.custid +INNER JOIN Sales.OrderDetails AS OD + ON O.orderid = OD.orderid +WHERE country = 'USA' +GROUP BY C.custid +ORDER BY C.custid; + +```","Upon a bit more reading, you have two things wrong. You're summing orders instead of counting, and you're grouping on quantity. +Try: + +``` +SELECT +C.custid, +COUNT(distinct O.orderid) as numorders, +SUM(OD.qty) as totalqty + +FROM Sales.Customers AS C +JOIN Sales.Orders AS O +ON C.custid = O.custid + JOIN Sales.OrderDetails AS OD + ON O.orderid = OD.orderid + +WHERE country = 'USA' +GROUP BY C.custid +ORDER BY C.custid; + +```" +3875021,"This is a general best practice question about creating parent / child relationships with objects. + +Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object + +``` +public class Car{ + + private List wheels = new List(); + + void AddWheel ( Wheel WheelToAdd) + { + wheels.Add(WheelToAdd) + //Some Other logic relating to adding wheels here + } + } +} + +``` + +So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this + +``` + public class Wheel { + + private Car parentCar; + public Car + { + get + { + return parentCar + } + + } + +} + +``` + +When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency. + +Any thoughts, many thanks in advance",2010/10/06,"['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']","You might want to consider having a setter that only sets `Wheel.parentCar` if that setting is null, but only if you're able to assume that your first setting will be valid and are thus able to disregard any other attempts. + +Edit: but yes, that would be the proper place to add the `Car` object. You could also do a check such that you create (for example) `Wheel.validateCar(Car carInQuestion)`, where it enforces that the `parentCar` property is only set where the current `Wheel` object exists in `Car`. This implies that you would have a public method for searching `Car.wheels` for membership based on a particular instance of a wheel. But that's only if you really feel the need to be strict.","I'm going to go with ""Don't"". A wheel isn't just a property of a `Car`. A wheel could be used on a `Trailer` or a `Cart` or a `FerrisWheel` (ok, maybe that's a bit of a stretch). The point is, by making the car which uses the wheel a property of the wheel itself, you couple your wheel's design to being used on a car, and at that point, you lose any reusability for the class. + +In this case, it seems like there's a lot to lose and little to gain by letting the wheel know what it's actually used on." +3875021,"This is a general best practice question about creating parent / child relationships with objects. + +Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object + +``` +public class Car{ + + private List wheels = new List(); + + void AddWheel ( Wheel WheelToAdd) + { + wheels.Add(WheelToAdd) + //Some Other logic relating to adding wheels here + } + } +} + +``` + +So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this + +``` + public class Wheel { + + private Car parentCar; + public Car + { + get + { + return parentCar + } + + } + +} + +``` + +When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency. + +Any thoughts, many thanks in advance",2010/10/06,"['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']","You might want to consider having a setter that only sets `Wheel.parentCar` if that setting is null, but only if you're able to assume that your first setting will be valid and are thus able to disregard any other attempts. + +Edit: but yes, that would be the proper place to add the `Car` object. You could also do a check such that you create (for example) `Wheel.validateCar(Car carInQuestion)`, where it enforces that the `parentCar` property is only set where the current `Wheel` object exists in `Car`. This implies that you would have a public method for searching `Car.wheels` for membership based on a particular instance of a wheel. But that's only if you really feel the need to be strict.","May be a little left of centre but conceptually a wheel is a ""part"" of a car. Did you consider using partial classes? A passenger is a ""part"" of a queue. I find the use of partial classes and well defined interfaces is very useful in some scenarios. You can abstract out aspects of whole object into interfaces and implement each interface as a partial class. The result is a complete object that is able to be abstracted by its partial interface to meet an array of contractual scenarios." +3875021,"This is a general best practice question about creating parent / child relationships with objects. + +Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object + +``` +public class Car{ + + private List wheels = new List(); + + void AddWheel ( Wheel WheelToAdd) + { + wheels.Add(WheelToAdd) + //Some Other logic relating to adding wheels here + } + } +} + +``` + +So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this + +``` + public class Wheel { + + private Car parentCar; + public Car + { + get + { + return parentCar + } + + } + +} + +``` + +When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency. + +Any thoughts, many thanks in advance",2010/10/06,"['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']","Bidirectional relationships tend to be very difficult to implement correctly. The prevailing advice here should be ""don't do that, most likely you don't actually need it, and it will do you more harm than good."" + +If, after much careful consideration, you decide a bidirectional relationship is warranted, you can make the setter of the `Car` property `internal`, which doesn't fully protect against rogues setting unwanted values but it does limit the surface area significantly.","I'm going to go with ""Don't"". A wheel isn't just a property of a `Car`. A wheel could be used on a `Trailer` or a `Cart` or a `FerrisWheel` (ok, maybe that's a bit of a stretch). The point is, by making the car which uses the wheel a property of the wheel itself, you couple your wheel's design to being used on a car, and at that point, you lose any reusability for the class. + +In this case, it seems like there's a lot to lose and little to gain by letting the wheel know what it's actually used on." +3875021,"This is a general best practice question about creating parent / child relationships with objects. + +Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object + +``` +public class Car{ + + private List wheels = new List(); + + void AddWheel ( Wheel WheelToAdd) + { + wheels.Add(WheelToAdd) + //Some Other logic relating to adding wheels here + } + } +} + +``` + +So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this + +``` + public class Wheel { + + private Car parentCar; + public Car + { + get + { + return parentCar + } + + } + +} + +``` + +When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency. + +Any thoughts, many thanks in advance",2010/10/06,"['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']","Bidirectional relationships tend to be very difficult to implement correctly. The prevailing advice here should be ""don't do that, most likely you don't actually need it, and it will do you more harm than good."" + +If, after much careful consideration, you decide a bidirectional relationship is warranted, you can make the setter of the `Car` property `internal`, which doesn't fully protect against rogues setting unwanted values but it does limit the surface area significantly.","May be a little left of centre but conceptually a wheel is a ""part"" of a car. Did you consider using partial classes? A passenger is a ""part"" of a queue. I find the use of partial classes and well defined interfaces is very useful in some scenarios. You can abstract out aspects of whole object into interfaces and implement each interface as a partial class. The result is a complete object that is able to be abstracted by its partial interface to meet an array of contractual scenarios." +3875021,"This is a general best practice question about creating parent / child relationships with objects. + +Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object + +``` +public class Car{ + + private List wheels = new List(); + + void AddWheel ( Wheel WheelToAdd) + { + wheels.Add(WheelToAdd) + //Some Other logic relating to adding wheels here + } + } +} + +``` + +So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this + +``` + public class Wheel { + + private Car parentCar; + public Car + { + get + { + return parentCar + } + + } + +} + +``` + +When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency. + +Any thoughts, many thanks in advance",2010/10/06,"['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']","You might want to consider having a setter that only sets `Wheel.parentCar` if that setting is null, but only if you're able to assume that your first setting will be valid and are thus able to disregard any other attempts. + +Edit: but yes, that would be the proper place to add the `Car` object. You could also do a check such that you create (for example) `Wheel.validateCar(Car carInQuestion)`, where it enforces that the `parentCar` property is only set where the current `Wheel` object exists in `Car`. This implies that you would have a public method for searching `Car.wheels` for membership based on a particular instance of a wheel. But that's only if you really feel the need to be strict.",Take a look at [Is it bad practice for a child object to have a pointer to its parent?](https://stackoverflow.com/questions/3724092/is-it-bad-practice-for-a-child-object-to-have-a-pointer-to-its-parent) +3875021,"This is a general best practice question about creating parent / child relationships with objects. + +Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object + +``` +public class Car{ + + private List wheels = new List(); + + void AddWheel ( Wheel WheelToAdd) + { + wheels.Add(WheelToAdd) + //Some Other logic relating to adding wheels here + } + } +} + +``` + +So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this + +``` + public class Wheel { + + private Car parentCar; + public Car + { + get + { + return parentCar + } + + } + +} + +``` + +When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency. + +Any thoughts, many thanks in advance",2010/10/06,"['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']","Bidirectional relationships tend to be very difficult to implement correctly. The prevailing advice here should be ""don't do that, most likely you don't actually need it, and it will do you more harm than good."" + +If, after much careful consideration, you decide a bidirectional relationship is warranted, you can make the setter of the `Car` property `internal`, which doesn't fully protect against rogues setting unwanted values but it does limit the surface area significantly.","Question: Can the Wheel instance be assigned to a different Car instance later in time? + +1) If yes, the expose a public method to set the parentCar. You *could* make it a fluent method, for ease of code: + +``` +public class Wheel +{ + private Car parentCar; + + public ParentCar + { + get + { + return parentCar; + } + } + + public void SetParentCar(Car _parentCar) + { + parentCar = _parentCar; + return this; + } +} + +``` + +Where you assign add the wheel, make the assignment: + +``` +void AddWheel ( Wheel WheelToAdd) +{ + wheels.Add(WheelToAdd.SetParentCar(this)); + //Some Other logic relating to adding wheels here +} + +``` + +2) If not, just set the parent in the constructor. + +``` +public class Wheel +{ + private Car parentCar; + + public ParentCar + { + get + { + return parentCar; + } + } + + public Wheel(Car _parentCar) + { + parentCar = _parentCar; + } +} + +```" +3875021,"This is a general best practice question about creating parent / child relationships with objects. + +Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object + +``` +public class Car{ + + private List wheels = new List(); + + void AddWheel ( Wheel WheelToAdd) + { + wheels.Add(WheelToAdd) + //Some Other logic relating to adding wheels here + } + } +} + +``` + +So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this + +``` + public class Wheel { + + private Car parentCar; + public Car + { + get + { + return parentCar + } + + } + +} + +``` + +When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency. + +Any thoughts, many thanks in advance",2010/10/06,"['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']","Bidirectional relationships tend to be very difficult to implement correctly. The prevailing advice here should be ""don't do that, most likely you don't actually need it, and it will do you more harm than good."" + +If, after much careful consideration, you decide a bidirectional relationship is warranted, you can make the setter of the `Car` property `internal`, which doesn't fully protect against rogues setting unwanted values but it does limit the surface area significantly.","It makes sense to me for the Car property of the Wheel object to be writable because there's nothing to stop you moving a Wheel from one ToyotaCamry (subclass of Car) to another. Though you might want to have a Drivable property on the original car to check that List.Count is still 4 before allowing Car.Drive() to be called. + +Do you create Wheels with Cars? if so set the property at that time. Otherwise set it when Wheel is attached to Car." +3875021,"This is a general best practice question about creating parent / child relationships with objects. + +Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object + +``` +public class Car{ + + private List wheels = new List(); + + void AddWheel ( Wheel WheelToAdd) + { + wheels.Add(WheelToAdd) + //Some Other logic relating to adding wheels here + } + } +} + +``` + +So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this + +``` + public class Wheel { + + private Car parentCar; + public Car + { + get + { + return parentCar + } + + } + +} + +``` + +When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency. + +Any thoughts, many thanks in advance",2010/10/06,"['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']","A better design methodology, (Domain Driven Design) specifies that you should first decide what the domain model requirements are for these entities... Not all entities need to be independantly accessible, and if `Wheel` falls into this category, every instance of it will always be a child member of a `Car` object and you don't need to put a Parent property on it... `Car` becomes what is referred to as a *root entity*, and the only way to access a `Wheel` is through a `Car` object. + +Even when the `Wheel` object needs to be independantly accessible, the domain model requirements should tell you what the usage patterns require. Will any `Wheel` ever be passed around as a separate object, without it's parent ? In those cases is the `Car` parent relevant? If the identity of the parent `Car` *is* relevant to some piece of functionality, why aren't you simply passing the complete composite `Car` object to that method or module? Cases where a contained composite object (like a `Wheel`) must be passed on it's own, but the identity of the parent (the object it is part of) is needed and/or relevant, are in fact not a common scenario, and approaching your design using the above type of analysis can save you from adding unnessary code to you system.","Question: Can the Wheel instance be assigned to a different Car instance later in time? + +1) If yes, the expose a public method to set the parentCar. You *could* make it a fluent method, for ease of code: + +``` +public class Wheel +{ + private Car parentCar; + + public ParentCar + { + get + { + return parentCar; + } + } + + public void SetParentCar(Car _parentCar) + { + parentCar = _parentCar; + return this; + } +} + +``` + +Where you assign add the wheel, make the assignment: + +``` +void AddWheel ( Wheel WheelToAdd) +{ + wheels.Add(WheelToAdd.SetParentCar(this)); + //Some Other logic relating to adding wheels here +} + +``` + +2) If not, just set the parent in the constructor. + +``` +public class Wheel +{ + private Car parentCar; + + public ParentCar + { + get + { + return parentCar; + } + } + + public Wheel(Car _parentCar) + { + parentCar = _parentCar; + } +} + +```" +3875021,"This is a general best practice question about creating parent / child relationships with objects. + +Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object + +``` +public class Car{ + + private List wheels = new List(); + + void AddWheel ( Wheel WheelToAdd) + { + wheels.Add(WheelToAdd) + //Some Other logic relating to adding wheels here + } + } +} + +``` + +So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this + +``` + public class Wheel { + + private Car parentCar; + public Car + { + get + { + return parentCar + } + + } + +} + +``` + +When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency. + +Any thoughts, many thanks in advance",2010/10/06,"['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']","You might want to consider having a setter that only sets `Wheel.parentCar` if that setting is null, but only if you're able to assume that your first setting will be valid and are thus able to disregard any other attempts. + +Edit: but yes, that would be the proper place to add the `Car` object. You could also do a check such that you create (for example) `Wheel.validateCar(Car carInQuestion)`, where it enforces that the `parentCar` property is only set where the current `Wheel` object exists in `Car`. This implies that you would have a public method for searching `Car.wheels` for membership based on a particular instance of a wheel. But that's only if you really feel the need to be strict.","It makes sense to me for the Car property of the Wheel object to be writable because there's nothing to stop you moving a Wheel from one ToyotaCamry (subclass of Car) to another. Though you might want to have a Drivable property on the original car to check that List.Count is still 4 before allowing Car.Drive() to be called. + +Do you create Wheels with Cars? if so set the property at that time. Otherwise set it when Wheel is attached to Car." +3875021,"This is a general best practice question about creating parent / child relationships with objects. + +Let's say I have Wheel and Car objects and I want to Add a Wheel object to car object + +``` +public class Car{ + + private List wheels = new List(); + + void AddWheel ( Wheel WheelToAdd) + { + wheels.Add(WheelToAdd) + //Some Other logic relating to adding wheels here + } + } +} + +``` + +So far so good. But what if I want to have a Car property of my wheel to say which parent car it relates to. Something like this + +``` + public class Wheel { + + private Car parentCar; + public Car + { + get + { + return parentCar + } + + } + +} + +``` + +When adding the wheel to the car, at which point would you set the parent property of the Wheel? You could set it in the Car.AddWheel method, but then the Car Property of the Wheel object would have to be Read/Write and then you could set it outside of the AddWheel method, creating an inconsistency. + +Any thoughts, many thanks in advance",2010/10/06,"['https://Stackoverflow.com/questions/3875021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/425095/']","A better design methodology, (Domain Driven Design) specifies that you should first decide what the domain model requirements are for these entities... Not all entities need to be independantly accessible, and if `Wheel` falls into this category, every instance of it will always be a child member of a `Car` object and you don't need to put a Parent property on it... `Car` becomes what is referred to as a *root entity*, and the only way to access a `Wheel` is through a `Car` object. + +Even when the `Wheel` object needs to be independantly accessible, the domain model requirements should tell you what the usage patterns require. Will any `Wheel` ever be passed around as a separate object, without it's parent ? In those cases is the `Car` parent relevant? If the identity of the parent `Car` *is* relevant to some piece of functionality, why aren't you simply passing the complete composite `Car` object to that method or module? Cases where a contained composite object (like a `Wheel`) must be passed on it's own, but the identity of the parent (the object it is part of) is needed and/or relevant, are in fact not a common scenario, and approaching your design using the above type of analysis can save you from adding unnessary code to you system.","It makes sense to me for the Car property of the Wheel object to be writable because there's nothing to stop you moving a Wheel from one ToyotaCamry (subclass of Car) to another. Though you might want to have a Drivable property on the original car to check that List.Count is still 4 before allowing Car.Drive() to be called. + +Do you create Wheels with Cars? if so set the property at that time. Otherwise set it when Wheel is attached to Car." +575755,"I am running a regression model in R including the following variables: + +* Intent = continuous DV +* Attitude = continuous IV +* Story = categorical +IV in 4 levels: Consumer, Heritage, Vision and Product +* Style = +categorical IV in 4 levels: Amiable, Analytical, Driver and +Expressive + +Categorical variables are dummy coded. I ran the following regression in R: + +``` +model 4 = glm(Intent ~ Story + Style + Attitude + Story*Style) + +``` + +Results of this regression are found here under model 4: + +[![enter image description here](https://i.stack.imgur.com/gd9Cv.png)](https://i.stack.imgur.com/gd9Cv.png) + +Naturally, R sets one story type and one style as reference groups, in my case the Consumer story and the Amiable style. My only issue is, how can I draw conclusions for these reference groups? + +My goal is to be able to say ""For Analytical styles, purchase intent is most positive when presented with a Product story"". As the results show with a coefficient of 1.063 for Product\*Analytical. But how can I derive a similar conclusion for Amiable people? + +Any help is welcome <3",2022/05/18,"['https://stats.stackexchange.com/questions/575755', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/358498/']","I agree this is odd, but I suppose it could be caused by tied scores showing up in particular quartiles. Suppose we have 100 subjects that get scores from 1 to 100 in 1-point intervals, except that everybody who would have had a score between 26 and 50 instead gets a score of 30. In this case, the average score percentile among the second quartile is either 26 or 50, depending on how you handle endpoints in the percentile calculation. For a dataset with only distinct scores, the average percentile of the second quartile must be 37.5, but it would be possible to find a different average percentile within a quartile that contains tied scores. Not sure if this is the case, or if it's just an error in plotting - even Figures 1 and 4 don't look exactly the same in ""actual test score"" values (the second quantile in Fig 1 is near 35, but it's closer to 40 in Fig 4).","You said: ""*The message is the perceived scores, and the actual scores are shown as a line for reference*"" but I disagree. + +**It doesn't matter that they aren't straight.** + +Consider this, a variant of the upper left subplot: + +[![enter image description here](https://i.stack.imgur.com/Vxxcg.png)](https://i.stack.imgur.com/Vxxcg.png) + +The yellow-colored region is where the perceived ability is higher than the actual ability. The green region is where the perceived ability is lower than the actual. + +I think the important point is that when actual skill is low, estimate of performance is falsely very high, but this decreases as skill increases until the skill is very high, and estimated skill is moderately lower than actual skill. + +Distribution of the measured variable can vary with population. It is easy to make a pathological example, where 25% of values get grades of 10% and the remainder get 100% to make a curve that is concave down. Similarly if 75% of all grades are 10% and the last quarter are 100% then it is strongly concave up. There are many general forms of curves and only a subset are linear. + +Here is some code for exploring this a little bit, numerically. + +``` +#library stuff +if(!require(pacman)) { +install.packages(""pacman""); +require(pacman) } + +p_load(dplyr, #munging + ggplot2) + +#reproducibility +set.seed(575743) + +#uniformly random sample of grades +y <- runif(100, min=0, max=100) + +# y <- rnorm(100, mean=80, sd=10) +# y <- ifelse(y>100,100,y) + +#make background points +q_list_all <- numeric(100) +q_store <- data.frame(q=0:100, y=0*(0:100), bin=0) +for(i in 1:101){ + q_val <- (i-1)/100 + q_store$y[i] <- quantile(y,q_val) +} + +q_store$bin <- ceiling(q\_store$y/round(diff(range(q_store$y))/3.5)) + +#make the plot +ggplot(data=q_store, aes(x=q, y=y) ) + + geom_path(color=""blue"") + geom_point(color=""blue"") + + geom_boxplot(aes(group=bin), alpha=0.5) + + xlab(""Quartile"") + ylab(""grade on test"") + +``` + +This is the plot that it makes: + +[![enter image description here](https://i.stack.imgur.com/uIkD9.png)](https://i.stack.imgur.com/uIkD9.png) + +If instead of using a uniform distribution, you were to use a normal one centered at 80% with a standard deviation of 10% and a maximum of 100%, then the plot looks more like this: + +[![enter image description here](https://i.stack.imgur.com/DDWDt.png)](https://i.stack.imgur.com/DDWDt.png)" +114415,Voldemort couldn't kill Harry as long as he called the Dursleys home. Why didn't he just murder the Dursleys? This would prevent Harry from being able to live there.,2016/01/11,"['https://scifi.stackexchange.com/questions/114415', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/55866/']","The traditional fanon answer is ""there were blood wards protecting the house"". It would not, however, have stopped Voldemort (or his Death Eaters) from attacking the Dursleys when they were out (as proved by Umbridge's dementor attack). + +That said, Voldemort would have needed to figure out 1) that Harry lived at the Dursleys (which itself might not have been common knowledge), and 2) that the blood protection was tied to that fact (that's assuming it was, which we only have Dumbledore's word on, IIRC, so that might not even be true). + +And after the ritual at the end of Harry's fourth year, Voldemort, specifically, had little to worry about from the blood protection anyway.","The Dursleys were safe by the same form of magic that kept Harry safe. However, all of them were only safe within the bounds of their home, till Harry came of age(i.e., he turned 17). Harry or any one of the Dursleys could have been attacked outside their home. Thus, when Harry was about to turn 17, the Order of Phoenix took the Dursleys some place safe. On that night, Harry and his protective guard were attacked as soon as they crossed the 'boundary' that protected the house, since they could not be attacked within that boundary. It was the house which had the protection. + +Harry Potter and the Half Blood Prince: + +Chapter 3: Will and Won't + +> +> ..but Dumbledore raised his finger for silence, a silence which fell as though he had struck Uncle Vernon dumb. +> “The magic I evoked fifteen years ago means that Harry has powerful protection while he can still call this house ‘home.’ However miserable he has been here, however unwelcome, however badlytreated, you have at least, grudgingly, allowed him houseroom. This magic will cease to operate the moment that Harry turns seventeen; in other words, at the moment he becomes a man. I ask only this: that you allow Harry to return, once more, to this house, before his seventeenth birthday, which will ensure that the protection continues until that time.” +> +> +> + +Harry Potter and the Deathly Hallows: + +Chapter 3: The Dursleys Departing + +> +> “You claim,” said Uncle Vernon, starting to pace yet again, “that this Lord +> Thing—” +> +> +> “—Voldemort,” said Harry impatiently, “and we’ve been through this about +> a hundred times already. This isn’t a claim, it’s fact, Dumbledore told you last +> year, and Kingsley and Mr. Weasley—”... +> +> +> ...“—Kingsley and Mr. Weasley explained it all as well,”Harry pressed on remorselessly. ""Once I’m seventeen, the protective charm that keeps me safe will break, and that exposes you as well as me..."" +> +> +>" +114415,Voldemort couldn't kill Harry as long as he called the Dursleys home. Why didn't he just murder the Dursleys? This would prevent Harry from being able to live there.,2016/01/11,"['https://scifi.stackexchange.com/questions/114415', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/55866/']","The traditional fanon answer is ""there were blood wards protecting the house"". It would not, however, have stopped Voldemort (or his Death Eaters) from attacking the Dursleys when they were out (as proved by Umbridge's dementor attack). + +That said, Voldemort would have needed to figure out 1) that Harry lived at the Dursleys (which itself might not have been common knowledge), and 2) that the blood protection was tied to that fact (that's assuming it was, which we only have Dumbledore's word on, IIRC, so that might not even be true). + +And after the ritual at the end of Harry's fourth year, Voldemort, specifically, had little to worry about from the blood protection anyway.","What would he achieve with this? + +According to Dumbledore: + +> +> The magic I evoked fifteen years ago means that Harry has powerful +> protection while he can still call this house ‘home.’ +> +> +> + +Harry and Aunt Marge are the only living relatives of the Dursleys. So if the Dursleys are killed, then Harry will inherit the house or part of it. + +Technically he will be still able to call the house his 'home' and the protection will stay. + +There is also the possibility that Vernon and Petunia Dursley created a will that explicitly transfers the full ownership of the house to Aunt Marge in case they are all dead. In this case the Order of the Phoenix will have hard time persuading Aunt Marge to invite Harry to stay until he is seventeen. + +Still I find this unlikely. Even the Dursleys, as horrible as they are, would not plan for what happens AFTER the death of their only child." +114415,Voldemort couldn't kill Harry as long as he called the Dursleys home. Why didn't he just murder the Dursleys? This would prevent Harry from being able to live there.,2016/01/11,"['https://scifi.stackexchange.com/questions/114415', 'https://scifi.stackexchange.com', 'https://scifi.stackexchange.com/users/55866/']","The Dursleys were safe by the same form of magic that kept Harry safe. However, all of them were only safe within the bounds of their home, till Harry came of age(i.e., he turned 17). Harry or any one of the Dursleys could have been attacked outside their home. Thus, when Harry was about to turn 17, the Order of Phoenix took the Dursleys some place safe. On that night, Harry and his protective guard were attacked as soon as they crossed the 'boundary' that protected the house, since they could not be attacked within that boundary. It was the house which had the protection. + +Harry Potter and the Half Blood Prince: + +Chapter 3: Will and Won't + +> +> ..but Dumbledore raised his finger for silence, a silence which fell as though he had struck Uncle Vernon dumb. +> “The magic I evoked fifteen years ago means that Harry has powerful protection while he can still call this house ‘home.’ However miserable he has been here, however unwelcome, however badlytreated, you have at least, grudgingly, allowed him houseroom. This magic will cease to operate the moment that Harry turns seventeen; in other words, at the moment he becomes a man. I ask only this: that you allow Harry to return, once more, to this house, before his seventeenth birthday, which will ensure that the protection continues until that time.” +> +> +> + +Harry Potter and the Deathly Hallows: + +Chapter 3: The Dursleys Departing + +> +> “You claim,” said Uncle Vernon, starting to pace yet again, “that this Lord +> Thing—” +> +> +> “—Voldemort,” said Harry impatiently, “and we’ve been through this about +> a hundred times already. This isn’t a claim, it’s fact, Dumbledore told you last +> year, and Kingsley and Mr. Weasley—”... +> +> +> ...“—Kingsley and Mr. Weasley explained it all as well,”Harry pressed on remorselessly. ""Once I’m seventeen, the protective charm that keeps me safe will break, and that exposes you as well as me..."" +> +> +>","What would he achieve with this? + +According to Dumbledore: + +> +> The magic I evoked fifteen years ago means that Harry has powerful +> protection while he can still call this house ‘home.’ +> +> +> + +Harry and Aunt Marge are the only living relatives of the Dursleys. So if the Dursleys are killed, then Harry will inherit the house or part of it. + +Technically he will be still able to call the house his 'home' and the protection will stay. + +There is also the possibility that Vernon and Petunia Dursley created a will that explicitly transfers the full ownership of the house to Aunt Marge in case they are all dead. In this case the Order of the Phoenix will have hard time persuading Aunt Marge to invite Harry to stay until he is seventeen. + +Still I find this unlikely. Even the Dursleys, as horrible as they are, would not plan for what happens AFTER the death of their only child." +15243891,"Hi, + +I'm trying to do a simple app with Hibernate and Maven. + +I've created hibernate.cfg.xml and mapping file contacts.hbm.xml. + +**Once I start it I get an exception:** + +``` +SLF4J: Failed to load class ""org.slf4j.impl.StaticLoggerBinder"". +SLF4J: Defaulting to no-operation (NOP) logger implementation +SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. +Exception in thread ""main"" org.hibernate.MappingException: invalid configuration + at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2241) + at org.hibernate.cfg.Configuration.configure(Configuration.java:2158) + at org.hibernate.cfg.Configuration.configure(Configuration.java:2137) + at main.java.FirstHibernate.com.myhib.CRUDS.CrudsOps.main(CrudsOps.java:15) +Caused by: org.xml.sax.SAXParseException; lineNumber: 54; columnNumber: 129; Attribute ""value"" must be declared for element type ""property"". + at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198) + at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) + at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437) + at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368) + at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325) + at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.addDTDDefaultAttrsAndValidate(XMLDTDValidator.java:1253) + at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java:1917) + at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(XMLDTDValidator.java:763) + at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:353) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607) + at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488) + at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835) + at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764) + at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123) + at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210) + at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568) + at org.dom4j.io.SAXReader.read(SAXReader.java:465) + at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2238) + ... 3 more + +``` + +**Here is my hibernate.cfg.xml** + +``` + + + + + + + + + + org.postgresql.Driver + jdbc:postgresql://localhost:5432/hibernatedb + postgres + postgres + + + 1 + + + org.hibernate.dialect.PostgreSQLDialect + + + org.hibernate.cache.internal.NoCacheProvider + + + true + + + create + + + + value + + + + + + + + + +``` + +**contacts.hbm.xml** + +``` + + + + + + + + + + + + + + +``` + +What can be a source of that exception? + +P.S. Java classes could be posted if they are needed. + +**--UPDATE--** + +when I changed + +``` + + +``` + +to + +``` +org.hibernate.connection.DriverManagerConnectionProvider + +``` + +I got such exception + +``` +SLF4J: Failed to load class ""org.slf4j.impl.StaticLoggerBinder"". +SLF4J: Defaulting to no-operation (NOP) logger implementation +SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. +Exception in thread ""main"" org.hibernate.MappingException: invalid configuration + at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2241) + at org.hibernate.cfg.Configuration.configure(Configuration.java:2158) + at org.hibernate.cfg.Configuration.configure(Configuration.java:2137) + at main.java.FirstHibernate.com.myhib.CRUDS.CrudsOps.main(CrudsOps.java:15) +Caused by: org.xml.sax.SAXParseException; lineNumber: 59; columnNumber: 76; Attribute ""resources"" must be declared for element type ""mapping"". + at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198) + at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) + at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437) + at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368) + at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325) + at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.addDTDDefaultAttrsAndValidate(XMLDTDValidator.java:1253) + at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java:1917) + at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(XMLDTDValidator.java:763) + at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:353) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607) + at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488) + at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835) + at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764) + at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123) + at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210) + at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568) + at org.dom4j.io.SAXReader.read(SAXReader.java:465) + at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2238) + ... 3 more + +``` + +**--UPDATE 2--** + +Once I changed + +*Are you sure it's and not ? Because in the DTD I can only see 'resource' and not 'resources' attribute of the element 'mapping'. – Balázs Mária Németh 5 mins ago* + +I got + +``` +SLF4J: Failed to load class ""org.slf4j.impl.StaticLoggerBinder"". +SLF4J: Defaulting to no-operation (NOP) logger implementation +SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. +Exception in thread ""main"" org.hibernate.InvalidMappingException: Unable to read XML + at org.hibernate.util.xml.MappingReader.readMappingDocument(MappingReader.java:101) + at org.hibernate.cfg.Configuration.add(Configuration.java:513) + at org.hibernate.cfg.Configuration.add(Configuration.java:509) + at org.hibernate.cfg.Configuration.add(Configuration.java:716) + at org.hibernate.cfg.Configuration.addResource(Configuration.java:801) + at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2344) + at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2310) + at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2290) + at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2243) + at org.hibernate.cfg.Configuration.configure(Configuration.java:2158) + at org.hibernate.cfg.Configuration.configure(Configuration.java:2137) + at main.java.FirstHibernate.com.myhib.CRUDS.CrudsOps.main(CrudsOps.java:15) +Caused by: org.xml.sax.SAXParseException; lineNumber: 6; columnNumber: 20; Document root element ""hibernate-mapping"", must match DOCTYPE root ""hibernate-configuration"". + at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198) + at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) + at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437) + at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368) + at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325) + at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.rootElementSpecified(XMLDTDValidator.java:1599) + at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java:1877) + at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(XMLDTDValidator.java:742) + at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:376) + at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:602) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3063) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:881) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607) + at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488) + at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835) + at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764) + at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123) + at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210) + at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568) + at org.dom4j.io.SAXReader.read(SAXReader.java:465) + at org.hibernate.util.xml.MappingReader.readMappingDocument(MappingReader.java:75) + ... 11 more + +``` + +**--UPDATE 3--** + +That helped me + +``` +And finally it looks like there's a problem with contacts.hbm.xml. Change + + +to + + + +``` + +Now I got such exception: + +``` +SLF4J: Failed to load class ""org.slf4j.impl.StaticLoggerBinder"". +SLF4J: Defaulting to no-operation (NOP) logger implementation +SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. +Exception in thread ""main"" org.hibernate.InvalidMappingException: Unable to read XML + at org.hibernate.util.xml.MappingReader.readMappingDocument(MappingReader.java:101) + at org.hibernate.cfg.Configuration.add(Configuration.java:513) + at org.hibernate.cfg.Configuration.add(Configuration.java:509) + at org.hibernate.cfg.Configuration.add(Configuration.java:716) + at org.hibernate.cfg.Configuration.addResource(Configuration.java:801) + at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2344) + at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2310) + at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2290) + at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2243) + at org.hibernate.cfg.Configuration.configure(Configuration.java:2158) + at org.hibernate.cfg.Configuration.configure(Configuration.java:2137) + at main.java.FirstHibernate.com.myhib.CRUDS.CrudsOps.main(CrudsOps.java:15) +Caused by: org.xml.sax.SAXParseException; lineNumber: 11; columnNumber: 63; Element type ""propetry"" must be declared. + at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198) + at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) + at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437) + at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368) + at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325) + at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java:1906) + at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.emptyElement(XMLDTDValidator.java:763) + at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:353) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607) + at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116) + at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488) + at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835) + at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764) + at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123) + at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210) + at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568) + at org.dom4j.io.SAXReader.read(SAXReader.java:465) + at org.hibernate.util.xml.MappingReader.readMappingDocument(MappingReader.java:75) + ... 11 more + +```",2013/03/06,"['https://Stackoverflow.com/questions/15243891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/304911/']","To get you started, I'll give an example with `S3` classes: + +``` +# create an S3 class using setClass: +setClass(""S3_class"", representation(""list"")) +# create an object of S3_class +S3_obj <- new(""S3_class"", list(x=sample(10), y=sample(10))) + +``` + +Now, you can function-overload internal functions, for example, `length` function to your class as (you can also `operator-overload`): + +``` +length.S3_class <- function(x) sapply(x, length) +# which allows you to do: +length(S3_obj) + +# x y +# 10 10 + +``` + +Or alternatively, you can have your own function with whatever name, where you can check if the object is of class `S3_class` and do something: + +``` +len <- function(x) { + if (class(x) != ""S3_class"") { + stop(""object not of class S3_class"") + } + sapply(x, length) +} + +> len(S3_obj) +# x y +# 10 10 + +> len(1:10) +# Error in len(1:10) : object not of class S3_class + +``` + +It is a bit hard to explain S4 (like S3) as there are quite a bit of terms and things to know of (they are not difficult, just different). I suggest you go through the links provided under comments for those (and for S3 as well, as my purpose here was to show you an example of how it's done).","R also has function closures, which fits your example quite nicely + +``` +test = function() { + len = 0 + set_length = function(l = 0) len <<-l + get_length = function() len + return(list(set_length=set_length, get_length=get_length)) +} + +``` + +this gives: + +``` +R> m = test() +R> m$set_length(10) +R> m$get_length() +[1] 10 +R> m$set_length() +R> m$get_length() +[1] 0 + +```" +28200567,"I'd like to disable some features of a web app I'm building, if the browser is Tor Browser. Can I inside the browser itself (client side, not server side) find out if the browser is Tor Browser? + +I would prefer a solution that didn't issue any HTTP requests to match the browser's IP against Tor exit nodes. + +Background: In my case, Tor Browser pops up a dialog that asks the user *""Should Tor Browser allow this website to extract HTML5 canvas image data?""*, because, says Tor Browser, canvas image data can be used to uniquely identify a browser. + +**Update:** After reading the answers below: Perhaps the best solution in my case, is to keep a list of Tor exit nodes server side (an up-to-date list, refreshed periodically), and when a browser loads the page, I set a variable in a ` + +``` + +It always gets the first `$('.summernote').eq(0).code();` summernote code never the second or third one. + +What I'm trying to do is when each summernote gets a blur, have that code update in a hidden textarea to submit back to the database. + +(btw) I am initilizing the summer notes like this: + +``` + + +```",2014/03/24,"['https://Stackoverflow.com/questions/22619110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3367639/']","After selecting all summernote's you need to access their attributes by specifying one element like: + +``` + + +```","I Finally got the code working for multiple summernote editors and image uploading! + +To fix + +> +> ""undefined"" +> +> +> + +, try: + +> +> var id = $(obj).data('id'); +> +> +> + +to + +> +> var id= $(obj).attr('id')) +> +> +> + +Source: + + + +Regards!" +22619110,"I am trying to get the code of a specific summer note div with multiple ones on a single page. + +My summer notes are created from a database with php as follows: + +``` +
+ + +
contentName; ?>""> +
""> + content; ?> +
+
+ +
+ +``` + +And then my javascript is: + +``` + + +``` + +It always gets the first `$('.summernote').eq(0).code();` summernote code never the second or third one. + +What I'm trying to do is when each summernote gets a blur, have that code update in a hidden textarea to submit back to the database. + +(btw) I am initilizing the summer notes like this: + +``` + + +```",2014/03/24,"['https://Stackoverflow.com/questions/22619110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3367639/']","After selecting all summernote's you need to access their attributes by specifying one element like: + +``` + + +```","To display multiple editors on a page, you need to place more than two `
` elements in HTML. + +**Example:** + +``` +
summernote 1
+
summernote 2
+ +``` + +**Then run summernote with jQuery selector.** + +``` +$(document).ready(function() { + $('.summernote').summernote(); +}); + +``` + +For more information [click](http://summernote.org/examples/#multiple-editor) + +Note: Multiple Editor summernote not work with `id`" +22619110,"I am trying to get the code of a specific summer note div with multiple ones on a single page. + +My summer notes are created from a database with php as follows: + +``` +
+ + +
contentName; ?>""> +
""> + content; ?> +
+
+ +
+ +``` + +And then my javascript is: + +``` + + +``` + +It always gets the first `$('.summernote').eq(0).code();` summernote code never the second or third one. + +What I'm trying to do is when each summernote gets a blur, have that code update in a hidden textarea to submit back to the database. + +(btw) I am initilizing the summer notes like this: + +``` + + +```",2014/03/24,"['https://Stackoverflow.com/questions/22619110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3367639/']","After selecting all summernote's you need to access their attributes by specifying one element like: + +``` + + +```","For anyone looking to use summernote to output multiple content with `foreach`, loop/repetitive statement etc + +Summernote works for the first output only but you can make it work for others by using the ***class twice***: + +``` +
+ +``` + +Provided your script is like this: + +``` + + +```" +22619110,"I am trying to get the code of a specific summer note div with multiple ones on a single page. + +My summer notes are created from a database with php as follows: + +``` +
+ + +
contentName; ?>""> +
""> + content; ?> +
+
+ +
+ +``` + +And then my javascript is: + +``` + + +``` + +It always gets the first `$('.summernote').eq(0).code();` summernote code never the second or third one. + +What I'm trying to do is when each summernote gets a blur, have that code update in a hidden textarea to submit back to the database. + +(btw) I am initilizing the summer notes like this: + +``` + + +```",2014/03/24,"['https://Stackoverflow.com/questions/22619110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3367639/']","After selecting all summernote's you need to access their attributes by specifying one element like: + +``` + + +```","if you are using summernote inside a textarea in a form and you intend to apply it on multiple textarea(s) on the same form, replace `id=summernote` with `class=""summernote""` + +Dont forget to do the same on your initialisation script + +``` + + +``` + +Example + +``` + + + + +```" +22619110,"I am trying to get the code of a specific summer note div with multiple ones on a single page. + +My summer notes are created from a database with php as follows: + +``` +
+ + +
contentName; ?>""> +
""> + content; ?> +
+
+ +
+ +``` + +And then my javascript is: + +``` + + +``` + +It always gets the first `$('.summernote').eq(0).code();` summernote code never the second or third one. + +What I'm trying to do is when each summernote gets a blur, have that code update in a hidden textarea to submit back to the database. + +(btw) I am initilizing the summer notes like this: + +``` + + +```",2014/03/24,"['https://Stackoverflow.com/questions/22619110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3367639/']","To display multiple editors on a page, you need to place more than two `
` elements in HTML. + +**Example:** + +``` +
summernote 1
+
summernote 2
+ +``` + +**Then run summernote with jQuery selector.** + +``` +$(document).ready(function() { + $('.summernote').summernote(); +}); + +``` + +For more information [click](http://summernote.org/examples/#multiple-editor) + +Note: Multiple Editor summernote not work with `id`","I Finally got the code working for multiple summernote editors and image uploading! + +To fix + +> +> ""undefined"" +> +> +> + +, try: + +> +> var id = $(obj).data('id'); +> +> +> + +to + +> +> var id= $(obj).attr('id')) +> +> +> + +Source: + + + +Regards!" +22619110,"I am trying to get the code of a specific summer note div with multiple ones on a single page. + +My summer notes are created from a database with php as follows: + +``` +
+ + +
contentName; ?>""> +
""> + content; ?> +
+
+ +
+ +``` + +And then my javascript is: + +``` + + +``` + +It always gets the first `$('.summernote').eq(0).code();` summernote code never the second or third one. + +What I'm trying to do is when each summernote gets a blur, have that code update in a hidden textarea to submit back to the database. + +(btw) I am initilizing the summer notes like this: + +``` + + +```",2014/03/24,"['https://Stackoverflow.com/questions/22619110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3367639/']","To display multiple editors on a page, you need to place more than two `
` elements in HTML. + +**Example:** + +``` +
summernote 1
+
summernote 2
+ +``` + +**Then run summernote with jQuery selector.** + +``` +$(document).ready(function() { + $('.summernote').summernote(); +}); + +``` + +For more information [click](http://summernote.org/examples/#multiple-editor) + +Note: Multiple Editor summernote not work with `id`","For anyone looking to use summernote to output multiple content with `foreach`, loop/repetitive statement etc + +Summernote works for the first output only but you can make it work for others by using the ***class twice***: + +``` +
+ +``` + +Provided your script is like this: + +``` + + +```" +22619110,"I am trying to get the code of a specific summer note div with multiple ones on a single page. + +My summer notes are created from a database with php as follows: + +``` +
+ + +
contentName; ?>""> +
""> + content; ?> +
+
+ +
+ +``` + +And then my javascript is: + +``` + + +``` + +It always gets the first `$('.summernote').eq(0).code();` summernote code never the second or third one. + +What I'm trying to do is when each summernote gets a blur, have that code update in a hidden textarea to submit back to the database. + +(btw) I am initilizing the summer notes like this: + +``` + + +```",2014/03/24,"['https://Stackoverflow.com/questions/22619110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3367639/']","To display multiple editors on a page, you need to place more than two `
` elements in HTML. + +**Example:** + +``` +
summernote 1
+
summernote 2
+ +``` + +**Then run summernote with jQuery selector.** + +``` +$(document).ready(function() { + $('.summernote').summernote(); +}); + +``` + +For more information [click](http://summernote.org/examples/#multiple-editor) + +Note: Multiple Editor summernote not work with `id`","if you are using summernote inside a textarea in a form and you intend to apply it on multiple textarea(s) on the same form, replace `id=summernote` with `class=""summernote""` + +Dont forget to do the same on your initialisation script + +``` + + +``` + +Example + +``` + + + + +```" +226645,"Is ""lemonade"" countable or uncountable? Could I say the following sentence? + +> +> Could you please bring me a lemonade? +> +> +> + +Or *must* I say ""a glass of lemonade"" ?",2019/10/03,"['https://ell.stackexchange.com/questions/226645', 'https://ell.stackexchange.com', 'https://ell.stackexchange.com/users/92124/']","""Lemonade"" is usually uncountable, but it can be used as a countable noun to mean ""a glass of lemonade"". It is uncommon, but possible, to treat ""lemonade"" as a countable noun. + +This applies not only to lemonade but to most beverages.","> +> Or must I say ""a glass of lemonade"" ? +> +> +> + +You don't need to. + +From Collins + +> +> A glass of lemonade can be referred to as *a lemonade*. Example: I'm going to get you a lemonade. +> +> +> + +Take a look at the following Q and A. + +> +> *What can I get you?* +> +> +> * A diet coke, please! +> * A can of diet coke, please! +> +> +> + +They are both idiomatic. The ""a can"" or ""a glass"" is implied." +114417,"Mending a bug in our SAP BW web application, I need to call two javascript functions from the web framework library upon page load. The problem is that each of these functions reloads the page as a side-effect. In addition, I don't have access to modify these functions. + +Any great ideas on how to execute a piece of code on ""real"" page load, then another piece of code on the subsequent load caused by this function, and then execute no code the third reload? + +My best idea so far it to set a cookie on each go to determine what to run. I don't greatly love this solution. Anything better would be very welcome. And by the way, I do realize loading a page three times is absolutely ridiculous, but that's how we roll with SAP.",2008/09/22,"['https://Stackoverflow.com/questions/114417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333/']","A cookie would work just fine. Or you could modify the query string each time with a ""mode=x"" or ""load=x"" parameter. + +This would present a problem if the user tries to bookmark the final page, though. If that's an option, the cookie solution is fine. I would guess they need cookies enabled to get that far in the app anyway?","A cookie, or pass a query string parameter indicating which javascript function has been run. We had to do something along these lines to trip out a piece of our software. That's really the best I got." +114417,"Mending a bug in our SAP BW web application, I need to call two javascript functions from the web framework library upon page load. The problem is that each of these functions reloads the page as a side-effect. In addition, I don't have access to modify these functions. + +Any great ideas on how to execute a piece of code on ""real"" page load, then another piece of code on the subsequent load caused by this function, and then execute no code the third reload? + +My best idea so far it to set a cookie on each go to determine what to run. I don't greatly love this solution. Anything better would be very welcome. And by the way, I do realize loading a page three times is absolutely ridiculous, but that's how we roll with SAP.",2008/09/22,"['https://Stackoverflow.com/questions/114417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333/']","A cookie would work just fine. Or you could modify the query string each time with a ""mode=x"" or ""load=x"" parameter. + +This would present a problem if the user tries to bookmark the final page, though. If that's an option, the cookie solution is fine. I would guess they need cookies enabled to get that far in the app anyway?",Use a cookie or set a hidden field value. My vote would be for the field value. +114417,"Mending a bug in our SAP BW web application, I need to call two javascript functions from the web framework library upon page load. The problem is that each of these functions reloads the page as a side-effect. In addition, I don't have access to modify these functions. + +Any great ideas on how to execute a piece of code on ""real"" page load, then another piece of code on the subsequent load caused by this function, and then execute no code the third reload? + +My best idea so far it to set a cookie on each go to determine what to run. I don't greatly love this solution. Anything better would be very welcome. And by the way, I do realize loading a page three times is absolutely ridiculous, but that's how we roll with SAP.",2008/09/22,"['https://Stackoverflow.com/questions/114417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333/']","A cookie would work just fine. Or you could modify the query string each time with a ""mode=x"" or ""load=x"" parameter. + +This would present a problem if the user tries to bookmark the final page, though. If that's an option, the cookie solution is fine. I would guess they need cookies enabled to get that far in the app anyway?","This might be a cute case for using window.name, 'the property that survives page reloads'." +114417,"Mending a bug in our SAP BW web application, I need to call two javascript functions from the web framework library upon page load. The problem is that each of these functions reloads the page as a side-effect. In addition, I don't have access to modify these functions. + +Any great ideas on how to execute a piece of code on ""real"" page load, then another piece of code on the subsequent load caused by this function, and then execute no code the third reload? + +My best idea so far it to set a cookie on each go to determine what to run. I don't greatly love this solution. Anything better would be very welcome. And by the way, I do realize loading a page three times is absolutely ridiculous, but that's how we roll with SAP.",2008/09/22,"['https://Stackoverflow.com/questions/114417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333/']","A cookie, or pass a query string parameter indicating which javascript function has been run. We had to do something along these lines to trip out a piece of our software. That's really the best I got.",Use a cookie or set a hidden field value. My vote would be for the field value. +114417,"Mending a bug in our SAP BW web application, I need to call two javascript functions from the web framework library upon page load. The problem is that each of these functions reloads the page as a side-effect. In addition, I don't have access to modify these functions. + +Any great ideas on how to execute a piece of code on ""real"" page load, then another piece of code on the subsequent load caused by this function, and then execute no code the third reload? + +My best idea so far it to set a cookie on each go to determine what to run. I don't greatly love this solution. Anything better would be very welcome. And by the way, I do realize loading a page three times is absolutely ridiculous, but that's how we roll with SAP.",2008/09/22,"['https://Stackoverflow.com/questions/114417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4333/']","A cookie, or pass a query string parameter indicating which javascript function has been run. We had to do something along these lines to trip out a piece of our software. That's really the best I got.","This might be a cute case for using window.name, 'the property that survives page reloads'." +26933422,"Who can share practical examples of the use of the `GET_LOCK` function? + +Example function: + +``` +mysql> SELECT GET_LOCK('b',10); ++------------------+ +| GET_LOCK('b',10) | ++------------------+ +| 1 | ++------------------+ +1 row in set (0.00 sec) + +mysql> SELECT IS_FREE_LOCK('b'); ++-------------------+ +| IS_FREE_LOCK('b') | ++-------------------+ +| 0 | ++-------------------+ +1 row in set (0.00 sec) + +mysql> SELECT RELEASE_LOCK('b'); ++-------------------+ +| RELEASE_LOCK('b') | ++-------------------+ +| 1 | ++-------------------+ +1 row in set (0.00 sec) + +mysql> SELECT IS_FREE_LOCK('b'); ++-------------------+ +| IS_FREE_LOCK('b') | ++-------------------+ +| 1 | ++-------------------+ +1 row in set (0.00 sec) + +``` + +Thank you.",2014/11/14,"['https://Stackoverflow.com/questions/26933422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2645137/']","This should be enough: + +``` +self.collectionView.pagingEnabled = YES; + +``` + +Swift version: + +``` +self.collectionView.pagingEnabled = true + +```","If you want your cells to be moved only one at a time then you need to set the frame of cell equals to the collection view and then set the collectionView's paging enabled as below, + +``` +[collectionView setPagingEnabled:YES]; + +``` + +or + +``` +collectionView.pagingEnabled=YES; + +```" +29214407,"I have a Queue of an abstract class KVP. I queue 2 different objects which inherit from KVP. Everything works fine when I serialize the queue, but since KVP cannot be constructed it fails on deserialization. + +If it was a single non generic object I could deserialize as dynamic, but I'm not sure how to deserialize a queue that could hold both events and IDs. + +Sample code: + +``` +public virtual async Task LoadFromFile(string FileName, bool addToExistingQueue,bool DeleteFileAfterLoad = true) + { + try + { + IFile File = await PCLStorage.FileSystem.Current.LocalStorage.GetFileAsync(FileName); + var serializedText = await File.ReadAllTextAsync(); + var mQueue = JsonConvert.DeserializeObject>(serializedText,jss); + if (!addToExistingQueue) + { + _queue = new ConcurrentQueue(); + } + while (mQueue.Count > 0) + { + _queue.Enqueue(mQueue.Dequeue()); + } + + if (DeleteFileAfterLoad) + { + await File.DeleteAsync(); + } + return true; + + } + catch (Exception ex) + { + Debug.WriteLine(""Could not load File. Exception Message: "" + ex.Message); + return false; + } + + } + public virtual async Task WriteToFile(string FileName) + { + try + { + Debug.WriteLine(""Writing File: "" + FileName); + var File = await FileSystem.Current.LocalStorage.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting); + var serializedText = JsonConvert.SerializeObject(_queue.ToList(),jss); + await File.WriteAllTextAsync(serializedText); + return true; + } + catch (Exception ex) + { + Debug.WriteLine(""Could not write File with exception message: "" + ex.Message); + return false; + } + + } + +```",2015/03/23,"['https://Stackoverflow.com/questions/29214407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1104177/']","You could + +1. Enable [TypeNameHandling](http://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonSerializerSettings_TypeNameHandling.htm) (in both serialization and deserialization): + +``` + var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }; + var serializedText= JsonConvert.SerializeObject(mQueue, settings); + +``` + +And then later + +``` + var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }; + var mQueue = JsonConvert.DeserializeObject>(serializedText, settings); + +``` + +This adds an extra `""$type""` property to your polymorphic classes, as is described [here](http://james.newtonking.com/archive/2010/08/13/json-net-3-5-release-8-3-5-final). + +Before choosing this solution, for a discussion of possible security concerns using `TypeNameHandling`, see [TypeNameHandling caution in Newtonsoft Json](https://stackoverflow.com/q/39565954/3744182) and [How to configure Json.NET to create a vulnerable web API](https://www.alphabot.com/security/blog/2017/net/How-to-configure-Json.NET-to-create-a-vulnerable-web-API.html). +2. Write a custom converter that looks at the actual properties and chooses which derived class to use, as is discussed here: [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/questions/19307752/deserializing-polymorphic-json-classes-without-type-information-using-json-net). This avoids the need for the extra `""$type""` property.","This should work if you use the following setting in the JSON.NET serialiser settings: + +``` +var settings = new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.Auto}; + +``` + +This will encode the object type into the JSON stream, which will help the deserializer determined the specific object type to construct during de-serialization." +18659832,"I've been wondering, is there a nice way to make `UIButtons` with multi-line `titleLabel` in Interface Builder? I've found none and puttin a separate `UILabel` on top of each button and tracking it's color on press and other events is not very straightforward. + +Maybe there are better alternatives done in code if there's no such way in IB?",2013/09/06,"['https://Stackoverflow.com/questions/18659832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1313939/']","**Code:** + +To allow multiple line you can use: + +``` +button.titleLabel.lineBreakMode = UILineBreakModeWordWrap; +button.titleLabel.textAlignment = UITextAlignmentCenter; +[button setTitle: @""Line1\nLine2"" forState: UIControlStateNormal]; + +``` + +In **iOS 6**, `UILineBreakModeWordWrap` and `UITextAlignmentCenter` are deprecated, so use: + +``` +button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping; +button.titleLabel.textAlignment = NSTextAlignmentCenter; + +``` + +**Interface Builder:** + +* In interface builder select *UIButton* +* on the right side Utilities pane under *Attributes Inspector*, you'll see an option for *Line Break* +* Choose *Word Wrap*","You can do solely in Interface Builder a couple ways. + +* First by simply setting the wrap feature. This offers limited customizability though. +* For more customizability, change the ""Plain Text"" to ""Attributed Text"" and then you can do most things without any code." +18659832,"I've been wondering, is there a nice way to make `UIButtons` with multi-line `titleLabel` in Interface Builder? I've found none and puttin a separate `UILabel` on top of each button and tracking it's color on press and other events is not very straightforward. + +Maybe there are better alternatives done in code if there's no such way in IB?",2013/09/06,"['https://Stackoverflow.com/questions/18659832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1313939/']","**Code:** + +To allow multiple line you can use: + +``` +button.titleLabel.lineBreakMode = UILineBreakModeWordWrap; +button.titleLabel.textAlignment = UITextAlignmentCenter; +[button setTitle: @""Line1\nLine2"" forState: UIControlStateNormal]; + +``` + +In **iOS 6**, `UILineBreakModeWordWrap` and `UITextAlignmentCenter` are deprecated, so use: + +``` +button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping; +button.titleLabel.textAlignment = NSTextAlignmentCenter; + +``` + +**Interface Builder:** + +* In interface builder select *UIButton* +* on the right side Utilities pane under *Attributes Inspector*, you'll see an option for *Line Break* +* Choose *Word Wrap*","Just to mention if one does not want word wrap but still want to achieve multi line title on a UIButton it can be done by setting lineBreakMode before numberOfLines, +This is because lineBreakMode seems to cancel out numberOfLines set hence we are doing it in this order. + +Swift: + +> +> button.titleLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail +> +> +> button.titleLabel?.numberOfLines = 2 +> +> +> button.setTitle(myTitle, for: UIControlState.normal) +> +> +>" +18659832,"I've been wondering, is there a nice way to make `UIButtons` with multi-line `titleLabel` in Interface Builder? I've found none and puttin a separate `UILabel` on top of each button and tracking it's color on press and other events is not very straightforward. + +Maybe there are better alternatives done in code if there's no such way in IB?",2013/09/06,"['https://Stackoverflow.com/questions/18659832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1313939/']","**Code:** + +To allow multiple line you can use: + +``` +button.titleLabel.lineBreakMode = UILineBreakModeWordWrap; +button.titleLabel.textAlignment = UITextAlignmentCenter; +[button setTitle: @""Line1\nLine2"" forState: UIControlStateNormal]; + +``` + +In **iOS 6**, `UILineBreakModeWordWrap` and `UITextAlignmentCenter` are deprecated, so use: + +``` +button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping; +button.titleLabel.textAlignment = NSTextAlignmentCenter; + +``` + +**Interface Builder:** + +* In interface builder select *UIButton* +* on the right side Utilities pane under *Attributes Inspector*, you'll see an option for *Line Break* +* Choose *Word Wrap*","In the case you are using only plain XCode 9.4: + +Set Line Break to any option (to enable numberOfLines) in the Attributes inspector: + +[![The first step in XCode](https://i.stack.imgur.com/Q1Rd1.png)](https://i.stack.imgur.com/Q1Rd1.png) + +Then you can set KeyPath as + +``` +titleLabel.numberOfLines + +``` + +in the Identity inspector: + +[![The second step in XCode](https://i.stack.imgur.com/5oZoM.png)](https://i.stack.imgur.com/5oZoM.png)" +18659832,"I've been wondering, is there a nice way to make `UIButtons` with multi-line `titleLabel` in Interface Builder? I've found none and puttin a separate `UILabel` on top of each button and tracking it's color on press and other events is not very straightforward. + +Maybe there are better alternatives done in code if there's no such way in IB?",2013/09/06,"['https://Stackoverflow.com/questions/18659832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1313939/']","You can do solely in Interface Builder a couple ways. + +* First by simply setting the wrap feature. This offers limited customizability though. +* For more customizability, change the ""Plain Text"" to ""Attributed Text"" and then you can do most things without any code.","Just to mention if one does not want word wrap but still want to achieve multi line title on a UIButton it can be done by setting lineBreakMode before numberOfLines, +This is because lineBreakMode seems to cancel out numberOfLines set hence we are doing it in this order. + +Swift: + +> +> button.titleLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail +> +> +> button.titleLabel?.numberOfLines = 2 +> +> +> button.setTitle(myTitle, for: UIControlState.normal) +> +> +>" +18659832,"I've been wondering, is there a nice way to make `UIButtons` with multi-line `titleLabel` in Interface Builder? I've found none and puttin a separate `UILabel` on top of each button and tracking it's color on press and other events is not very straightforward. + +Maybe there are better alternatives done in code if there's no such way in IB?",2013/09/06,"['https://Stackoverflow.com/questions/18659832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1313939/']","In the case you are using only plain XCode 9.4: + +Set Line Break to any option (to enable numberOfLines) in the Attributes inspector: + +[![The first step in XCode](https://i.stack.imgur.com/Q1Rd1.png)](https://i.stack.imgur.com/Q1Rd1.png) + +Then you can set KeyPath as + +``` +titleLabel.numberOfLines + +``` + +in the Identity inspector: + +[![The second step in XCode](https://i.stack.imgur.com/5oZoM.png)](https://i.stack.imgur.com/5oZoM.png)","Just to mention if one does not want word wrap but still want to achieve multi line title on a UIButton it can be done by setting lineBreakMode before numberOfLines, +This is because lineBreakMode seems to cancel out numberOfLines set hence we are doing it in this order. + +Swift: + +> +> button.titleLabel?.lineBreakMode = NSLineBreakMode.byTruncatingTail +> +> +> button.titleLabel?.numberOfLines = 2 +> +> +> button.setTitle(myTitle, for: UIControlState.normal) +> +> +>" +77623,"knowing that the characteristic of an integral domain is $0$ or a prime number, i want to prove that the characteristic of a finite field $F\_n$ is a prime number, that is $\operatorname{char}(F\_n)\not = 0$. the proof i'm reading uses the fact that within $e,2e,3e,\ldots$ there are two that are necessarily equal $ie=(i+k)e$ so $ke=0$ for some positive $k$. But can i say the following argument: +$F\_n=\{0,e,x\_1,\ldots ,x\_{n-2}\}$ ( $e$ is the multiplicative identity ) and since $e\not = 0$ then $e\not = 2e\not =\cdots ,\not = ne$ so we have $n$ distinct elements $ie, i=1,\ldots,n$ of $F\_n$ hence one of them must equal $0$; $ie=0$ for some $i\in \{2,\ldots,n\}$, moreover the trivial field with one element $e=0$ has obviously characteristic $1$. Is there a non-trivial field where $e=0$?",2011/10/31,"['https://math.stackexchange.com/questions/77623', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10463/']","Let $1$ denote the *multiplicative* identity of the field. Then, $1 \neq 0$ where $0$ is the *additive* identity. So every field must have at least two elements: your notion of a field with one element $0$ is not correct. + +So, since the field contains $1$, it contains $1+1$, $1+1+1$, $1 + 1 + 1 + 1, \ldots, 1 + 1 + \cdots + 1$ (where the last sum has $n$ $1$s in it). All these $n$ sums cannot be distinct since the field has only $n-1$ *nonzero* elements. So, +for some distinct $i$ and $j$, the sum of $i$ $1$s must equal the sum of $j$ $1$s, +and by subtraction, the sum of $|i-j|$ $1$s must equal $0$. The smallest number of $1$s that sum to $0$ is called the characteristic of the finite field, and the characteristic must be a prime number. This is because if the +characteristic were a composite +number $ab$, then the sum of $a$ $1$s multiplied by the sum of $b$ $1$s, +which equals the sum of $ab$ $1$s by the distributive law, would equal +$0$, that is, the product of two nonzero elements would equal $0$, +which cannot happen in a field.","I feel as though the answer you are stating is making things more difficult. As you pointed out all integral domains are either characterstic zero or of prime characteristic, and so in particular all fields are of prime characteristic or zero characteristic. But, if a field has characteristic zero you know that it's multiplicative identity has infinite additive order and all finite groups (and thus all finite fields) have no elements of infinite order (for the reason FIRST reason you stated). Another route is, if you know group theory (but this is really overkill compared to the other two arguments) to note that $|\mathbb{F}\_q|\mathbb{F}\_q=0$ by Lagrange's theorem, and so all elements have order dividing $|\mathbb{F}\_q|$. + +To answer your last question, no, there are no non-trivial examples where $1=0$ since the ONLY ring with such an identity is the zero ring." +33710057,"So I'm working on implementing an insert method for a binary tree. + +From what I can tell, the problem is that the changes made in the arguments of the function don't get properly returned back to main(). + +``` +static void addChild(Child c, Child tree){ + if(tree==null){ + tree=c; + } + else{ + if(c.cid>tree.cid){ + addChild(c, tree.lc); + } + else if(c.cidtree.cid + addTree(c, tree.lc); + // tree != null + // c.cid>tree.cid + addTree(c, tree.lc); + // tree == null + tree = c; // Won't be effective + return; + return; + +``` + +That locally mutates the **tree** reference and has no effect outside this recursive call. + +The trick here is to update the parent tree's left or right subtree at this point. + +``` +static Child addChild(Child c, Child tree){ + if(tree==null){ + return c; + } + else{ + if(c.cid>tree.cid){ + tree.lc = addChild(c, tree.lc); + } + else if(c.cidtree.cid + tree.lc = addTree(c, tree.lc); + // tree != null + // c.cid>tree.cid + tree.lc = addTree(c, tree.lc); + // tree == null + return c; + return tree; + return tree; + +```" +61850588,"Hi so i have table called products, i have some information there like name,netto price,tax etc. I want to add new records named brutto\_price which is automatically calculated as (netto\_price + netto\_price\*tax) or (netto\_price \*1.22 if tax is null) its not allowed to insert null into netto\_price. (tax could be null). +Im doing sth like this + +``` +alter table products add (brutto_price FLOAT DEFAULT netto_price*1.22 ) + + UPDATE products + SET brutto_price = netto_price + netto_price*tax + where + tax is not null; + +``` + +but first query is not working (probably because i use record name in this) any idea?",2020/05/17,"['https://Stackoverflow.com/questions/61850588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13560269/']","You can use + +``` +{(book.authors || []).map(({firstname, lastname}) => `${lastname} ${firstname}`).join("", "")}. + +``` + +This will give you comma separated names + +``` + +{books.length === 0 ? + + {this.state.books.length} List is empty. + : + books.map((book) => ( + + {book.id} + {book.title} + {(book.authors || []).map(({firstname, lastname}) => `${lastname} ${firstname}`)} + {book.description} + {book.language} + {book.price} + {book.action} + + )) +} + + +```","One of the ways to do that: + +``` + +(book.authors || []).map(author => author.firstname + ' ' + author.lastname).join(', ') + +```" +288319,I realized the solution to this problem while I was creating the documentation to ASK this question...so I am posting the answer if for no other reason than to keep me from wasting time on this in the future,2008/11/13,"['https://Stackoverflow.com/questions/288319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2755/']","`toggle()` is pretty buggy at times, i've had it do odd things to checkmarks (unchecking them) and other assorted issues. i'd suggest just handling it using a click event, much less minor annoyances. and this way, you don't have to worry about what state `#lowerDiv` is in in the first place: + +``` +$('#upperDiv').click(function() { + $('#lowerDiv').animate({ + 'opacity' : 'toggle', + }); +}); + +```","If the content to be TOGGLEd is displayed (visible) when the page is rendered the functions would be in the following order, if the content is hidden originally then reverse the functions + +``` + + + + + + + + +
Upper div
+
Lover Div
+ + + +```" +288319,I realized the solution to this problem while I was creating the documentation to ASK this question...so I am posting the answer if for no other reason than to keep me from wasting time on this in the future,2008/11/13,"['https://Stackoverflow.com/questions/288319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2755/']","If the content to be TOGGLEd is displayed (visible) when the page is rendered the functions would be in the following order, if the content is hidden originally then reverse the functions + +``` + + + + + + + + +
Upper div
+
Lover Div
+ + + +```","I know this is a really old question, but just for people that are looking for a quick fix this worked for me: + +a. in the PHP/HTML file: + +``` + + + +``` + +b. in the CSS file: + +``` +#pText {display: none;} + +``` + +It now works even on the first click. It's a simple, quick answer that I hope will be useful." +288319,I realized the solution to this problem while I was creating the documentation to ASK this question...so I am posting the answer if for no other reason than to keep me from wasting time on this in the future,2008/11/13,"['https://Stackoverflow.com/questions/288319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2755/']","`toggle()` is pretty buggy at times, i've had it do odd things to checkmarks (unchecking them) and other assorted issues. i'd suggest just handling it using a click event, much less minor annoyances. and this way, you don't have to worry about what state `#lowerDiv` is in in the first place: + +``` +$('#upperDiv').click(function() { + $('#lowerDiv').animate({ + 'opacity' : 'toggle', + }); +}); + +```","I know this is a really old question, but just for people that are looking for a quick fix this worked for me: + +a. in the PHP/HTML file: + +``` + + + +``` + +b. in the CSS file: + +``` +#pText {display: none;} + +``` + +It now works even on the first click. It's a simple, quick answer that I hope will be useful." +6312748,"I have the code: + +``` +var timer:Timer = new Timer(milliseconds, repititions); +timer.addEventListener(TimerEvent.TIMER, callback); +timer.start(); + +``` + +and if a user click I want to call the callback early. Is there was a way to either force the timer to finish immediately, or stop it and send the `TimerEvent.Timer` on my own? + +I'm looking for something simple like the tween classes `fforward()`. + +*EDIT* + +The Solution was + +``` +timer.dispatchEvent(new TimerEvent(TimerEvent.TIMER)); + +``` + +I was trying to do `timer.dispatchEvent(new TimerEvent(""TIMER""));` which doesn't work.",2011/06/10,"['https://Stackoverflow.com/questions/6312748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/198034/']","``` +var evt:TimerEvent = new TimerEvent(TimerEvent.TIMER); +timer.dispatchEvent(evt); + +```","Have button call a function in my example i call it onDoEvent. + +onDoEvent will then call the timer event callback using the proper ""CLICK"" event. + +``` +import fl.controls.Button + +var milliseconds:int = 3000; +var repititions:int = 0; +var timer:Timer = new Timer(milliseconds, repititions); +timer.addEventListener(TimerEvent.TIMER,onTimerEvent ); + +var btn_start:Button = new Button( ); +btn_start.label = 'start'; +btn_start.x = 0; +btn_start.addEventListener( MouseEvent.CLICK, onStart ); +this.addChild( btn_start ); +function onStart( e:Event ):void{ + timer.start(); +} + +var btn_stop:Button = new Button( ); +btn_stop.label = 'stop'; +btn_stop.x = 150; +btn_stop.addEventListener( MouseEvent.CLICK, onStop ); +this.addChild( btn_stop ); +function onStop( e:Event ):void{ + timer.stop(); +} + +var btn_doEvent:Button = new Button( ); +btn_doEvent.label = 'Trigger Event'; +btn_doEvent.x = 300; +btn_doEvent.addEventListener( MouseEvent.CLICK, onDoEvent ); +this.addChild( btn_doEvent ); +function onDoEvent( e:Event ):void{ + onTimerEvent( new TimerEvent(""CLICK"") ); +} + +function onTimerEvent(e:TimerEvent){ + trace('TimerEvent was triggered'); +} + +```" +6312748,"I have the code: + +``` +var timer:Timer = new Timer(milliseconds, repititions); +timer.addEventListener(TimerEvent.TIMER, callback); +timer.start(); + +``` + +and if a user click I want to call the callback early. Is there was a way to either force the timer to finish immediately, or stop it and send the `TimerEvent.Timer` on my own? + +I'm looking for something simple like the tween classes `fforward()`. + +*EDIT* + +The Solution was + +``` +timer.dispatchEvent(new TimerEvent(TimerEvent.TIMER)); + +``` + +I was trying to do `timer.dispatchEvent(new TimerEvent(""TIMER""));` which doesn't work.",2011/06/10,"['https://Stackoverflow.com/questions/6312748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/198034/']","``` +var evt:TimerEvent = new TimerEvent(TimerEvent.TIMER); +timer.dispatchEvent(evt); + +```","``` +var timer:Timer = new Timer(milliseconds, repititions); +timer.addEventListener(TimerEvent.TIMER, callback); +timer.start(); + +function callback(e:TimerEvent):void{ + //to do what +} + +``` + +to call simpliest way, just call the function like this. + +``` +callback(null); + +```" +35298518,"Hi, + +I have a requirement, i need to modify a ClearQuest schema. This modification is + +done based on the application name(application\_name field)in the form. For a particular application an additional approval from a group is required. For rest of the application needs to be eliminated. + +[![enter image description here](https://i.stack.imgur.com/E7NvE.jpg)](https://i.stack.imgur.com/E7NvE.jpg) + +Is there any way this can be achieved? + +Thanks",2016/02/09,"['https://Stackoverflow.com/questions/35298518', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3437212/']","For just bash commands, it's possible to get system commands to work. For example, in the IRkernel: + +``` +system(""echo 'hi'"", intern=TRUE) + +``` + +Output: + +``` +'hi' + +``` + +Or to see the first 5 lines of a file: + +``` +system(""head -5 data/train.csv"", intern=TRUE) + +``` + +As IPython magics are available in the IPython kernel (but not in the IRkernel), I did a quick check if it was possible to access these using the `rPython` and `PythonInR` libraries. However, the issue is that `get_ipython()` isn't visible to the Python code, so none of the following worked: + +``` +library(""rPython"") +rPython::python.exec(""from IPython import get_ipython; get_ipython().run_cell_magic('writefile', 'test.txt', 'This is a test')"") + +library(""PythonInR"") +PythonInR::pyExec(""from IPython import get_ipython; get_ipython().run_cell_magic('head -5 data/test.csv')"") + +```","A cosmetic improvement to the output of `system` can be obtained by wrapping the call in `cat` and specify `'\n'` as the separator, which displays the output on separate lines instead of separated by whitespaces which is the default for character vectors. This is very useful for commands like `tree`, since the format of the output makes little sense unless separated by newlines. + +Compare the following for a sample directory named `test`: + +**Bash** + +``` +$ tree test +test +├── A1.tif +├── A2.tif +├── A3.tif +├── README +└── src + ├── sample.R + └── sample2.R + +1 directory, 6 files + +``` + +**R in Jupyter Notebook** + +`system` only, difficult to comprehend output: + +``` +> system('tree test', intern=TRUE) + +'test' '├── A1.tif' '├── A2.tif' '├── A3.tif' '├── README' '└── src' ' ├── sample.R' ' └── sample2.R' '' '1 directory, 6 files + +``` + +`cat` + `system`, output looks like in bash: + +``` +> cat(system('tree test', intern=TRUE), sep='\n') + +test +├── A1.tif +├── A2.tif +├── A3.tif +├── README +└── src + ├── sample.R + └── sample2.R + +1 directory, 6 files + +``` + +Note that for commands like `ls`, the above would introduce a newline where outputs are normally separated by a space in bash. + +You can create a function to save you some typing: + +``` +> # ""jupyter shell"" function +> js <- function(shell_command){ +> cat(system(shell_command, intern=TRUE), sep='\n') +> } +> +> # brief syntax for shell commands +> js('tree test') + +```" +667040,"I have a server machine (A) which has ssh installed, along with a webserver. + +How do I forward the port with the webserver to my local machine (B). + +I should be able to browse to `http://localhost:forwardedport` + +Is this LOCAL or REMOTE port fowarding? Here's what I've tried. + +``` +ssh -L 8888:name.dnydns-server.com:8888 localhost + +ssh -L 8888:localhost:8888 name.dnydns-server.com + +and both of those with username@name.dnydns-server.com + +``` + +What am I doing wrong? + +**EDIT**: The answers given were factually correct and explained the usage of port forwarding. It turned out that I was using the correct command, rather there was a firewall rule which prevented me from connecting to port 8888 FROM the server itself. I figured this out when I tried to connect to the website while sshed into the remote server.",2013/10/29,"['https://superuser.com/questions/667040', 'https://superuser.com', 'https://superuser.com/users/35728/']","I guess you first need to get clear on some terms I'll use: + +**Client** means the machine where you start ssh. This machine is refered to by ""local"". + +**Server** means the machine you want to connect to with ssh. This machine is refered to by ""remote"". + +**Local port forwarding** with ssh means you connect from your client to your server and thereby open a tunnel so that another program on your client can connect via a local port to a host&port on the server site. The option for this is -L local\_port:remote\_machine:remote\_port. + +**Remote port forwarding** with ssh means you connect from your client to your server and thereby open a tunnel so that a program on your server can connect via a port on the server to a host&port on the client site. The option for this is -R remote\_port:local\_machine:local\_port. + +If I understand you correctly, you want a local forwarding, e.g. create a connection to your server name.dnydns-server.com and then connect with your local browser to port 8888 on name.dnydns-server.com. + +The following command from your list should actually do what you want: + +``` +ssh -L 8888:localhost:8888 name.dnydns-server.com + +``` + +The first 8888 is the port on your client that your additional program (browser) can connet to. + +The ""localhost"" in that line is seen from the end of the tunnel, that is on the server (name.dnydns-server.com). There localhost is the machine itself so it's the one you want. (You could place a different name on the network of your server there to access that) + +The second 8888 is the port you want to connect to on the server site. If you run your webserver on the standard port 80, you'll have to change this to 80. + +name.dnydns-server.com is the name of your ssh server where you connect to, which is then the endpoint of the tunnel. + +I don't know why this line didn't work for you though. Did you quit the ssh? It has to stay connected the whole time for the tunnel to work. Default port on the webserver? Webserver not running? + +**Edit:** I changed the definition of ""client"" and ""server"" to clarify things, so some of the comments don't apply anymore and refer to deleted content.","I am presuming that the server has sshd installed, and listening on the well known default port (22), and that the web server is listening on the well-known default port (80). The assumption is that the server is the server (A) is the 'conduit' through which you want to tunnel to get to the web server. Here's what you need to 'tell' ssh in this case: + +``` +ssh -L :: @ + +``` + +So, here's what I think it should look like based on what I think you're trying to do: + +``` +ssh -L 8888:web.server.dyndns-server.com:80 youruserid@yourserver + +``` + +Do this, then point your browser to localhost:8888." +33134621,"I want to compile this code: + +``` +#include +#include +#include +int main ( int argc , char ** argv ) +{ + printf (""%zu\n"", alignof ( max_align_t )); + return 0; +} + +``` + +But compiler says that: + +``` +error: ‘max_align_t’ undeclared"". + +``` + +`stddef.h` is included and everything must be ok, isn't it? + +P.S. I already tried to compile this code under gcc4.8 and gcc4.9, but I have error as described.",2015/10/14,"['https://Stackoverflow.com/questions/33134621', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5444662/']","To use a C11 feature you need to tell the compiler to run in C11 compliant mode. + +For gcc this can be achieved by specifying the option `-std=c11`.",I use a compiler that is natively based on c99 that has a stddef.h that it uses. On my computer I need to use the -std=c11 option and also a header file that apparently corresponds to c11. +53405895,"I have a table like: + +``` +id fkey srno remark date +1 A001 1 +2 A001 2 +3 A002 1 +4 A003 1 +5 A002 2 + +``` + +I want distinct latest record based on max srno like + +``` +2 A001 2 +4 A003 1 +5 A002 2 + +```",2018/11/21,"['https://Stackoverflow.com/questions/53405895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4337261/']","use window function `row_number()` + +``` +select * from ( +select *,row_number() over(PARTITION by fkey order by srno desc) rn from table1 t1 +) t where rn=1 + +``` + +you can write it by using cte + +``` +with cte as +( + select *,row_number() over(PARTITION by fkey order by srno desc) rn from + table_name t1 +) select * from cte where rn=1 + +```","You can use correlated subquery + +``` +select * from tablename where srno in +(select max(srno) from tablename b where a.fkey=b.fkey) + +```" +53405895,"I have a table like: + +``` +id fkey srno remark date +1 A001 1 +2 A001 2 +3 A002 1 +4 A003 1 +5 A002 2 + +``` + +I want distinct latest record based on max srno like + +``` +2 A001 2 +4 A003 1 +5 A002 2 + +```",2018/11/21,"['https://Stackoverflow.com/questions/53405895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4337261/']","The best way to do this in Postgres is to use `DISTINCT ON`: + +``` +SELECT DISTINCT ON (fkey) id, fkey, srno +FROM yourTable +ORDER BY fkey, srno DESC; + +``` + +[![enter image description here](https://i.stack.imgur.com/LkEyJ.png)](https://i.stack.imgur.com/LkEyJ.png) + +[Demo +----](https://dbfiddle.uk/?rdbms=postgres_11&fiddle=45e6379feee11ead0fbc1bf8e790a144)","You can use correlated subquery + +``` +select * from tablename where srno in +(select max(srno) from tablename b where a.fkey=b.fkey) + +```" +53405895,"I have a table like: + +``` +id fkey srno remark date +1 A001 1 +2 A001 2 +3 A002 1 +4 A003 1 +5 A002 2 + +``` + +I want distinct latest record based on max srno like + +``` +2 A001 2 +4 A003 1 +5 A002 2 + +```",2018/11/21,"['https://Stackoverflow.com/questions/53405895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4337261/']","The best way to do this in Postgres is to use `DISTINCT ON`: + +``` +SELECT DISTINCT ON (fkey) id, fkey, srno +FROM yourTable +ORDER BY fkey, srno DESC; + +``` + +[![enter image description here](https://i.stack.imgur.com/LkEyJ.png)](https://i.stack.imgur.com/LkEyJ.png) + +[Demo +----](https://dbfiddle.uk/?rdbms=postgres_11&fiddle=45e6379feee11ead0fbc1bf8e790a144)","use window function `row_number()` + +``` +select * from ( +select *,row_number() over(PARTITION by fkey order by srno desc) rn from table1 t1 +) t where rn=1 + +``` + +you can write it by using cte + +``` +with cte as +( + select *,row_number() over(PARTITION by fkey order by srno desc) rn from + table_name t1 +) select * from cte where rn=1 + +```" +53405895,"I have a table like: + +``` +id fkey srno remark date +1 A001 1 +2 A001 2 +3 A002 1 +4 A003 1 +5 A002 2 + +``` + +I want distinct latest record based on max srno like + +``` +2 A001 2 +4 A003 1 +5 A002 2 + +```",2018/11/21,"['https://Stackoverflow.com/questions/53405895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4337261/']","use window function `row_number()` + +``` +select * from ( +select *,row_number() over(PARTITION by fkey order by srno desc) rn from table1 t1 +) t where rn=1 + +``` + +you can write it by using cte + +``` +with cte as +( + select *,row_number() over(PARTITION by fkey order by srno desc) rn from + table_name t1 +) select * from cte where rn=1 + +```","You may use a subquery with an `IN` operator + +``` +with tab(id, fkey, srno) as +( + select 1,'A001',1 union all + select 2,'A001',2 union all + select 3,'A002',1 union all + select 4,'A003',1 union all + select 5,'A002',2 +) +select * + from tab + where ( fkey, srno ) in + ( + select fkey, max(srno) + from tab + group by fkey + ); + +id fkey srno +2 A001 2 +4 A003 1 +5 A002 2 + +``` + +[***Rextester Demo***](https://rextester.com/KPF2258)" +53405895,"I have a table like: + +``` +id fkey srno remark date +1 A001 1 +2 A001 2 +3 A002 1 +4 A003 1 +5 A002 2 + +``` + +I want distinct latest record based on max srno like + +``` +2 A001 2 +4 A003 1 +5 A002 2 + +```",2018/11/21,"['https://Stackoverflow.com/questions/53405895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4337261/']","The best way to do this in Postgres is to use `DISTINCT ON`: + +``` +SELECT DISTINCT ON (fkey) id, fkey, srno +FROM yourTable +ORDER BY fkey, srno DESC; + +``` + +[![enter image description here](https://i.stack.imgur.com/LkEyJ.png)](https://i.stack.imgur.com/LkEyJ.png) + +[Demo +----](https://dbfiddle.uk/?rdbms=postgres_11&fiddle=45e6379feee11ead0fbc1bf8e790a144)","You may use a subquery with an `IN` operator + +``` +with tab(id, fkey, srno) as +( + select 1,'A001',1 union all + select 2,'A001',2 union all + select 3,'A002',1 union all + select 4,'A003',1 union all + select 5,'A002',2 +) +select * + from tab + where ( fkey, srno ) in + ( + select fkey, max(srno) + from tab + group by fkey + ); + +id fkey srno +2 A001 2 +4 A003 1 +5 A002 2 + +``` + +[***Rextester Demo***](https://rextester.com/KPF2258)" +681226,"I have PHP application that is completely procedural (No PHP Classes). In my case, is there any formal diagrams I can draw to show how my web application that is equivalent to a UML class diagram for OOP based applications. + +Thanks all",2009/03/25,"['https://Stackoverflow.com/questions/681226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51649/']",[doxygen](http://www.doxygen.org/) can generate call- and caller graphs automatically - if that suits your needs.,"You could make some Hatley-Pirbhai models: + +" +681226,"I have PHP application that is completely procedural (No PHP Classes). In my case, is there any formal diagrams I can draw to show how my web application that is equivalent to a UML class diagram for OOP based applications. + +Thanks all",2009/03/25,"['https://Stackoverflow.com/questions/681226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51649/']","You could make some Hatley-Pirbhai models: + +","It's not because the implementation (or even the design) is procedural, that the business model is. + +Though you may not find explicit reference to classes in your code, they may still be there, hidden, scattered through global variables etc, functions manipulating some globals, ... + +So in order to describe your app, you *may* still be able to use a (conceptual) class diagram." +681226,"I have PHP application that is completely procedural (No PHP Classes). In my case, is there any formal diagrams I can draw to show how my web application that is equivalent to a UML class diagram for OOP based applications. + +Thanks all",2009/03/25,"['https://Stackoverflow.com/questions/681226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51649/']",[doxygen](http://www.doxygen.org/) can generate call- and caller graphs automatically - if that suits your needs.,"It's not because the implementation (or even the design) is procedural, that the business model is. + +Though you may not find explicit reference to classes in your code, they may still be there, hidden, scattered through global variables etc, functions manipulating some globals, ... + +So in order to describe your app, you *may* still be able to use a (conceptual) class diagram." +58267243,"I have problems when sending email, I make registration and verification by email, when on localhost everything runs smoothly, there are no problems, but when I am hosting, the email function cannot, please help + +``` + $config = array( + 'protocol' => 'smtp', + 'smtp_host' => 'ssl://smtp.gmail.com', + 'smtp_port' => 465, + 'smtp_user' => 'email@gmail.com', // change it to yours + 'smtp_pass' => 'mypassword', // change it to yours + 'mailtype' => 'html', + 'charset' => 'iso-8859-1', + 'wordwrap' => TRUE + ); + $message = "" + + + Verifikasi Kode + + +

Terima kasih telah berpartisipasi.

+

Akun anda:

+

Email: "".$email.""

+

Untuk melanjutkan pendaftaran, mohon klik link yang kami berikan

+

Activate My Account

+ + + ""; + $this->email->initialize($config); + $this->load->library('email', $config); + $this->email->set_newline(""\r\n""); + $this->email->from($config['smtp_user']); + $this->email->to($email); + $this->email->subject('Signup Verification Email, abcd.com | No reply'); + $this->email->message($message); + if($this->email->send()){ + $this->session->set_flashdata('msg','Kode Aktivasi telah dikirim ke email, mohon di cek'); + } + else{ + $this->session->set_flashdata('msg', $this->email->print_debugger()); + } + + redirect('register',$data); +} + +``` + +> +> Error : Failed to authenticate password. Error: 534-5.7.14 Please 534-5.7.14 log in via your web browser and then try again. 534-5.7.14 Learn more at 534 5.7.14 18sm13749594pfp.100 - gsmtp +> +> +> Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method. +> +> +>",2019/10/07,"['https://Stackoverflow.com/questions/58267243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11944485/']","**Tl;dr:** + +> +> You'll see this occur in most templates in the Template Gallery. The +> official [Google Documentation](https://developers.google.com/tag-platform/tag-manager/templates/api#createqueue) has nothing to say about it. +> However, in my tests, this small change in structure (nesting your +> pushes in randomly-named sub-objects) does not affect GTM's ability to +> pick up on the event names. So you should be able to use them as they +> are. +> +> +> + +**Detailed response** + +Even though you see nesting within the dataLayer object, this doesn't translate to nesting within GTM's data model. + +To test this, consider the following setup: + +1. A custom HTML tag that pushes a nested object to the dataLayer + +```html + +``` + +2. A Tag Template that pushes a simple event to the dataLayer + +```js +const dataLayerPush = require('createQueue')('dataLayer'); +dataLayerPush({event:'test'}); +data.gtmOnSuccess(); +``` + +These 2, when fired, will produce seemingly identical results. Check the linked image for details. +[Test Events pushed by the Tag Template (1) and Custom HTML Tag (2)](https://i.stack.imgur.com/QP3Np.png) + +However, if you set up a Custom Event Trigger that listens for `'test'` event names, only the one created by the Tag Template will fire. You can also see that the one created by the Tag Template also has a `gtm.uniqueEventId` key-value pair. The objects are not the same, and they are not treated the same way. + +You can try to debug further by using the [dataLayer helper](https://github.com/google/data-layer-helper), if that's doable for you. + +Hope this helps the next person to stumble upon this. I know I needed it.","For a dataLayer push you can use a custom +HTML template and trigger it via page view then add the below code + +``` + + +```" +1179,"The design of SO/SU/SF is very clean and easy to use, I want to have a similar one to host the Q/A service in my local company, is it open source? or does stack overflow service inc. have the Q/A hosting service?",2010/07/24,"['https://meta.superuser.com/questions/1179', 'https://meta.superuser.com', 'https://meta.superuser.com/users/19926/']","I'm sorry to say that no, you can't self host. And it is not open source. + +But there are open source clones exist. One of the example is [cnprog](http://cnprog.com/). You can access the source [here](http://code.google.com/p/cnprog/) and [here](http://github.com/cnprog/CNPROG). + +After you have the source, you can do anything you want.",Check out [Area 51](http://area51.stackexchange.com/). +4641495,"I want to make a simple script to post a tweet from a Textbox when the user click on the Submit button, but all using Javascript, without any server-side language. How may I do this?",2011/01/09,"['https://Stackoverflow.com/questions/4641495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/126353/']","What you want to use is Twitter Anywhere, develop by twitter + + + +This handles all OAuth, create the box and post the tweet."," +But just change the document.title to the location of your textbox" +3686778,"I'm trying to store an hexadecimal value (\xC1) in MySql Database. When I print that with PHP, i get: xC1lcool instead of the right word. + +> +> INSERT INTO veiculos VALUES (1, 'Ford', 'Ka RoCam Flex', 25850.00, 1998, 1999, 'Vermelho', 15000, '\xC1lcool;Gasolina;GNV', 'Ar-Condicionado;4 portas;Câmbio automático', 'imagem1.jpg;imagem2.jpg;imagem3.jpg;imagem4.jpg;imagem5.jpg;'), (2, 'Ford', 'Ka RoCam Flex', 223850.00, 1999, 2001, 'Prata', 10000, '\xC1lcool;GNV', 'Ar-Condicionado;4 portas;Câmbio automático;', 'imagem1.jpg;imagem2.jpg;imagem3.jpg;imagem4.jpg;imagem5.jpg;'), (3, 'Ford', 'Fiesta', 21380.00, 1998, 2002, 'Preto', 23043, 'Gasolina', '', 'imagem1.jpg;imagem2.jpg;imagem3.jpg;imagem4.jpg;imagem5.jpg;'); +> +> +> + +How could i do that?",2010/09/10,"['https://Stackoverflow.com/questions/3686778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/444582/']","`\x` is not a valid escape sequence. Valid sequences are detailed at + +Quoting the manual: + +> +> For all other escape sequences, +> backslash is ignored. That is, the +> escaped character is interpreted as if +> it was not escaped. For example, “\x” +> is just “x”. +> +> +> + +You can specify a full string in hexadecimal: + +``` +SELECT 0x61626364 -- Prints abcd + +``` + +If you want to mix both styles, you have to concatenate: + +``` +SELECT CONCAT('a', 0x6263, 'd') -- Prints abcd + +```","Use MySQL [`UNHEX()`](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_unhex) function with [`CONCAT()`](http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat). Like this + +``` +insert into tablename values (CONCAT(UNHEX('C1'), 'other-part-of-string')) + +```" +3686778,"I'm trying to store an hexadecimal value (\xC1) in MySql Database. When I print that with PHP, i get: xC1lcool instead of the right word. + +> +> INSERT INTO veiculos VALUES (1, 'Ford', 'Ka RoCam Flex', 25850.00, 1998, 1999, 'Vermelho', 15000, '\xC1lcool;Gasolina;GNV', 'Ar-Condicionado;4 portas;Câmbio automático', 'imagem1.jpg;imagem2.jpg;imagem3.jpg;imagem4.jpg;imagem5.jpg;'), (2, 'Ford', 'Ka RoCam Flex', 223850.00, 1999, 2001, 'Prata', 10000, '\xC1lcool;GNV', 'Ar-Condicionado;4 portas;Câmbio automático;', 'imagem1.jpg;imagem2.jpg;imagem3.jpg;imagem4.jpg;imagem5.jpg;'), (3, 'Ford', 'Fiesta', 21380.00, 1998, 2002, 'Preto', 23043, 'Gasolina', '', 'imagem1.jpg;imagem2.jpg;imagem3.jpg;imagem4.jpg;imagem5.jpg;'); +> +> +> + +How could i do that?",2010/09/10,"['https://Stackoverflow.com/questions/3686778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/444582/']","`\x` is not a valid escape sequence. Valid sequences are detailed at + +Quoting the manual: + +> +> For all other escape sequences, +> backslash is ignored. That is, the +> escaped character is interpreted as if +> it was not escaped. For example, “\x” +> is just “x”. +> +> +> + +You can specify a full string in hexadecimal: + +``` +SELECT 0x61626364 -- Prints abcd + +``` + +If you want to mix both styles, you have to concatenate: + +``` +SELECT CONCAT('a', 0x6263, 'd') -- Prints abcd + +```","You can store full binary data, such as an image or pdf in a MySQL database. When you insert the value make sure you do a `""insert ... values("".mysql_real_escape_string($value)."")"";`. It is recommended that you use the blob datatype for that column, but you can use a varchar if you really want to. After that when you select the data out it will be normal, you don't have to do anything else. In the case of an image, just use a `header(content-type: ...)` and print out the variable normally and the image will be displayed to the end user." +59303,"In the approach phase, engine 1 of [Cathay Pacific flight 780](https://en.wikipedia.org/wiki/Cathay_Pacific_Flight_780) got stuck at about 70% N1 and it forced the crew to do an overspeed landing (230knots). + +Why didn't they shut it off by turning the fuel pumps off? Is there a backup mechanism if the fuel valve fails like in this scenario?",2019/01/22,"['https://aviation.stackexchange.com/questions/59303', 'https://aviation.stackexchange.com', 'https://aviation.stackexchange.com/users/36788/']","You can find the [full incident report here](https://www.webcitation.org/6Rk7TGDPW?url=http://www.cad.gov.hk/reports/2%20Final%20Report%20-%20CX%20780%202013%2007%20web%20access%20compliant.pdf) and this topic is touched upon briefly, but in short they had little to no time to entertain any other options but a full speed landing. + +> +> It was not until the aircraft [was] on the final descent for landing that +> the Commander realised they could not reduce the thrust on the number +> 1 engine. The speed was not controllable and from that point, there +> was no time for the crew to consider other strategy nor procedure to +> cope with such emergency situation. +> +> +> + +and more in the conclusion section... + +> +> **t.** At that stage, there was no time for the flight crew to consider other +> strategy nor procedure to cope with such emergency situation. The +> flight crew concentrated on flying the aircraft for a safe landing. +> +> +> + +First off, the engine was throwing errors throughout the flight and they were talking to the maintenance team at other points. Ultimately, the proper steps were taken and everything was done by the book. They were prepared for an engine-out landing. When you have a runaway engine malfunction (or throttle stuck at full) shutting down prior to landing *may* not be the right decision if the running engine provides no immediate safety risk. If you shut down a problematic engine in flight you run the serious risk of not being able to get it started again. + +Considering that most airports have a bit (or a lot) of extra runway, [EMAS systems](https://en.wikipedia.org/wiki/Engineered_materials_arrestor_system) and often land at the end of the runway, coming in overspeed and burning through your tires and brakes may be safer than cutting the engine and potentially falling short of the runway.","Engine #2 wasn't doing its job either +------------------------------------- + +Had the situation just been engine #1 stuck at high thrust, with engine 2 normally controllable, than what you describe would be a reasonable response to the situation. However, that was *not* the case with CX780 -- during approach, Engine #2 was stuck at 17% N1 (or rather below idle) and thus delivering effectively nil thrust. + +As a result, the pilots dared not shut down engine #1 until they were safely stopped on the ground." +59303,"In the approach phase, engine 1 of [Cathay Pacific flight 780](https://en.wikipedia.org/wiki/Cathay_Pacific_Flight_780) got stuck at about 70% N1 and it forced the crew to do an overspeed landing (230knots). + +Why didn't they shut it off by turning the fuel pumps off? Is there a backup mechanism if the fuel valve fails like in this scenario?",2019/01/22,"['https://aviation.stackexchange.com/questions/59303', 'https://aviation.stackexchange.com', 'https://aviation.stackexchange.com/users/36788/']","You can find the [full incident report here](https://www.webcitation.org/6Rk7TGDPW?url=http://www.cad.gov.hk/reports/2%20Final%20Report%20-%20CX%20780%202013%2007%20web%20access%20compliant.pdf) and this topic is touched upon briefly, but in short they had little to no time to entertain any other options but a full speed landing. + +> +> It was not until the aircraft [was] on the final descent for landing that +> the Commander realised they could not reduce the thrust on the number +> 1 engine. The speed was not controllable and from that point, there +> was no time for the crew to consider other strategy nor procedure to +> cope with such emergency situation. +> +> +> + +and more in the conclusion section... + +> +> **t.** At that stage, there was no time for the flight crew to consider other +> strategy nor procedure to cope with such emergency situation. The +> flight crew concentrated on flying the aircraft for a safe landing. +> +> +> + +First off, the engine was throwing errors throughout the flight and they were talking to the maintenance team at other points. Ultimately, the proper steps were taken and everything was done by the book. They were prepared for an engine-out landing. When you have a runaway engine malfunction (or throttle stuck at full) shutting down prior to landing *may* not be the right decision if the running engine provides no immediate safety risk. If you shut down a problematic engine in flight you run the serious risk of not being able to get it started again. + +Considering that most airports have a bit (or a lot) of extra runway, [EMAS systems](https://en.wikipedia.org/wiki/Engineered_materials_arrestor_system) and often land at the end of the runway, coming in overspeed and burning through your tires and brakes may be safer than cutting the engine and potentially falling short of the runway.","From the incident report section 1.1.4: + +> +> a. At 0519 hrs during the descent to a cleared level of FL230, ECAM +> messages “ENG 1 CTL SYS FAULT” and “ENG 2 STALL” were annunciated +> within a short period of time. According to the Commander, a light +> “pop” sound was heard and some “ozone” and “burning” smell was +> detected shortly before the ECAM message “ENG 2 STALL” +> +> +> + +Then later: + +> +> e. At 0530 hrs, when the aircraft was approximately 45 nm southeast +> from VHHH and was about to level off at 8,000 ft AMSL, ECAM message +> “ENG 1 STALL” was annunciated. +> +> +> + +So now both engines are out, they started the APU and successfully managed to restart #1: + +> +> h. The crew moved the thrust levers to check the engine control but +> there was no direct response from the engines. The No. 1 engine speed +> eventually increased to about 74% N1 with the No. 1 thrust lever in +> the CLB (climb) detent position. The No. 2 engine speed remained at +> sub-idle about 17% N1, with the No. 2 t hrust lever at the IDLE +> position. +> +> +> + +Engine 2 was out of action, producing no power, engine 1 had failed, but was temporarily working although they couldn't adjust power, if they'd shut that down too they'd have been gliding and probably would have crashed with total loss of life. They didn't have the power to climb and had one shot at landing, so they made damn sure they got it on the runway, not a bad landing considering the circumstances. + +On a humorous note, another example of pilot understatement: + +> +> l. At 0539 hrs, the Commander made another PA advising the passengers +> of having “small problem with the engines” with small vibrations and +> requesting them to remain seated and follow the directions from the +> cabin crew. +> +> +>" +59303,"In the approach phase, engine 1 of [Cathay Pacific flight 780](https://en.wikipedia.org/wiki/Cathay_Pacific_Flight_780) got stuck at about 70% N1 and it forced the crew to do an overspeed landing (230knots). + +Why didn't they shut it off by turning the fuel pumps off? Is there a backup mechanism if the fuel valve fails like in this scenario?",2019/01/22,"['https://aviation.stackexchange.com/questions/59303', 'https://aviation.stackexchange.com', 'https://aviation.stackexchange.com/users/36788/']","You can find the [full incident report here](https://www.webcitation.org/6Rk7TGDPW?url=http://www.cad.gov.hk/reports/2%20Final%20Report%20-%20CX%20780%202013%2007%20web%20access%20compliant.pdf) and this topic is touched upon briefly, but in short they had little to no time to entertain any other options but a full speed landing. + +> +> It was not until the aircraft [was] on the final descent for landing that +> the Commander realised they could not reduce the thrust on the number +> 1 engine. The speed was not controllable and from that point, there +> was no time for the crew to consider other strategy nor procedure to +> cope with such emergency situation. +> +> +> + +and more in the conclusion section... + +> +> **t.** At that stage, there was no time for the flight crew to consider other +> strategy nor procedure to cope with such emergency situation. The +> flight crew concentrated on flying the aircraft for a safe landing. +> +> +> + +First off, the engine was throwing errors throughout the flight and they were talking to the maintenance team at other points. Ultimately, the proper steps were taken and everything was done by the book. They were prepared for an engine-out landing. When you have a runaway engine malfunction (or throttle stuck at full) shutting down prior to landing *may* not be the right decision if the running engine provides no immediate safety risk. If you shut down a problematic engine in flight you run the serious risk of not being able to get it started again. + +Considering that most airports have a bit (or a lot) of extra runway, [EMAS systems](https://en.wikipedia.org/wiki/Engineered_materials_arrestor_system) and often land at the end of the runway, coming in overspeed and burning through your tires and brakes may be safer than cutting the engine and potentially falling short of the runway.","Aside from what Unrec. and GdD point out, even if the other engine had been running perfectly... + +A frequent problem with twin engine airplanes is **[shutting down](https://en.wikipedia.org/wiki/Kegworth_air_disaster) the [wrong](https://en.wikipedia.org/wiki/TransAsia_Airways_Flight_235) engine**. Nobody ever expects or plans to shut down the wrong engine, but it happens anyway. + +So a crew is very cautious to shutdown an engine that is working." +59303,"In the approach phase, engine 1 of [Cathay Pacific flight 780](https://en.wikipedia.org/wiki/Cathay_Pacific_Flight_780) got stuck at about 70% N1 and it forced the crew to do an overspeed landing (230knots). + +Why didn't they shut it off by turning the fuel pumps off? Is there a backup mechanism if the fuel valve fails like in this scenario?",2019/01/22,"['https://aviation.stackexchange.com/questions/59303', 'https://aviation.stackexchange.com', 'https://aviation.stackexchange.com/users/36788/']","You can find the [full incident report here](https://www.webcitation.org/6Rk7TGDPW?url=http://www.cad.gov.hk/reports/2%20Final%20Report%20-%20CX%20780%202013%2007%20web%20access%20compliant.pdf) and this topic is touched upon briefly, but in short they had little to no time to entertain any other options but a full speed landing. + +> +> It was not until the aircraft [was] on the final descent for landing that +> the Commander realised they could not reduce the thrust on the number +> 1 engine. The speed was not controllable and from that point, there +> was no time for the crew to consider other strategy nor procedure to +> cope with such emergency situation. +> +> +> + +and more in the conclusion section... + +> +> **t.** At that stage, there was no time for the flight crew to consider other +> strategy nor procedure to cope with such emergency situation. The +> flight crew concentrated on flying the aircraft for a safe landing. +> +> +> + +First off, the engine was throwing errors throughout the flight and they were talking to the maintenance team at other points. Ultimately, the proper steps were taken and everything was done by the book. They were prepared for an engine-out landing. When you have a runaway engine malfunction (or throttle stuck at full) shutting down prior to landing *may* not be the right decision if the running engine provides no immediate safety risk. If you shut down a problematic engine in flight you run the serious risk of not being able to get it started again. + +Considering that most airports have a bit (or a lot) of extra runway, [EMAS systems](https://en.wikipedia.org/wiki/Engineered_materials_arrestor_system) and often land at the end of the runway, coming in overspeed and burning through your tires and brakes may be safer than cutting the engine and potentially falling short of the runway.","I could be wrong but reverse thrust from the running engine helped to stop the plane1 as it was approaching at a great speed way over the recommended landing speed, so shutting the running engine off right at approach would have made the plane to overshoot the runway, making the situation worse. + +--- + +1: Source: + +> +> [...] The aircraft then rolled left seven degrees and +> pitched down to -2.5 degrees at the second touchdown during which, the lower +> cowling of No. 1 engine contacted the runway surface. Spoilers deployed +> automatically. **Both engine thrust reversers were selected by the Commander. +> Only No. 1 engine thrust reverser was deployed successfully and ECAM message +> “ENG 2 REV FAULT” was annunciated.** Maximum manual braking was +> applied. ... *[[Accident report](https://www.webcitation.org/6Rk7TGDPW?url=http://www.cad.gov.hk/reports/2%20Final%20Report%20-%20CX%20780%202013%2007%20web%20access%20compliant.pdf), page 26. Engine #1 was the one that was stuck at 74% N1.]* +> +> +>" +59303,"In the approach phase, engine 1 of [Cathay Pacific flight 780](https://en.wikipedia.org/wiki/Cathay_Pacific_Flight_780) got stuck at about 70% N1 and it forced the crew to do an overspeed landing (230knots). + +Why didn't they shut it off by turning the fuel pumps off? Is there a backup mechanism if the fuel valve fails like in this scenario?",2019/01/22,"['https://aviation.stackexchange.com/questions/59303', 'https://aviation.stackexchange.com', 'https://aviation.stackexchange.com/users/36788/']","Engine #2 wasn't doing its job either +------------------------------------- + +Had the situation just been engine #1 stuck at high thrust, with engine 2 normally controllable, than what you describe would be a reasonable response to the situation. However, that was *not* the case with CX780 -- during approach, Engine #2 was stuck at 17% N1 (or rather below idle) and thus delivering effectively nil thrust. + +As a result, the pilots dared not shut down engine #1 until they were safely stopped on the ground.","From the incident report section 1.1.4: + +> +> a. At 0519 hrs during the descent to a cleared level of FL230, ECAM +> messages “ENG 1 CTL SYS FAULT” and “ENG 2 STALL” were annunciated +> within a short period of time. According to the Commander, a light +> “pop” sound was heard and some “ozone” and “burning” smell was +> detected shortly before the ECAM message “ENG 2 STALL” +> +> +> + +Then later: + +> +> e. At 0530 hrs, when the aircraft was approximately 45 nm southeast +> from VHHH and was about to level off at 8,000 ft AMSL, ECAM message +> “ENG 1 STALL” was annunciated. +> +> +> + +So now both engines are out, they started the APU and successfully managed to restart #1: + +> +> h. The crew moved the thrust levers to check the engine control but +> there was no direct response from the engines. The No. 1 engine speed +> eventually increased to about 74% N1 with the No. 1 thrust lever in +> the CLB (climb) detent position. The No. 2 engine speed remained at +> sub-idle about 17% N1, with the No. 2 t hrust lever at the IDLE +> position. +> +> +> + +Engine 2 was out of action, producing no power, engine 1 had failed, but was temporarily working although they couldn't adjust power, if they'd shut that down too they'd have been gliding and probably would have crashed with total loss of life. They didn't have the power to climb and had one shot at landing, so they made damn sure they got it on the runway, not a bad landing considering the circumstances. + +On a humorous note, another example of pilot understatement: + +> +> l. At 0539 hrs, the Commander made another PA advising the passengers +> of having “small problem with the engines” with small vibrations and +> requesting them to remain seated and follow the directions from the +> cabin crew. +> +> +>" +59303,"In the approach phase, engine 1 of [Cathay Pacific flight 780](https://en.wikipedia.org/wiki/Cathay_Pacific_Flight_780) got stuck at about 70% N1 and it forced the crew to do an overspeed landing (230knots). + +Why didn't they shut it off by turning the fuel pumps off? Is there a backup mechanism if the fuel valve fails like in this scenario?",2019/01/22,"['https://aviation.stackexchange.com/questions/59303', 'https://aviation.stackexchange.com', 'https://aviation.stackexchange.com/users/36788/']","Engine #2 wasn't doing its job either +------------------------------------- + +Had the situation just been engine #1 stuck at high thrust, with engine 2 normally controllable, than what you describe would be a reasonable response to the situation. However, that was *not* the case with CX780 -- during approach, Engine #2 was stuck at 17% N1 (or rather below idle) and thus delivering effectively nil thrust. + +As a result, the pilots dared not shut down engine #1 until they were safely stopped on the ground.","Aside from what Unrec. and GdD point out, even if the other engine had been running perfectly... + +A frequent problem with twin engine airplanes is **[shutting down](https://en.wikipedia.org/wiki/Kegworth_air_disaster) the [wrong](https://en.wikipedia.org/wiki/TransAsia_Airways_Flight_235) engine**. Nobody ever expects or plans to shut down the wrong engine, but it happens anyway. + +So a crew is very cautious to shutdown an engine that is working." +59303,"In the approach phase, engine 1 of [Cathay Pacific flight 780](https://en.wikipedia.org/wiki/Cathay_Pacific_Flight_780) got stuck at about 70% N1 and it forced the crew to do an overspeed landing (230knots). + +Why didn't they shut it off by turning the fuel pumps off? Is there a backup mechanism if the fuel valve fails like in this scenario?",2019/01/22,"['https://aviation.stackexchange.com/questions/59303', 'https://aviation.stackexchange.com', 'https://aviation.stackexchange.com/users/36788/']","Engine #2 wasn't doing its job either +------------------------------------- + +Had the situation just been engine #1 stuck at high thrust, with engine 2 normally controllable, than what you describe would be a reasonable response to the situation. However, that was *not* the case with CX780 -- during approach, Engine #2 was stuck at 17% N1 (or rather below idle) and thus delivering effectively nil thrust. + +As a result, the pilots dared not shut down engine #1 until they were safely stopped on the ground.","I could be wrong but reverse thrust from the running engine helped to stop the plane1 as it was approaching at a great speed way over the recommended landing speed, so shutting the running engine off right at approach would have made the plane to overshoot the runway, making the situation worse. + +--- + +1: Source: + +> +> [...] The aircraft then rolled left seven degrees and +> pitched down to -2.5 degrees at the second touchdown during which, the lower +> cowling of No. 1 engine contacted the runway surface. Spoilers deployed +> automatically. **Both engine thrust reversers were selected by the Commander. +> Only No. 1 engine thrust reverser was deployed successfully and ECAM message +> “ENG 2 REV FAULT” was annunciated.** Maximum manual braking was +> applied. ... *[[Accident report](https://www.webcitation.org/6Rk7TGDPW?url=http://www.cad.gov.hk/reports/2%20Final%20Report%20-%20CX%20780%202013%2007%20web%20access%20compliant.pdf), page 26. Engine #1 was the one that was stuck at 74% N1.]* +> +> +>" +59303,"In the approach phase, engine 1 of [Cathay Pacific flight 780](https://en.wikipedia.org/wiki/Cathay_Pacific_Flight_780) got stuck at about 70% N1 and it forced the crew to do an overspeed landing (230knots). + +Why didn't they shut it off by turning the fuel pumps off? Is there a backup mechanism if the fuel valve fails like in this scenario?",2019/01/22,"['https://aviation.stackexchange.com/questions/59303', 'https://aviation.stackexchange.com', 'https://aviation.stackexchange.com/users/36788/']","From the incident report section 1.1.4: + +> +> a. At 0519 hrs during the descent to a cleared level of FL230, ECAM +> messages “ENG 1 CTL SYS FAULT” and “ENG 2 STALL” were annunciated +> within a short period of time. According to the Commander, a light +> “pop” sound was heard and some “ozone” and “burning” smell was +> detected shortly before the ECAM message “ENG 2 STALL” +> +> +> + +Then later: + +> +> e. At 0530 hrs, when the aircraft was approximately 45 nm southeast +> from VHHH and was about to level off at 8,000 ft AMSL, ECAM message +> “ENG 1 STALL” was annunciated. +> +> +> + +So now both engines are out, they started the APU and successfully managed to restart #1: + +> +> h. The crew moved the thrust levers to check the engine control but +> there was no direct response from the engines. The No. 1 engine speed +> eventually increased to about 74% N1 with the No. 1 thrust lever in +> the CLB (climb) detent position. The No. 2 engine speed remained at +> sub-idle about 17% N1, with the No. 2 t hrust lever at the IDLE +> position. +> +> +> + +Engine 2 was out of action, producing no power, engine 1 had failed, but was temporarily working although they couldn't adjust power, if they'd shut that down too they'd have been gliding and probably would have crashed with total loss of life. They didn't have the power to climb and had one shot at landing, so they made damn sure they got it on the runway, not a bad landing considering the circumstances. + +On a humorous note, another example of pilot understatement: + +> +> l. At 0539 hrs, the Commander made another PA advising the passengers +> of having “small problem with the engines” with small vibrations and +> requesting them to remain seated and follow the directions from the +> cabin crew. +> +> +>","Aside from what Unrec. and GdD point out, even if the other engine had been running perfectly... + +A frequent problem with twin engine airplanes is **[shutting down](https://en.wikipedia.org/wiki/Kegworth_air_disaster) the [wrong](https://en.wikipedia.org/wiki/TransAsia_Airways_Flight_235) engine**. Nobody ever expects or plans to shut down the wrong engine, but it happens anyway. + +So a crew is very cautious to shutdown an engine that is working." +59303,"In the approach phase, engine 1 of [Cathay Pacific flight 780](https://en.wikipedia.org/wiki/Cathay_Pacific_Flight_780) got stuck at about 70% N1 and it forced the crew to do an overspeed landing (230knots). + +Why didn't they shut it off by turning the fuel pumps off? Is there a backup mechanism if the fuel valve fails like in this scenario?",2019/01/22,"['https://aviation.stackexchange.com/questions/59303', 'https://aviation.stackexchange.com', 'https://aviation.stackexchange.com/users/36788/']","From the incident report section 1.1.4: + +> +> a. At 0519 hrs during the descent to a cleared level of FL230, ECAM +> messages “ENG 1 CTL SYS FAULT” and “ENG 2 STALL” were annunciated +> within a short period of time. According to the Commander, a light +> “pop” sound was heard and some “ozone” and “burning” smell was +> detected shortly before the ECAM message “ENG 2 STALL” +> +> +> + +Then later: + +> +> e. At 0530 hrs, when the aircraft was approximately 45 nm southeast +> from VHHH and was about to level off at 8,000 ft AMSL, ECAM message +> “ENG 1 STALL” was annunciated. +> +> +> + +So now both engines are out, they started the APU and successfully managed to restart #1: + +> +> h. The crew moved the thrust levers to check the engine control but +> there was no direct response from the engines. The No. 1 engine speed +> eventually increased to about 74% N1 with the No. 1 thrust lever in +> the CLB (climb) detent position. The No. 2 engine speed remained at +> sub-idle about 17% N1, with the No. 2 t hrust lever at the IDLE +> position. +> +> +> + +Engine 2 was out of action, producing no power, engine 1 had failed, but was temporarily working although they couldn't adjust power, if they'd shut that down too they'd have been gliding and probably would have crashed with total loss of life. They didn't have the power to climb and had one shot at landing, so they made damn sure they got it on the runway, not a bad landing considering the circumstances. + +On a humorous note, another example of pilot understatement: + +> +> l. At 0539 hrs, the Commander made another PA advising the passengers +> of having “small problem with the engines” with small vibrations and +> requesting them to remain seated and follow the directions from the +> cabin crew. +> +> +>","I could be wrong but reverse thrust from the running engine helped to stop the plane1 as it was approaching at a great speed way over the recommended landing speed, so shutting the running engine off right at approach would have made the plane to overshoot the runway, making the situation worse. + +--- + +1: Source: + +> +> [...] The aircraft then rolled left seven degrees and +> pitched down to -2.5 degrees at the second touchdown during which, the lower +> cowling of No. 1 engine contacted the runway surface. Spoilers deployed +> automatically. **Both engine thrust reversers were selected by the Commander. +> Only No. 1 engine thrust reverser was deployed successfully and ECAM message +> “ENG 2 REV FAULT” was annunciated.** Maximum manual braking was +> applied. ... *[[Accident report](https://www.webcitation.org/6Rk7TGDPW?url=http://www.cad.gov.hk/reports/2%20Final%20Report%20-%20CX%20780%202013%2007%20web%20access%20compliant.pdf), page 26. Engine #1 was the one that was stuck at 74% N1.]* +> +> +>" +59303,"In the approach phase, engine 1 of [Cathay Pacific flight 780](https://en.wikipedia.org/wiki/Cathay_Pacific_Flight_780) got stuck at about 70% N1 and it forced the crew to do an overspeed landing (230knots). + +Why didn't they shut it off by turning the fuel pumps off? Is there a backup mechanism if the fuel valve fails like in this scenario?",2019/01/22,"['https://aviation.stackexchange.com/questions/59303', 'https://aviation.stackexchange.com', 'https://aviation.stackexchange.com/users/36788/']","Aside from what Unrec. and GdD point out, even if the other engine had been running perfectly... + +A frequent problem with twin engine airplanes is **[shutting down](https://en.wikipedia.org/wiki/Kegworth_air_disaster) the [wrong](https://en.wikipedia.org/wiki/TransAsia_Airways_Flight_235) engine**. Nobody ever expects or plans to shut down the wrong engine, but it happens anyway. + +So a crew is very cautious to shutdown an engine that is working.","I could be wrong but reverse thrust from the running engine helped to stop the plane1 as it was approaching at a great speed way over the recommended landing speed, so shutting the running engine off right at approach would have made the plane to overshoot the runway, making the situation worse. + +--- + +1: Source: + +> +> [...] The aircraft then rolled left seven degrees and +> pitched down to -2.5 degrees at the second touchdown during which, the lower +> cowling of No. 1 engine contacted the runway surface. Spoilers deployed +> automatically. **Both engine thrust reversers were selected by the Commander. +> Only No. 1 engine thrust reverser was deployed successfully and ECAM message +> “ENG 2 REV FAULT” was annunciated.** Maximum manual braking was +> applied. ... *[[Accident report](https://www.webcitation.org/6Rk7TGDPW?url=http://www.cad.gov.hk/reports/2%20Final%20Report%20-%20CX%20780%202013%2007%20web%20access%20compliant.pdf), page 26. Engine #1 was the one that was stuck at 74% N1.]* +> +> +>" +969292,"I develop some program and I encountered to this problem: + +![enter image description here](https://i.stack.imgur.com/5reAv.png) + +We know point **P**, **X**, and angle **a**. Range of angle is <0°,360°> between lines **p** and **o**. How I can determine in which side of line **o** is point **X**? Line **p** is always perpendicular to x axe. I thought that I would use this equation: (**Bx - Ax) \* (Cy - Ay) - (By - Ay) \* (Cx - Ax)** (slope) but second point of line **o** is missing and I have no idea how do this with given angle.",2014/10/11,"['https://math.stackexchange.com/questions/969292', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/183624/']","You have two vectors: $X-P$ and $\langle \cos\left(\frac{\pi}{2}-\alpha\right), \sin\left(\frac{\pi}{2}-\alpha\right)\rangle$. $X$ lies below the line if and only if $(X-P) \times \langle \cos\left(\frac{\pi}{2}-\alpha\right), \sin\left(\frac{\pi}{2}-\alpha\right)\rangle$ (when both are regarded as vectors in $\mathbb{R}^3$ with zero third coordinate) points upwards (so that the three form a right-handed system).","Equation for line $o$: +$$ +u(t) = p + t q +$$ +for $t \in \mathbb{R}$ with normed direction vector $q = (\sin a, \cos a)^T$ and vector $p = (x, y)^T$. Then +$$ +v = x-p +$$ +where $x = (a, b)^T$ (vector $x$, not coordinate $x$; coordinate $a$, not angle $a$) and $v$ is the vector from line $o$, at the end point of $p$, to the end point of $x$. + +And now we decompose $v$ into two parts: +$$ +v\_q = (v \cdot q) \, q +$$ +is the part of $v$ in direction of $q$. Then +$$ +v\_\perp = v - v\_q +$$ +is the part of $v$ orthogonal to $o$'s direction vector $q$. +It should have a negative $y$ coordinate if $x$'s end point is below the line $o$, if the angle $a$ is non-zero, $a \in (0, 2\pi)$. + +Otherwise ($a = 0$) check if it's $x$ coordinate is positive. + +### Example + +This is a vector on the line $o$: + +``` +octave> p = [2, 5]' +p = + 2 + 5 + +``` + +Line $o$ has an $60^\circ$ angle $a$ regarding to the $y$-axis: + +``` +octave> a = 60 * 2 * pi / 360 + a = 1.0472 + +``` + +Vector $q$ is a normed direction vector of line $o$: + +``` +octave> q = [sin(a), cos(a)]' + q = + 0.86603 + 0.50000 + +``` + +This is an example vector below the line $o$: + +``` +octave> x = [4,3]' + x = + 4 + 3 + +``` + +Here we have the difference vector $v$ that would lead from $p$ to $x$: + +``` +octave> v = x - p + v = + 2 + -2 + +``` + +This is $v\_q$, the part of $v$ in direction of $q$: + +``` +octave> vq = (v' * q) * q + vq = + 0.63397 + 0.36603 + +``` + +And this is $v\_\perp$, the part of $v$ orthogonal to $q$: + +``` +octave> vo = v - vq + vo = + 1.3660 + -2.3660 + +``` + +A test: + +``` +octave> vo + vq + ans = + 2.0000 + -2.0000 + +``` + +The $y$-coordinate is negative (and $a$ is non-zero): + +``` +octave> vo(2) + ans = -2.3660 + +``` + +We can put the test into an octave function: + +``` +octave> function res = test(x) +> p=[2,5]' +> a = 60*2*pi/360 +> q = [sin(a), cos(a)]' +> v = x - p +> vq = (v'*q)*q +> vo = v - vq +> if (vo(2) == 0) +> res = 0 +> else +> res = vo(2)/abs(vo(2)) +> endif +> endfunction + +``` + +Some applications: + +``` +octave> x2 = [ -2, 7]' +octave> test(x2) +.. +ans = 1 + +``` + +which means $x\_2$ is above line $o$. And then + +``` +octave> test(p) +ans = 0 + +``` + +which means $p$ is on the line $o$." +969292,"I develop some program and I encountered to this problem: + +![enter image description here](https://i.stack.imgur.com/5reAv.png) + +We know point **P**, **X**, and angle **a**. Range of angle is <0°,360°> between lines **p** and **o**. How I can determine in which side of line **o** is point **X**? Line **p** is always perpendicular to x axe. I thought that I would use this equation: (**Bx - Ax) \* (Cy - Ay) - (By - Ay) \* (Cx - Ax)** (slope) but second point of line **o** is missing and I have no idea how do this with given angle.",2014/10/11,"['https://math.stackexchange.com/questions/969292', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/183624/']","Equation for line $o$: +$$ +u(t) = p + t q +$$ +for $t \in \mathbb{R}$ with normed direction vector $q = (\sin a, \cos a)^T$ and vector $p = (x, y)^T$. Then +$$ +v = x-p +$$ +where $x = (a, b)^T$ (vector $x$, not coordinate $x$; coordinate $a$, not angle $a$) and $v$ is the vector from line $o$, at the end point of $p$, to the end point of $x$. + +And now we decompose $v$ into two parts: +$$ +v\_q = (v \cdot q) \, q +$$ +is the part of $v$ in direction of $q$. Then +$$ +v\_\perp = v - v\_q +$$ +is the part of $v$ orthogonal to $o$'s direction vector $q$. +It should have a negative $y$ coordinate if $x$'s end point is below the line $o$, if the angle $a$ is non-zero, $a \in (0, 2\pi)$. + +Otherwise ($a = 0$) check if it's $x$ coordinate is positive. + +### Example + +This is a vector on the line $o$: + +``` +octave> p = [2, 5]' +p = + 2 + 5 + +``` + +Line $o$ has an $60^\circ$ angle $a$ regarding to the $y$-axis: + +``` +octave> a = 60 * 2 * pi / 360 + a = 1.0472 + +``` + +Vector $q$ is a normed direction vector of line $o$: + +``` +octave> q = [sin(a), cos(a)]' + q = + 0.86603 + 0.50000 + +``` + +This is an example vector below the line $o$: + +``` +octave> x = [4,3]' + x = + 4 + 3 + +``` + +Here we have the difference vector $v$ that would lead from $p$ to $x$: + +``` +octave> v = x - p + v = + 2 + -2 + +``` + +This is $v\_q$, the part of $v$ in direction of $q$: + +``` +octave> vq = (v' * q) * q + vq = + 0.63397 + 0.36603 + +``` + +And this is $v\_\perp$, the part of $v$ orthogonal to $q$: + +``` +octave> vo = v - vq + vo = + 1.3660 + -2.3660 + +``` + +A test: + +``` +octave> vo + vq + ans = + 2.0000 + -2.0000 + +``` + +The $y$-coordinate is negative (and $a$ is non-zero): + +``` +octave> vo(2) + ans = -2.3660 + +``` + +We can put the test into an octave function: + +``` +octave> function res = test(x) +> p=[2,5]' +> a = 60*2*pi/360 +> q = [sin(a), cos(a)]' +> v = x - p +> vq = (v'*q)*q +> vo = v - vq +> if (vo(2) == 0) +> res = 0 +> else +> res = vo(2)/abs(vo(2)) +> endif +> endfunction + +``` + +Some applications: + +``` +octave> x2 = [ -2, 7]' +octave> test(x2) +.. +ans = 1 + +``` + +which means $x\_2$ is above line $o$. And then + +``` +octave> test(p) +ans = 0 + +``` + +which means $p$ is on the line $o$.","Another way (renamed the angle as ""A"" to avoid confussion with the coordinate ""a""): if (a-x)\*tan(A)>b-y then X is below the line." +969292,"I develop some program and I encountered to this problem: + +![enter image description here](https://i.stack.imgur.com/5reAv.png) + +We know point **P**, **X**, and angle **a**. Range of angle is <0°,360°> between lines **p** and **o**. How I can determine in which side of line **o** is point **X**? Line **p** is always perpendicular to x axe. I thought that I would use this equation: (**Bx - Ax) \* (Cy - Ay) - (By - Ay) \* (Cx - Ax)** (slope) but second point of line **o** is missing and I have no idea how do this with given angle.",2014/10/11,"['https://math.stackexchange.com/questions/969292', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/183624/']","You have two vectors: $X-P$ and $\langle \cos\left(\frac{\pi}{2}-\alpha\right), \sin\left(\frac{\pi}{2}-\alpha\right)\rangle$. $X$ lies below the line if and only if $(X-P) \times \langle \cos\left(\frac{\pi}{2}-\alpha\right), \sin\left(\frac{\pi}{2}-\alpha\right)\rangle$ (when both are regarded as vectors in $\mathbb{R}^3$ with zero third coordinate) points upwards (so that the three form a right-handed system).","Another way (renamed the angle as ""A"" to avoid confussion with the coordinate ""a""): if (a-x)\*tan(A)>b-y then X is below the line." +2817849,"Is there any PNG-fix for IE 6 and without modifying current HTML, CSS and image name? + +any javascript way. + +I can add any thing in `........` but can't modify anythings inside `.....`. + +in one shot i want to make transparent all png transparent.",2010/05/12,"['https://Stackoverflow.com/questions/2817849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84201/']","As I just learned, [this script](http://code.google.com/p/ie7-js/) will make IE behave like a standards compliant browser, including PNG fixes.","This can be fix in 2 way + +1. There is a fix file called png-fix.js, just get from net and include it before your `` tag. +2. Better you can change you png file format into png-8 format via the photo-shop tool." +2817849,"Is there any PNG-fix for IE 6 and without modifying current HTML, CSS and image name? + +any javascript way. + +I can add any thing in `........` but can't modify anythings inside `.....`. + +in one shot i want to make transparent all png transparent.",2010/05/12,"['https://Stackoverflow.com/questions/2817849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84201/']","As I just learned, [this script](http://code.google.com/p/ie7-js/) will make IE behave like a standards compliant browser, including PNG fixes.","My preferred PNGFix is [DD\_belatedPNG](http://www.dillerdesign.com/experiment/DD_belatedPNG/). It is easy to use, example from the page: + +``` + + +``` + +You can set that `.png_bg` selector to whatever you see fit. Perhaps you want to replace all of the headings on a page: `DD_belatedPNG.fix('h1,h2,h3');`" +2817849,"Is there any PNG-fix for IE 6 and without modifying current HTML, CSS and image name? + +any javascript way. + +I can add any thing in `........` but can't modify anythings inside `.....`. + +in one shot i want to make transparent all png transparent.",2010/05/12,"['https://Stackoverflow.com/questions/2817849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84201/']","OK here's a question: if you can't modify the HTML, CSS or image at all, what the heck *can* you modify? The raw network stream coming from the server?","This can be fix in 2 way + +1. There is a fix file called png-fix.js, just get from net and include it before your `` tag. +2. Better you can change you png file format into png-8 format via the photo-shop tool." +2817849,"Is there any PNG-fix for IE 6 and without modifying current HTML, CSS and image name? + +any javascript way. + +I can add any thing in `........` but can't modify anythings inside `.....`. + +in one shot i want to make transparent all png transparent.",2010/05/12,"['https://Stackoverflow.com/questions/2817849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84201/']","My preferred PNGFix is [DD\_belatedPNG](http://www.dillerdesign.com/experiment/DD_belatedPNG/). It is easy to use, example from the page: + +``` + + +``` + +You can set that `.png_bg` selector to whatever you see fit. Perhaps you want to replace all of the headings on a page: `DD_belatedPNG.fix('h1,h2,h3');`","This can be fix in 2 way + +1. There is a fix file called png-fix.js, just get from net and include it before your `` tag. +2. Better you can change you png file format into png-8 format via the photo-shop tool." +2817849,"Is there any PNG-fix for IE 6 and without modifying current HTML, CSS and image name? + +any javascript way. + +I can add any thing in `........` but can't modify anythings inside `.....`. + +in one shot i want to make transparent all png transparent.",2010/05/12,"['https://Stackoverflow.com/questions/2817849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84201/']","OK here's a question: if you can't modify the HTML, CSS or image at all, what the heck *can* you modify? The raw network stream coming from the server?","My preferred PNGFix is [DD\_belatedPNG](http://www.dillerdesign.com/experiment/DD_belatedPNG/). It is easy to use, example from the page: + +``` + + +``` + +You can set that `.png_bg` selector to whatever you see fit. Perhaps you want to replace all of the headings on a page: `DD_belatedPNG.fix('h1,h2,h3');`" +51619280,"According to this [docs](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.relationaldatabasefacadeextensions.executesqlcommand?view=efcore-2.1) and [this](https://learn.microsoft.com/en-us/ef/core/querying/raw-sql), I should be able to pass an interpolated string to `ExecuteSqlCommandAsync` like this: + +``` +public async Task DeleteEntries(DateTimeOffset loggedOn) { + await myContext.Database.ExecuteSqlCommandAsync( + $""DELETE from log_entry WHERE logged_on < '{loggedOn}';"" + ); +} + +``` + +However, it gives me the following error: `Npgsql.PostgresException: '22007: invalid input syntax for type timestamp with time zone: ""@p0""'` + +1. `loggedOn` is a valid date. +2. Extracting the interpolated string to a temporary variable fixes it, however I am losing input validation for SQL injection attacks. + +Am i doing something wrong or is this a bug in EFCore? Using latest EFCore 2.1",2018/07/31,"['https://Stackoverflow.com/questions/51619280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5053000/']","As provided by @IvanStoev, the answer was to remove single quotes around the interpolated parameter.","That webpage you refer to, warns you to not have direct values inserted into SQL, that is to use parameters like so: + +``` +FromSql(""EXECUTE dbo.GetMostPopularBlogsForUser @user"", user) + +``` + +So, adjust it to your needs and have something like: + +``` +FromSql(""DELETE from log_entry WHERE logged_on < @logged_on"", loggedOn.ToString(""0"")) + +``` + +P.S. do not use double quotes `""` for the table names - either use no quotes or wrap them with `[]` as `[log_entry]`." +39762688,"How I can open Short Message Service (SMS) window on Android phode with pretyped message text and recipient number. + +In manuals i found only Phone dialer + +``` + PhoneDialerService.Call(edtTelephoneNumber.Text) + +``` + +which allow make call, but nothing about sending SMS messages.",2016/09/29,"['https://Stackoverflow.com/questions/39762688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6760778/']","See the class [`SMSManager`](https://d.android.com/reference/android/telephony/SmsManager.html) on Android API. + +There is a [`sendTextMessage`](https://d.android.com/reference/android/telephony/SmsManager.html#sendTextMessage(java.lang.String,%20java.lang.String,%20java.lang.String,%20android.app.PendingIntent,%20android.app.PendingIntent)) method that you can use: + +Try some code like this: + +``` +uses + Androidapi.Helpers, + Androidapi.JNI.JavaTypes, + Androidapi.JNI.Telephony; + +procedure TForm1.Button1Click(Sender: TObject); +var + destAdress: JString; + smsManager: JSmsManager; +begin + smsManager := TJSmsManager.JavaClass.getDefault; + destAdress := StringToJString('0034123456789'); + smsManager.sendTextMessage(destAdress, nil, StringToJString('The message content'), nil, nil); +end; + +``` + +You must [add permissions](http://docwiki.embarcadero.com/RADStudio/en/Uses_Permissions) to the project configuration. See the ""Send SMS"": + +> +> Send SMS - Allows an application to send SMS messages. +> +> +> + +Regards.","The question asks about launching the SMS window, which I've taken to mean launching the built-in SMS-sending app. It wants a target number and message content sent in. + +This can be done by asking Android to start an activity using an intent set up to view a carefully crafted SMS-specific URI and containing the required message as an extra field. + +The primary benefit to invoking the SMS app rather than sending the SMS within your own app is that it does not require additional permissions - the SMS app already has those permissions. + +I show how to do this in [my old activity launching article](http://blong.com/Articles/DelphiXE6AndroidActivityResult/ActivityResult.htm#SMSActivity) (which was written for Delphi XE6 but is still applicable to all later versions, with a few minor code updates here and there), but for completeness here is a helper unit that does the job: + +``` +unit SMSHelperU; + +interface + +procedure CreateSMS(const Number, Msg: string); + +implementation + +uses + Androidapi.Helpers, + Androidapi.JNI.JavaTypes, + Androidapi.JNI.App, + Androidapi.JNI.Net, + Androidapi.JNI.GraphicsContentViewText, + System.SysUtils; + +function LaunchActivity(const Intent: JIntent): Boolean; overload; +var + ResolveInfo: JResolveInfo; +begin +{$IF RTLVersion >= 30} + ResolveInfo := TAndroidHelper.Activity.getPackageManager.resolveActivity(Intent, 0); +{$ELSE} + ResolveInfo := SharedActivity.getPackageManager.resolveActivity(Intent, 0); +{$ENDIF} + Result := ResolveInfo <> nil; + if Result then +{$IF RTLVersion >= 30} + TAndroidHelper.Activity.startActivity(Intent); +{$ELSE} + SharedActivity.startActivity(Intent); +{$ENDIF} +end; + +procedure CreateSMS(const Number, Msg: string); +var + Intent: JIntent; + URI: Jnet_Uri; +begin + URI := StrToJURI(Format('smsto:%s', [Number])); + Intent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_VIEW, URI); + Intent.putExtra(StringToJString('sms_body'), StringToJString(Msg)); + LaunchActivity(Intent); +end; + +end. + +``` + +The routine can be called like this: + +``` +CreateSMS('123456789', 'O HAI2U!'); + +``` + +If you did want to actually send the SMS the unit below does that job but also includes code that self-checks the relevant permission is set for the app: + +``` +unit AndroidStuff; + +interface + +function HasPermission(const Permission: string): Boolean; +procedure SendSMS(const Number, Msg: string); + +implementation + +uses + System.SysUtils, + System.UITypes, +{$IF RTLVersion >= 31} + FMX.DialogService, +{$ELSE} + FMX.Dialogs, +{$ENDIF} + FMX.Helpers.Android, + Androidapi.Helpers, + Androidapi.JNI.App, + Androidapi.JNI.JavaTypes, + Androidapi.JNI.GraphicsContentViewText, + Androidapi.JNI.Telephony; + +function HasPermission(const Permission: string): Boolean; +begin + //Permissions listed at http://d.android.com/reference/android/Manifest.permission.html +{$IF RTLVersion >= 30} + Result := TAndroidHelper.Context.checkCallingOrSelfPermission( +{$ELSE} + Result := SharedActivityContext.checkCallingOrSelfPermission( +{$ENDIF} + StringToJString(Permission)) = + TJPackageManager.JavaClass.PERMISSION_GRANTED +end; + +procedure SendSMS(const Number, Msg: string); +var + SmsManager: JSmsManager; +begin + if not HasPermission('android.permission.SEND_SMS') then +{$IF RTLVersion >= 31} + TDialogService.MessageDialog('App does not have the SEND_SMS permission', TMsgDlgType.mtError, [TMsgDlgBtn.mbCancel], TMsgDlgBtn.mbCancel, 0, nil) +{$ELSE} + MessageDlg('App does not have the SEND_SMS permission', TMsgDlgType.mtError, [TMsgDlgBtn.mbCancel], 0) +{$ENDIF} + else + begin + SmsManager := TJSmsManager.JavaClass.getDefault; + SmsManager.sendTextMessage( + StringToJString(Number), + nil, + StringToJString(Msg), + nil, + nil); + end; +end; + +end. + +```" +1911782,"I came across the following question today: + +> +> ""In drawing two balls from a box containing 6 red and 4 white balls without replacement, which of the following pairs will be independent?: +> +> +> (a) Red on 1st and red on 2nd draw +> (b) Red on 1st and white on 2nd draw +> +> +> + +I approached this problem by writing down the sample space as {RW, RR, WW, WR} first. + +Then, let $A$ be the event that red is drawn first and $B$ be the event that red is drawn second; +$A$=$({RW}, {RR}) and $B=$({RR}, {WR}) + +Which gives me $A∩B$={$RR$} + +Therefore, I get +$P(A)=1/2$ +$P(B)=1/2$ and +$P(A∩B)=1/4$ + +Which gives me $P(A)P(B)=P(A∩B)$, proving that A and B are independent events. However, clearly, this is nonsense! A and B are absolutely **not** independent events, since the occurrence of A affects the chances of occurrence of B. Where have I gone completely wrong in my reasoning? + +Edit: My textbook has solved this problem correctly in the following way but I am not interested in the solution to this problem in particular; I want to know where I have made a grave mistake. Please correct me for if I don't understand my mistake, I will continue to commit the **same** mistake in the future as well. Much thanks in advance :) Regards. + +[![Textbook solution](https://i.stack.imgur.com/FHWgD.jpg)](https://i.stack.imgur.com/FHWgD.jpg)",2016/09/02,"['https://math.stackexchange.com/questions/1911782', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']","Let $I$ be a fixed interval $[a,b]$. Then you may let $F=\mathbb{Q} \cap I$ (rationals in $I$) and $G=I\setminus \mathbb{Q}$ (irrationals in $I$), which satisfy all the properties you want. + +As you point out, there is no 'least next' value, but this is not an issue because your last bullet point doesn't necessitate that such things exist. Instead, it is sufficient for both $F$ and $G$ to be dense in $I$. + +To answer your last question, nothing changes, we could take $F= (I\cap \mathbb{Q})\cap \{n/2^m \mid \text{$n$ odd integer, $m\geq 0$}\}$ and $G = (I\cap \mathbb{Q}) \setminus \{n/2^m \mid \text{$n$ odd integer, $m\geq 0$}\}$. The elements of $\{n/2^m \mid \text{$n$ odd integer, $m\geq 0$}\}$ are called the dyadic rationals. + +As far as your function $z(x)$ defined by +$$z(x) = \begin{cases} x+1 & x\in F \\ x-1 & x\in G \end{cases}$$ +is concerned, it does indeed exist (that's a valid definition above). While it separates $I$, that isn't really a problem.","To summarize what you're asking for: you want a partition of $\mathbb{R}$ into two sets $F$ and $G$, such that there is an element of $F$ between any two elements of $G$ and vice-versa. Certainly this is possible: let $F$ and $G$ be the rationals and the irrationals, respectively. And your zipper-like function is well-defined: $z(x)$ increases rational numbers by $1$ and decreases irrational numbers by $1$, and so it is discontinuous everywhere, even though it is continuous when restricted to either the rationals or the irrationals. Altering the base set from $\mathbb{R}$ to $\mathbb{Q}$ doesn't change any of this. For instance, you can let $F$ be the set of rationals with prime denominators (in lowest terms). Both $F$ and $\mathbb{Q}-F$ are dense on the real line, so they interleave in the way you want." +1911782,"I came across the following question today: + +> +> ""In drawing two balls from a box containing 6 red and 4 white balls without replacement, which of the following pairs will be independent?: +> +> +> (a) Red on 1st and red on 2nd draw +> (b) Red on 1st and white on 2nd draw +> +> +> + +I approached this problem by writing down the sample space as {RW, RR, WW, WR} first. + +Then, let $A$ be the event that red is drawn first and $B$ be the event that red is drawn second; +$A$=$({RW}, {RR}) and $B=$({RR}, {WR}) + +Which gives me $A∩B$={$RR$} + +Therefore, I get +$P(A)=1/2$ +$P(B)=1/2$ and +$P(A∩B)=1/4$ + +Which gives me $P(A)P(B)=P(A∩B)$, proving that A and B are independent events. However, clearly, this is nonsense! A and B are absolutely **not** independent events, since the occurrence of A affects the chances of occurrence of B. Where have I gone completely wrong in my reasoning? + +Edit: My textbook has solved this problem correctly in the following way but I am not interested in the solution to this problem in particular; I want to know where I have made a grave mistake. Please correct me for if I don't understand my mistake, I will continue to commit the **same** mistake in the future as well. Much thanks in advance :) Regards. + +[![Textbook solution](https://i.stack.imgur.com/FHWgD.jpg)](https://i.stack.imgur.com/FHWgD.jpg)",2016/09/02,"['https://math.stackexchange.com/questions/1911782', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']","Let $I$ be a fixed interval $[a,b]$. Then you may let $F=\mathbb{Q} \cap I$ (rationals in $I$) and $G=I\setminus \mathbb{Q}$ (irrationals in $I$), which satisfy all the properties you want. + +As you point out, there is no 'least next' value, but this is not an issue because your last bullet point doesn't necessitate that such things exist. Instead, it is sufficient for both $F$ and $G$ to be dense in $I$. + +To answer your last question, nothing changes, we could take $F= (I\cap \mathbb{Q})\cap \{n/2^m \mid \text{$n$ odd integer, $m\geq 0$}\}$ and $G = (I\cap \mathbb{Q}) \setminus \{n/2^m \mid \text{$n$ odd integer, $m\geq 0$}\}$. The elements of $\{n/2^m \mid \text{$n$ odd integer, $m\geq 0$}\}$ are called the dyadic rationals. + +As far as your function $z(x)$ defined by +$$z(x) = \begin{cases} x+1 & x\in F \\ x-1 & x\in G \end{cases}$$ +is concerned, it does indeed exist (that's a valid definition above). While it separates $I$, that isn't really a problem.","Such a partition does exist. Let $F = I \cap \Bbb Q$ and $G = I \setminus F$. It's clear that $F$ and $G$ have empty intersection, and their union is all of $I$. + +And for any two rational numbers, there's an irrational number between them. The other way around too. Since this is all taking place inside an interval $I$, the middle point that you find is also in $I$." +7579300,"I have tried several ways to serve my static resources from Plone with XDV: + +1. Putting the CSS and images in the Custom folder - files are 404 not found +2. Serving them from Apache and setting the Absolute URL Prefix in the XDV config - works, but any other relatively URL'd links (e.g. PDF files in my content) get prefixed as well and therefore are 404 not found +3. Setting browser:resourceDirectory - 404 not found +4. Setting cmf:registerDirectory - 404 not found + +Any suggestions? I've turned the log level to DEBUG but this doesn't give me any clues.",2011/09/28,"['https://Stackoverflow.com/questions/7579300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/535071/']","You just need to put your css/js in the ""static"" directory and than use relative path in the index.html. Diazo/XDV will automagically remap relative paths. + +Or you can also register a resourceDirectory in the usual way and than link files like so ""++resource++myresourcedirid/my.css"" + +See an example [here](https://github.com/giacomos/plonetheme.codapress/blob/master/plonetheme/codapress/static/index.html).","I managed to use static content served by Apache using mod\_rewrite and the following rules in Apache Virtual Host configuration. + +``` +RewriteRule ^/css - [L] +RewriteRule ^/img - [L] + +``` + +I have also used Giacomo method for specific Plone content style with the `static` directory in my package which is linked in the ""index.html"" as ""++resource++mypackage.theme/plone.css""" +52417142,"I've got a bug that looks like it's caused by an Event handler being attached a click event: + +``` + mxpnl.track_links(""#pagebody a"", ""Click.body""); + +``` + +I'd like to watch to see how that Element's event handler is added (and when) + +I found it in the Chrome Debugger (Dev Tools) > Elements and choose Break on Attribute modifications. Debugger never Breaks. + +I also selected it's Parent Div (that it is within) and set Debugger (right-click on Element) > break on subtree modifications. Again, it never breaks. + +What am I doing wrong here?",2018/09/20,"['https://Stackoverflow.com/questions/52417142', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4906/']","Adding an event listener isn't an attribute change (often) - rather, generally it's a call to `addEventListener` or an `on`- assignment. So, listening to attribute changes won't work. + +One option would be to monkeypatch `addEventListener` so that `debugger` runs when `addEventListener` is called with the matching arguments. For example: + +```js +// snippet might not actually enter the debugger due to embedded sandboxing issues + +const nativeEventListener = EventTarget.prototype.addEventListener; +EventTarget.prototype.addEventListener = function(...args) { + if (this.matches('div') && args[0] === 'click') { + console.log('listener is being added to a div'); + debugger; + } + nativeEventListener.apply(this, args); +} + +// then, when an event listener is added, you'll be able to intercept the call and debug it: + +document.querySelector('div').addEventListener('click', () => { + console.log('clicked'); +}); +``` + +```html +
click me
+```","In very simple term if explain then event listeners is just a function which add in an array with reference of string such as ""click"" and ""on"" etc.. + +So when you say..... + +``` + function myClick1(){ + console.log('myclick1 called'); +} + document.querySelector('mydiv').addEventListener('click', myClick1); + function myClick2(){ + console.log('myclick2 called'); + } +document.querySelector('mydiv').addEventListener('click', myClick2); + +``` + +it add the function myClick1 and myClick2 in event listener array for click and execute in sequence as it added. + +AND YOU CAN USE PROTOTYPE OF EVENT TARGET TO MONKEY PATCH THE EVENT LISTENER ARRAY." +2493585,"Can anyone help with extracting text from a page in a pdf? + +``` +page[0]; + +``` + +I would assume a page method would exist but I could not find anything to let me extract the contents. + +Example: $page->getContents(); $page->toString(); $page->extractText(); + +...Help!!!! This is driving me crazy!",2010/03/22,"['https://Stackoverflow.com/questions/2493585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/272645/']","I agree with Andy that this does not appear to be supported. As an alternative, take a look at [Shaun Farrell's solution to extracting text from a PDF for use with Zend\_Search\_Lucene](http://www.kapustabrothers.com/2008/01/20/indexing-pdf-documents-with-zend_search_lucene/). He uses [XPDF](http://www.foolabs.com/xpdf/), which might also meet your needs.","From [the manual](http://framework.zend.com/manual/en/zend.pdf.html) it doesn't appear that this functionality is supported. Also, new text is written using the [drawText() function](http://framework.zend.com/manual/en/zend.pdf.usage.html), which appears to write images, not plain ""decodable"" text." +16766300,I am developing an applciation which requires to connect to sql database server. I am planning to connect to database directly without using webservice. Let me know if its possible?,2013/05/27,"['https://Stackoverflow.com/questions/16766300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2361064/']","you can directly connect to the sqlite database that is in phone. but you can not directly connect to the remote database like mysql , MSSQL and other database. if you really need to use that database you have to use web service(SOAP or REST), Http request or JSON.","You can't access remote database server without web services. If you want, you can access internal database (sqlite) without any web services. I have a doubt whether you are asking that. For that this [video](http://www.youtube.com/watch?v=j-IV87qQ00M) may be helpful for you." +3929368,"I really need help with that question, so I'd appreciate a solution with steps because this problem was given for practice and my exam is in a few days so I'd like to understand the steps to the solution. Thank you.",2020/11/30,"['https://math.stackexchange.com/questions/3929368', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']","I think what this question is getting at is that, to be a basis of a vector space, + +a set of vectors must span the vector space and be linearly independent. + +If $\pmatrix{x\\y}$ is any element of $\mathbb R^2$, we can solve $\pmatrix{x\\y}=a\pmatrix{1\\2}+b\pmatrix{1\\3}$ + +to get $a=3x-y$ and $b=y-2x$, + +so $\pmatrix{x\\y}$ is a linear combination of $\pmatrix{1\\2}$ and $\pmatrix{1\\3}$, so $\pmatrix{1\\2}$ and $\pmatrix{1\\3}$ span $\mathbb R^2$ + +(so certainly $\pmatrix{1\\2}$, $\pmatrix{1\\3},$ and $\pmatrix{1\\4}$ span $\mathbb R^2$). + +Indeed, any two linearly independent vectors in $\mathbb R^2$ (which is a $2$-dimensional vector space over $\mathbb R$) + +will span $\mathbb R^2$ and be a basis. + +Elements of a basis must be linearly independent, but $(1,4)=2(1,3)-(1,2)$, + +so the set of three vectors given are not a basis.","**HINT** + +To spell out the comment hint a bit more, if $U$ spans $\mathbb{R}^2$, and $\vec{b} \in \mathbb{R}^2$, then there must exist $x,y,z \in \mathbb{R}$ such that +$$ +\vec{b} + = x\begin{bmatrix} 1\\2\end{bmatrix} + + y\begin{bmatrix} 1\\3\end{bmatrix} + + z\begin{bmatrix} 1\\4\end{bmatrix} + = \begin{bmatrix} 1 & 1 & 1 \\2 & 3 & 4\end{bmatrix} + \begin{bmatrix} x\\y\\z\end{bmatrix} +$$ +So you have to prove that any $b$ can be generated that way..." +3929368,"I really need help with that question, so I'd appreciate a solution with steps because this problem was given for practice and my exam is in a few days so I'd like to understand the steps to the solution. Thank you.",2020/11/30,"['https://math.stackexchange.com/questions/3929368', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']","**HINT** + +To spell out the comment hint a bit more, if $U$ spans $\mathbb{R}^2$, and $\vec{b} \in \mathbb{R}^2$, then there must exist $x,y,z \in \mathbb{R}$ such that +$$ +\vec{b} + = x\begin{bmatrix} 1\\2\end{bmatrix} + + y\begin{bmatrix} 1\\3\end{bmatrix} + + z\begin{bmatrix} 1\\4\end{bmatrix} + = \begin{bmatrix} 1 & 1 & 1 \\2 & 3 & 4\end{bmatrix} + \begin{bmatrix} x\\y\\z\end{bmatrix} +$$ +So you have to prove that any $b$ can be generated that way...","For instance, $(1,3)$ is not a multiple of $(1,2)$, so they are independent and span $\Bbb R^2$. + +But any $3$ vectors in a two-dimensional space are dependent, and so can't form a basis. + +I have taken as given that $\Bbb R^2$ is two-dimensional, say with basis $e\_1=(1,0)$ and $e\_2=(0,1)$." +3929368,"I really need help with that question, so I'd appreciate a solution with steps because this problem was given for practice and my exam is in a few days so I'd like to understand the steps to the solution. Thank you.",2020/11/30,"['https://math.stackexchange.com/questions/3929368', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']","I think what this question is getting at is that, to be a basis of a vector space, + +a set of vectors must span the vector space and be linearly independent. + +If $\pmatrix{x\\y}$ is any element of $\mathbb R^2$, we can solve $\pmatrix{x\\y}=a\pmatrix{1\\2}+b\pmatrix{1\\3}$ + +to get $a=3x-y$ and $b=y-2x$, + +so $\pmatrix{x\\y}$ is a linear combination of $\pmatrix{1\\2}$ and $\pmatrix{1\\3}$, so $\pmatrix{1\\2}$ and $\pmatrix{1\\3}$ span $\mathbb R^2$ + +(so certainly $\pmatrix{1\\2}$, $\pmatrix{1\\3},$ and $\pmatrix{1\\4}$ span $\mathbb R^2$). + +Indeed, any two linearly independent vectors in $\mathbb R^2$ (which is a $2$-dimensional vector space over $\mathbb R$) + +will span $\mathbb R^2$ and be a basis. + +Elements of a basis must be linearly independent, but $(1,4)=2(1,3)-(1,2)$, + +so the set of three vectors given are not a basis.","For instance, $(1,3)$ is not a multiple of $(1,2)$, so they are independent and span $\Bbb R^2$. + +But any $3$ vectors in a two-dimensional space are dependent, and so can't form a basis. + +I have taken as given that $\Bbb R^2$ is two-dimensional, say with basis $e\_1=(1,0)$ and $e\_2=(0,1)$." +4924600,"I need to get the full path to a file somewhere on the phone (any location) and play it with MediaPlayer. + +ive heard of using a file chooser for Android (by launching an intent). + +In the test code, I just copied a resource to a another file, got the path and passed it to AudioVideoEntry (as i show later, a very simple and thin wrapper around MediaPlayer) + +Here's the test code I've written: + +``` +private String ave_path; + private String ave_file_name = ""my_media_content""; + private InputStream ave_fis; + private OutputStream ave_fos; + public void testAudioVideoEntry() + { + //get the Activity + Module_JournalEntry journalentryactivity = getActivity(); + //open an InputStream to a resource file (in this case strokes.mp3) + ave_fis = journalentryactivity.getResources().openRawResource(module.jakway.JournalEntry.R.raw.strokes); + + //open an OutputStream to a new file + try { + ave_fos = journalentryactivity.openFileOutput(ave_file_name, + Context.MODE_PRIVATE); + } catch (FileNotFoundException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + assertTrue(false); + } + catch(Exception e) + { + assertTrue(false); + } + + //copy the data from the resource into + //the OutputStream + int data; + try { + while((data = ave_fis.read()) != -1) + { + ave_fos.write(data); + } + assertTrue(true); + } + catch(Exception e) + { + assertTrue(false); + } + + //get the full path of the file we wrote to + ave_path = journalentryactivity.getFileStreamPath(ave_file_name).toString(); + + //and construct a new object of AudioVideoEntry with that path + AudioVideoEntry ave = new AudioVideoEntry(ave_path); + + //register an error listener via MediaPlayer's setOnErrorListener + ave.setOnErrorListener(new OnErrorListener() + { + @Override + public boolean onError(MediaPlayer mp, + int what, int extra) { + Log.e(""MEDIAPLAYER ERRORS"", + ""what: "" + what + "" extra: "" + extra); + assertTrue(false); + // TODO Auto-generated method stub + return false; + } + }); + ave.prepareMedia(); + ave.playMedia(); + try { + ave_fis.close(); + ave_fos.close(); + } + catch(Exception e) + { + assertTrue(false); + e.printStackTrace(); + } + +``` + +AudioVideoEntry is basically a thin wrapper around MediaPlayer that can hold its own path: + +``` +public class AudioVideoEntry +{ + private String path_to_audio_file; + private MediaPlayer mediaplayer; + + /** + * Initialize the internal MediaPlayer + * from the String parameter + * @param set_path_to_audio_file + */ + public AudioVideoEntry(String set_path_to_audio_file) + { + path_to_audio_file = set_path_to_audio_file; + mediaplayer = new MediaPlayer(); + try { + mediaplayer.setDataSource(path_to_audio_file); + mediaplayer.prepare(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public AudioVideoEntry(FileDescriptor fd) + { + + mediaplayer = new MediaPlayer(); + try { + mediaplayer.setDataSource(fd); + mediaplayer.prepare(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * Begin playing media + */ + public void prepareMedia() + { + try { + mediaplayer.prepare(); + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * play media + * don't forget to prepare() if necessary + */ + public void playMedia() + { + mediaplayer.start(); + } + + /** + * pause the media + * can be played later + */ + public void pauseMedia() + { + mediaplayer.pause(); + } + + /** + * stop media + */ + public void stopMedia() + { + mediaplayer.stop(); + } + + public void setOnErrorListener(OnErrorListener listener) + { + mediaplayer.setOnErrorListener(listener); + } +} + +``` + +here's the logcat output from the JUnit test (the tests were successful, the actual results - as the logat shows - were not) + +``` +02-07 09:40:23.129: ERROR/MediaPlayer(1209): error (1, -2147483648) +02-07 09:40:23.139: WARN/System.err(1209): java.io.IOException: Prepare failed.: status=0x1 +02-07 09:40:23.149: WARN/System.err(1209): at android.media.MediaPlayer.prepare(Native Method) +02-07 09:40:23.149: WARN/System.err(1209): at module.jakway.JournalEntry.AudioVideoEntry.(AudioVideoEntry.java:39) +02-07 09:40:23.149: WARN/System.err(1209): at module.jakway.JournalEntry.test.Module_JournalEntryTest.testAudioVideoEntry(Module_JournalEntryTest.java:182) +02-07 09:40:23.149: WARN/System.err(1209): at java.lang.reflect.Method.invokeNative(Native Method) +02-07 09:40:23.149: WARN/System.err(1209): at java.lang.reflect.Method.invoke(Method.java:507) +02-07 09:40:23.159: WARN/System.err(1209): at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204) +02-07 09:40:23.159: WARN/System.err(1209): at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194) +02-07 09:40:23.159: WARN/System.err(1209): at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186) +02-07 09:40:23.159: WARN/System.err(1209): at junit.framework.TestCase.runBare(TestCase.java:127) +02-07 09:40:23.169: WARN/System.err(1209): at junit.framework.TestResult$1.protect(TestResult.java:106) +02-07 09:40:23.169: WARN/System.err(1209): at junit.framework.TestResult.runProtected(TestResult.java:124) +02-07 09:40:23.169: WARN/System.err(1209): at junit.framework.TestResult.run(TestResult.java:109) +02-07 09:40:23.179: WARN/System.err(1209): at junit.framework.TestCase.run(TestCase.java:118) +02-07 09:40:23.179: WARN/System.err(1209): at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169) +02-07 09:40:23.179: WARN/System.err(1209): at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154) +02-07 09:40:23.179: WARN/System.err(1209): at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529) +02-07 09:40:23.189: WARN/System.err(1209): at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447) +02-07 09:40:23.189: ERROR/MediaPlayer(1209): prepareAsync called in state 0 +02-07 09:40:23.189: WARN/System.err(1209): java.lang.IllegalStateException +02-07 09:40:23.189: WARN/System.err(1209): at android.media.MediaPlayer.prepare(Native Method) +02-07 09:40:23.189: WARN/System.err(1209): at module.jakway.JournalEntry.AudioVideoEntry.prepareMedia(AudioVideoEntry.java:79) +02-07 09:40:23.199: WARN/System.err(1209): at module.jakway.JournalEntry.test.Module_JournalEntryTest.testAudioVideoEntry(Module_JournalEntryTest.java:197) +02-07 09:40:23.199: WARN/System.err(1209): at java.lang.reflect.Method.invokeNative(Native Method) +02-07 09:40:23.199: WARN/System.err(1209): at java.lang.reflect.Method.invoke(Method.java:507) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestCase.runBare(TestCase.java:127) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestResult$1.protect(TestResult.java:106) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestResult.runProtected(TestResult.java:124) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestResult.run(TestResult.java:109) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestCase.run(TestCase.java:118) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529) +02-07 09:40:23.199: WARN/System.err(1209): at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447) +02-07 09:40:23.199: ERROR/MediaPlayer(1209): start called in state 0 +02-07 09:40:23.199: ERROR/MediaPlayer(1209): error (-38, 0) + +``` + +Edit: why is MediaPlayer failing? + +thanks! +dragonwrenn",2011/02/07,"['https://Stackoverflow.com/questions/4924600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/450153/']","Some points: + +1. Do not call `prepare()` twice (once in the constructor and the other explicitly). That could be one of the reasons that the `IllegalStateException` is thrown. +2. Also, is the file that you are trying to play inside the application? If so, why are you trying to create a stream? If the file is already within the application (and within `/res/raw`, you could try and save yourself the hassle of using `prepare()` by creating the mediaplayer object like so: + +mediaplayer = new MediaPlayer.create(this, R.raw.resource-name here); + +The create function calls `prepare()` within. + +3. You can also try and use the `reset()` function if any one of the stages in the MediaPlayer fails resulting in the MediaPlayer object entering the error state. Using `reset()` would bring it back to Idle state. + +4. The last time I had that error `status=0x1` message, it turned out that I had not had the correct permissions set for the files (external storage etc. in Manifest) and some files placed in incorrect folders. You may also want to take a look at that. + +Let me know in case that does not work, + +We can try something else. + +Sriram.","It seems you are calling `prepare()` twice, first in the constructor of `AudioVideoEntry`, and second in the method `prepareMedia()`, that's why it's giving an `IllegalStateException`. + +If you read carefully the [documentation](http://developer.android.com/reference/android/media/MediaPlayer.html) you can understand the State Diagram and why gives such exceptions." +4924600,"I need to get the full path to a file somewhere on the phone (any location) and play it with MediaPlayer. + +ive heard of using a file chooser for Android (by launching an intent). + +In the test code, I just copied a resource to a another file, got the path and passed it to AudioVideoEntry (as i show later, a very simple and thin wrapper around MediaPlayer) + +Here's the test code I've written: + +``` +private String ave_path; + private String ave_file_name = ""my_media_content""; + private InputStream ave_fis; + private OutputStream ave_fos; + public void testAudioVideoEntry() + { + //get the Activity + Module_JournalEntry journalentryactivity = getActivity(); + //open an InputStream to a resource file (in this case strokes.mp3) + ave_fis = journalentryactivity.getResources().openRawResource(module.jakway.JournalEntry.R.raw.strokes); + + //open an OutputStream to a new file + try { + ave_fos = journalentryactivity.openFileOutput(ave_file_name, + Context.MODE_PRIVATE); + } catch (FileNotFoundException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + assertTrue(false); + } + catch(Exception e) + { + assertTrue(false); + } + + //copy the data from the resource into + //the OutputStream + int data; + try { + while((data = ave_fis.read()) != -1) + { + ave_fos.write(data); + } + assertTrue(true); + } + catch(Exception e) + { + assertTrue(false); + } + + //get the full path of the file we wrote to + ave_path = journalentryactivity.getFileStreamPath(ave_file_name).toString(); + + //and construct a new object of AudioVideoEntry with that path + AudioVideoEntry ave = new AudioVideoEntry(ave_path); + + //register an error listener via MediaPlayer's setOnErrorListener + ave.setOnErrorListener(new OnErrorListener() + { + @Override + public boolean onError(MediaPlayer mp, + int what, int extra) { + Log.e(""MEDIAPLAYER ERRORS"", + ""what: "" + what + "" extra: "" + extra); + assertTrue(false); + // TODO Auto-generated method stub + return false; + } + }); + ave.prepareMedia(); + ave.playMedia(); + try { + ave_fis.close(); + ave_fos.close(); + } + catch(Exception e) + { + assertTrue(false); + e.printStackTrace(); + } + +``` + +AudioVideoEntry is basically a thin wrapper around MediaPlayer that can hold its own path: + +``` +public class AudioVideoEntry +{ + private String path_to_audio_file; + private MediaPlayer mediaplayer; + + /** + * Initialize the internal MediaPlayer + * from the String parameter + * @param set_path_to_audio_file + */ + public AudioVideoEntry(String set_path_to_audio_file) + { + path_to_audio_file = set_path_to_audio_file; + mediaplayer = new MediaPlayer(); + try { + mediaplayer.setDataSource(path_to_audio_file); + mediaplayer.prepare(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public AudioVideoEntry(FileDescriptor fd) + { + + mediaplayer = new MediaPlayer(); + try { + mediaplayer.setDataSource(fd); + mediaplayer.prepare(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * Begin playing media + */ + public void prepareMedia() + { + try { + mediaplayer.prepare(); + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * play media + * don't forget to prepare() if necessary + */ + public void playMedia() + { + mediaplayer.start(); + } + + /** + * pause the media + * can be played later + */ + public void pauseMedia() + { + mediaplayer.pause(); + } + + /** + * stop media + */ + public void stopMedia() + { + mediaplayer.stop(); + } + + public void setOnErrorListener(OnErrorListener listener) + { + mediaplayer.setOnErrorListener(listener); + } +} + +``` + +here's the logcat output from the JUnit test (the tests were successful, the actual results - as the logat shows - were not) + +``` +02-07 09:40:23.129: ERROR/MediaPlayer(1209): error (1, -2147483648) +02-07 09:40:23.139: WARN/System.err(1209): java.io.IOException: Prepare failed.: status=0x1 +02-07 09:40:23.149: WARN/System.err(1209): at android.media.MediaPlayer.prepare(Native Method) +02-07 09:40:23.149: WARN/System.err(1209): at module.jakway.JournalEntry.AudioVideoEntry.(AudioVideoEntry.java:39) +02-07 09:40:23.149: WARN/System.err(1209): at module.jakway.JournalEntry.test.Module_JournalEntryTest.testAudioVideoEntry(Module_JournalEntryTest.java:182) +02-07 09:40:23.149: WARN/System.err(1209): at java.lang.reflect.Method.invokeNative(Native Method) +02-07 09:40:23.149: WARN/System.err(1209): at java.lang.reflect.Method.invoke(Method.java:507) +02-07 09:40:23.159: WARN/System.err(1209): at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204) +02-07 09:40:23.159: WARN/System.err(1209): at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194) +02-07 09:40:23.159: WARN/System.err(1209): at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186) +02-07 09:40:23.159: WARN/System.err(1209): at junit.framework.TestCase.runBare(TestCase.java:127) +02-07 09:40:23.169: WARN/System.err(1209): at junit.framework.TestResult$1.protect(TestResult.java:106) +02-07 09:40:23.169: WARN/System.err(1209): at junit.framework.TestResult.runProtected(TestResult.java:124) +02-07 09:40:23.169: WARN/System.err(1209): at junit.framework.TestResult.run(TestResult.java:109) +02-07 09:40:23.179: WARN/System.err(1209): at junit.framework.TestCase.run(TestCase.java:118) +02-07 09:40:23.179: WARN/System.err(1209): at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169) +02-07 09:40:23.179: WARN/System.err(1209): at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154) +02-07 09:40:23.179: WARN/System.err(1209): at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529) +02-07 09:40:23.189: WARN/System.err(1209): at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447) +02-07 09:40:23.189: ERROR/MediaPlayer(1209): prepareAsync called in state 0 +02-07 09:40:23.189: WARN/System.err(1209): java.lang.IllegalStateException +02-07 09:40:23.189: WARN/System.err(1209): at android.media.MediaPlayer.prepare(Native Method) +02-07 09:40:23.189: WARN/System.err(1209): at module.jakway.JournalEntry.AudioVideoEntry.prepareMedia(AudioVideoEntry.java:79) +02-07 09:40:23.199: WARN/System.err(1209): at module.jakway.JournalEntry.test.Module_JournalEntryTest.testAudioVideoEntry(Module_JournalEntryTest.java:197) +02-07 09:40:23.199: WARN/System.err(1209): at java.lang.reflect.Method.invokeNative(Native Method) +02-07 09:40:23.199: WARN/System.err(1209): at java.lang.reflect.Method.invoke(Method.java:507) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestCase.runBare(TestCase.java:127) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestResult$1.protect(TestResult.java:106) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestResult.runProtected(TestResult.java:124) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestResult.run(TestResult.java:109) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestCase.run(TestCase.java:118) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529) +02-07 09:40:23.199: WARN/System.err(1209): at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447) +02-07 09:40:23.199: ERROR/MediaPlayer(1209): start called in state 0 +02-07 09:40:23.199: ERROR/MediaPlayer(1209): error (-38, 0) + +``` + +Edit: why is MediaPlayer failing? + +thanks! +dragonwrenn",2011/02/07,"['https://Stackoverflow.com/questions/4924600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/450153/']","The second call to MediaPlayer.prepare() (already called once in the AudioVideoEntry ctor) in the AudioVideoEntry.prepareMedia() method was easy to spot as other people have noticed. + +The harder error to find was the first error. + +I used an Ogg file for testing. + +First clue was from davidsparks reply (last one) in [android-platform - Ogg on G1](http://groups.google.com/group/android-platform/browse_thread/thread/73ee9bfcf311763b) + +> +> As long as the files have a .ogg extension, they should play with the +> built-in music player. We rely on the file extensions because there is +> no centralized file recognizer for the media scanner. +> +> +> + +Second clue was from [[android-developers] Re: File permission about MediaPlayer](http://www.mail-archive.com/android-developers@googlegroups.com/msg12519.html) + +> +> Due to the Android security model, MediaPlayer does not have root +> access rights. It can access the sdcard, but it can't access private +> app directories. +> +> +> Your app can explicitly grant MediaPlayer temporary access to secure +> files by opening the file and passing the file descriptor to +> MediaPlayer using the setDataSource(FileDescriptor fd) method. +> +> +> + +If you look at the absolute path of the output stream, you see it's in the `/data/data` directory under the app's package name's directory. + +Excuse the timestamps - I worked backwards to get data to show on a OS2.1update1 (API7) emulator. + +Your code had: + +``` +String ave_file_name = ""my_media_content""; + +ave_fos = activity.openFileOutput(ave_file_name, Context.MODE_PRIVATE); + +``` + +DDMS showed: + +``` +02-10 05:10:28.253: WARN/MediaPlayer(1992): info/warning (1, 26) +02-10 05:10:28.253: ERROR/PlayerDriver(31): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported +02-10 05:10:28.253: ERROR/MediaPlayer(1992): error (1, -4) +02-10 05:10:28.274: WARN/PlayerDriver(31): PVMFInfoErrorHandlingComplete + +``` + +If we change **JUST** the file to MODE\_WORLD\_READABLE: + +``` +String ave_file_name = ""my_media_content""; + +ave_fos = activity.openFileOutput(ave_file_name, Context.MODE_WORLD_READABLE); + +``` + +DDMS shows no improvement: + +``` +02-10 05:08:28.543: WARN/MediaPlayer(1900): info/warning (1, 26) +02-10 05:08:28.553: ERROR/PlayerDriver(31): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported +02-10 05:08:28.553: ERROR/MediaPlayer(1900): error (1, -4) +02-10 05:08:28.563: WARN/PlayerDriver(31): PVMFInfoErrorHandlingComplete + +``` + +If we change **JUST** the file extension to `ogg`: + +``` +String ave_file_name = ""my_media_content.ogg""; + +ave_fos = activity.openFileOutput(ave_file_name, Context.MODE_PRIVATE); + +``` + +We get a change in DDMS output: + +``` +02-10 04:59:30.153: ERROR/MediaPlayerService(31): error: -2 +02-10 04:59:30.163: ERROR/MediaPlayer(1603): Unable to to create media player + +``` + +But when we **combine the two**: + +``` +String ave_file_name = ""my_media_content.ogg""; + +ave_fos = activity.openFileOutput(ave_file_name, Context.MODE_WORLD_READABLE); + +``` + +DDMS shows no errors.","It seems you are calling `prepare()` twice, first in the constructor of `AudioVideoEntry`, and second in the method `prepareMedia()`, that's why it's giving an `IllegalStateException`. + +If you read carefully the [documentation](http://developer.android.com/reference/android/media/MediaPlayer.html) you can understand the State Diagram and why gives such exceptions." +4924600,"I need to get the full path to a file somewhere on the phone (any location) and play it with MediaPlayer. + +ive heard of using a file chooser for Android (by launching an intent). + +In the test code, I just copied a resource to a another file, got the path and passed it to AudioVideoEntry (as i show later, a very simple and thin wrapper around MediaPlayer) + +Here's the test code I've written: + +``` +private String ave_path; + private String ave_file_name = ""my_media_content""; + private InputStream ave_fis; + private OutputStream ave_fos; + public void testAudioVideoEntry() + { + //get the Activity + Module_JournalEntry journalentryactivity = getActivity(); + //open an InputStream to a resource file (in this case strokes.mp3) + ave_fis = journalentryactivity.getResources().openRawResource(module.jakway.JournalEntry.R.raw.strokes); + + //open an OutputStream to a new file + try { + ave_fos = journalentryactivity.openFileOutput(ave_file_name, + Context.MODE_PRIVATE); + } catch (FileNotFoundException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + assertTrue(false); + } + catch(Exception e) + { + assertTrue(false); + } + + //copy the data from the resource into + //the OutputStream + int data; + try { + while((data = ave_fis.read()) != -1) + { + ave_fos.write(data); + } + assertTrue(true); + } + catch(Exception e) + { + assertTrue(false); + } + + //get the full path of the file we wrote to + ave_path = journalentryactivity.getFileStreamPath(ave_file_name).toString(); + + //and construct a new object of AudioVideoEntry with that path + AudioVideoEntry ave = new AudioVideoEntry(ave_path); + + //register an error listener via MediaPlayer's setOnErrorListener + ave.setOnErrorListener(new OnErrorListener() + { + @Override + public boolean onError(MediaPlayer mp, + int what, int extra) { + Log.e(""MEDIAPLAYER ERRORS"", + ""what: "" + what + "" extra: "" + extra); + assertTrue(false); + // TODO Auto-generated method stub + return false; + } + }); + ave.prepareMedia(); + ave.playMedia(); + try { + ave_fis.close(); + ave_fos.close(); + } + catch(Exception e) + { + assertTrue(false); + e.printStackTrace(); + } + +``` + +AudioVideoEntry is basically a thin wrapper around MediaPlayer that can hold its own path: + +``` +public class AudioVideoEntry +{ + private String path_to_audio_file; + private MediaPlayer mediaplayer; + + /** + * Initialize the internal MediaPlayer + * from the String parameter + * @param set_path_to_audio_file + */ + public AudioVideoEntry(String set_path_to_audio_file) + { + path_to_audio_file = set_path_to_audio_file; + mediaplayer = new MediaPlayer(); + try { + mediaplayer.setDataSource(path_to_audio_file); + mediaplayer.prepare(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public AudioVideoEntry(FileDescriptor fd) + { + + mediaplayer = new MediaPlayer(); + try { + mediaplayer.setDataSource(fd); + mediaplayer.prepare(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * Begin playing media + */ + public void prepareMedia() + { + try { + mediaplayer.prepare(); + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * play media + * don't forget to prepare() if necessary + */ + public void playMedia() + { + mediaplayer.start(); + } + + /** + * pause the media + * can be played later + */ + public void pauseMedia() + { + mediaplayer.pause(); + } + + /** + * stop media + */ + public void stopMedia() + { + mediaplayer.stop(); + } + + public void setOnErrorListener(OnErrorListener listener) + { + mediaplayer.setOnErrorListener(listener); + } +} + +``` + +here's the logcat output from the JUnit test (the tests were successful, the actual results - as the logat shows - were not) + +``` +02-07 09:40:23.129: ERROR/MediaPlayer(1209): error (1, -2147483648) +02-07 09:40:23.139: WARN/System.err(1209): java.io.IOException: Prepare failed.: status=0x1 +02-07 09:40:23.149: WARN/System.err(1209): at android.media.MediaPlayer.prepare(Native Method) +02-07 09:40:23.149: WARN/System.err(1209): at module.jakway.JournalEntry.AudioVideoEntry.(AudioVideoEntry.java:39) +02-07 09:40:23.149: WARN/System.err(1209): at module.jakway.JournalEntry.test.Module_JournalEntryTest.testAudioVideoEntry(Module_JournalEntryTest.java:182) +02-07 09:40:23.149: WARN/System.err(1209): at java.lang.reflect.Method.invokeNative(Native Method) +02-07 09:40:23.149: WARN/System.err(1209): at java.lang.reflect.Method.invoke(Method.java:507) +02-07 09:40:23.159: WARN/System.err(1209): at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204) +02-07 09:40:23.159: WARN/System.err(1209): at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194) +02-07 09:40:23.159: WARN/System.err(1209): at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186) +02-07 09:40:23.159: WARN/System.err(1209): at junit.framework.TestCase.runBare(TestCase.java:127) +02-07 09:40:23.169: WARN/System.err(1209): at junit.framework.TestResult$1.protect(TestResult.java:106) +02-07 09:40:23.169: WARN/System.err(1209): at junit.framework.TestResult.runProtected(TestResult.java:124) +02-07 09:40:23.169: WARN/System.err(1209): at junit.framework.TestResult.run(TestResult.java:109) +02-07 09:40:23.179: WARN/System.err(1209): at junit.framework.TestCase.run(TestCase.java:118) +02-07 09:40:23.179: WARN/System.err(1209): at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169) +02-07 09:40:23.179: WARN/System.err(1209): at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154) +02-07 09:40:23.179: WARN/System.err(1209): at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529) +02-07 09:40:23.189: WARN/System.err(1209): at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447) +02-07 09:40:23.189: ERROR/MediaPlayer(1209): prepareAsync called in state 0 +02-07 09:40:23.189: WARN/System.err(1209): java.lang.IllegalStateException +02-07 09:40:23.189: WARN/System.err(1209): at android.media.MediaPlayer.prepare(Native Method) +02-07 09:40:23.189: WARN/System.err(1209): at module.jakway.JournalEntry.AudioVideoEntry.prepareMedia(AudioVideoEntry.java:79) +02-07 09:40:23.199: WARN/System.err(1209): at module.jakway.JournalEntry.test.Module_JournalEntryTest.testAudioVideoEntry(Module_JournalEntryTest.java:197) +02-07 09:40:23.199: WARN/System.err(1209): at java.lang.reflect.Method.invokeNative(Native Method) +02-07 09:40:23.199: WARN/System.err(1209): at java.lang.reflect.Method.invoke(Method.java:507) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestCase.runBare(TestCase.java:127) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestResult$1.protect(TestResult.java:106) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestResult.runProtected(TestResult.java:124) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestResult.run(TestResult.java:109) +02-07 09:40:23.199: WARN/System.err(1209): at junit.framework.TestCase.run(TestCase.java:118) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154) +02-07 09:40:23.199: WARN/System.err(1209): at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529) +02-07 09:40:23.199: WARN/System.err(1209): at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447) +02-07 09:40:23.199: ERROR/MediaPlayer(1209): start called in state 0 +02-07 09:40:23.199: ERROR/MediaPlayer(1209): error (-38, 0) + +``` + +Edit: why is MediaPlayer failing? + +thanks! +dragonwrenn",2011/02/07,"['https://Stackoverflow.com/questions/4924600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/450153/']","The second call to MediaPlayer.prepare() (already called once in the AudioVideoEntry ctor) in the AudioVideoEntry.prepareMedia() method was easy to spot as other people have noticed. + +The harder error to find was the first error. + +I used an Ogg file for testing. + +First clue was from davidsparks reply (last one) in [android-platform - Ogg on G1](http://groups.google.com/group/android-platform/browse_thread/thread/73ee9bfcf311763b) + +> +> As long as the files have a .ogg extension, they should play with the +> built-in music player. We rely on the file extensions because there is +> no centralized file recognizer for the media scanner. +> +> +> + +Second clue was from [[android-developers] Re: File permission about MediaPlayer](http://www.mail-archive.com/android-developers@googlegroups.com/msg12519.html) + +> +> Due to the Android security model, MediaPlayer does not have root +> access rights. It can access the sdcard, but it can't access private +> app directories. +> +> +> Your app can explicitly grant MediaPlayer temporary access to secure +> files by opening the file and passing the file descriptor to +> MediaPlayer using the setDataSource(FileDescriptor fd) method. +> +> +> + +If you look at the absolute path of the output stream, you see it's in the `/data/data` directory under the app's package name's directory. + +Excuse the timestamps - I worked backwards to get data to show on a OS2.1update1 (API7) emulator. + +Your code had: + +``` +String ave_file_name = ""my_media_content""; + +ave_fos = activity.openFileOutput(ave_file_name, Context.MODE_PRIVATE); + +``` + +DDMS showed: + +``` +02-10 05:10:28.253: WARN/MediaPlayer(1992): info/warning (1, 26) +02-10 05:10:28.253: ERROR/PlayerDriver(31): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported +02-10 05:10:28.253: ERROR/MediaPlayer(1992): error (1, -4) +02-10 05:10:28.274: WARN/PlayerDriver(31): PVMFInfoErrorHandlingComplete + +``` + +If we change **JUST** the file to MODE\_WORLD\_READABLE: + +``` +String ave_file_name = ""my_media_content""; + +ave_fos = activity.openFileOutput(ave_file_name, Context.MODE_WORLD_READABLE); + +``` + +DDMS shows no improvement: + +``` +02-10 05:08:28.543: WARN/MediaPlayer(1900): info/warning (1, 26) +02-10 05:08:28.553: ERROR/PlayerDriver(31): Command PLAYER_SET_DATA_SOURCE completed with an error or info PVMFErrNotSupported +02-10 05:08:28.553: ERROR/MediaPlayer(1900): error (1, -4) +02-10 05:08:28.563: WARN/PlayerDriver(31): PVMFInfoErrorHandlingComplete + +``` + +If we change **JUST** the file extension to `ogg`: + +``` +String ave_file_name = ""my_media_content.ogg""; + +ave_fos = activity.openFileOutput(ave_file_name, Context.MODE_PRIVATE); + +``` + +We get a change in DDMS output: + +``` +02-10 04:59:30.153: ERROR/MediaPlayerService(31): error: -2 +02-10 04:59:30.163: ERROR/MediaPlayer(1603): Unable to to create media player + +``` + +But when we **combine the two**: + +``` +String ave_file_name = ""my_media_content.ogg""; + +ave_fos = activity.openFileOutput(ave_file_name, Context.MODE_WORLD_READABLE); + +``` + +DDMS shows no errors.","Some points: + +1. Do not call `prepare()` twice (once in the constructor and the other explicitly). That could be one of the reasons that the `IllegalStateException` is thrown. +2. Also, is the file that you are trying to play inside the application? If so, why are you trying to create a stream? If the file is already within the application (and within `/res/raw`, you could try and save yourself the hassle of using `prepare()` by creating the mediaplayer object like so: + +mediaplayer = new MediaPlayer.create(this, R.raw.resource-name here); + +The create function calls `prepare()` within. + +3. You can also try and use the `reset()` function if any one of the stages in the MediaPlayer fails resulting in the MediaPlayer object entering the error state. Using `reset()` would bring it back to Idle state. + +4. The last time I had that error `status=0x1` message, it turned out that I had not had the correct permissions set for the files (external storage etc. in Manifest) and some files placed in incorrect folders. You may also want to take a look at that. + +Let me know in case that does not work, + +We can try something else. + +Sriram." +26163209,"I'm processing a data.frame of products called ""`all`"" whose first variable `all$V1` is a product family. There are several rows per product family, i.e. `length(levels(all$V1))` < `length(all$V1)`. + +I want to traverse the data.frame and process by product family ""`p`"". I'm new to R, so I haven't fully grasped when I can do something vectorially, or when to loop. At the moment, I can traverse and get subsets by: + +``` +for (i in levels (all$V1)){ + p = all[which(all[,'V1'] == i), ]; + calculateStuff(p); +} + +``` + +Is this the way to do this, or is there a groovy vectorial way of doing this with `apply` or something? There are only a few thousand rows, so performance gain is probably negligeable, but I'd like to devlop good habits for larger data ses.",2014/10/02,"['https://Stackoverflow.com/questions/26163209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3790954/']","Data: + +``` +all = data.frame(V1=c(""a"",""b"",""c"",""d"",""d"",""c"",""c"",""b"",""a"",""a"",""a"",""d"")) + +``` + +'all' can be split by V1: + +``` +> ll = split(all, all$V1) +> ll +$a + V1 +1 a +9 a +10 a +11 a + +$b + V1 +2 b +8 b + +$c + V1 +3 c +6 c +7 c + +$d + V1 +4 d +5 d +12 d + +``` + +sapply can be used to analyze each component of list 'll'. Following finds number of rows in each component (which represents product family): + +``` +calculateStuff <- function(p){ + nrow(p) +} + +> sapply(ll, calculateStuff) +a b c d +4 2 3 3 + +```","There is unlikely to be much of a performance gain with the below, but it is at least more compact and returns the results of `calculateStuff` as a convenient list: + +``` +lapply(levels(all$V1), function(i) calculateStuff(all[all$V1 == i, ]) ) + +``` + +As @SimonG points out in his comment, depending on exactly what your `calculateStuff` function is, `aggregate` may also be useful to you if you want your results in the form of dataframe." +6507359,"[As I have seen here](https://stackoverflow.com/questions/3680429/click-through-a-div-to-underlying-elements/4839672#4839672), a filter can be used to simulate a cross browser version of + +```css +pointer-events: none; + +``` + +However, this just doesn't work in IE9, nor does it in the ""emulate IE8"" version in IE9. A native installation of IE8 handles it fine, however. Is there any solution that makes it work for IE9?",2011/06/28,"['https://Stackoverflow.com/questions/6507359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775265/']","You're right - AlphaImageLoader filter has been removed from IE9. This was done so that it doesn't conflict with the standards compliant methods. In this case, `pointer-events: none`, which [now works in IE9](http://msdn.microsoft.com/en-us/library/ff972269%28v=vs.85%29.aspx). + +If you're using a conditional comments to target IE for the filter fix, change them to target only IE8 and below. Try changing ` + +``` + +Apologies for the misinformation, I'll keep looking into this. + +**Update Sept 24 2012:** + +The wonderfully useful [caniuse.com](http://caniuse.com/pointer-events) has more information on `pointer-events` for HTML. Support in IE10 is still unknown and it appears that Opera does not support this property either. I would advise against using `pointer-events` for now unless you're specifically targeting Webkit/Mozilla.","pointer-events only works in webkit, mozilla browsers in html. + +However pointer-events works on svg elements in internet explorer. + +There is a good modernizr plugin to test the existence of pointer-events + +If you are using the pointer events to just add some sort of texture over the top you can replace a div with a svg element + +``` +if( !Modernizr.pointerevents ) +{ + $('#texture').replaceWith(''); +} + +```" +26801957,"I am trying to create a mini accounts application that captures and stores the first name, last name, student number and grade of students through textboxes and then stores it to a comma delimited text file. The problem is that it re-writes the input every time I hit the save file. Any help would be appreciated. Here is the code I am using: + +``` +Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click + + Dim fName, lName, sNum As String + Dim grade As Decimal + + fName = txtFName.Text + lName = txtLName.Text + sNum = txtSNum.Text + grade = txtGrade.Text + + Try + + Dim write As StreamWriter + write = New StreamWriter(""hello.txt"") + write.WriteLine(String.Format(""{0},{1},{2},{3}"", fName, lName, sNum, grade)) + write.Close() + + Catch ex As Exception + + MessageBox.Show(ex.Message) + + End Try + +End Sub + +```",2014/11/07,"['https://Stackoverflow.com/questions/26801957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4227012/']","On report right click and Properties > +More under the Properties > Add this parameters; + +**net.sf.jasperreports.export.xls.ignore.graphics = false** + +and on Jasper Server : + +jasperreports-server-cp-5.0.0/apache-tomcat/webapps/jasperserver/WEB-INF/classes/jasperreports.properties + +add this parameter; + +**net.sf.jasperreports.export.xls.ignore.graphics = false**","1 - You can using a simply URL File Path. Create one image component. + +2 - You can active ""Markup"" for show HTML interpreted. + +3 - You can use itext API, to generate PDF using HTML code. + +maybe exists another options." +65772928,"I have a meta reducer that should clear the state when logging out. + +``` +export function clearState(reducer: ActionReducer): ActionReducer { + return (state, action) => { + if (action.type === AuthActionTypes.UNAUTHENTICATED) { + state = undefined; + } + return reducer(state, action); + }; +} + +export const metaReducers: MetaReducer[] = [clearState]; + +``` + +I want to unit test this piece of code. I have tested normal reducers before but for me it is hard to apply the same technique when writing a test for the meta reducer. And there are no examples in the docs.",2021/01/18,"['https://Stackoverflow.com/questions/65772928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4956266/']","I figured out a way to test it after digging deep in the ngrx source code + +``` +const invokeActionReducer = (currentState, action: any) => { + return clearState((state) => state)(currentState, action); +}; + +it('should set state to initial value when logout action is dispatched', () => { + const currentState = { /* state here */ }; + + expect(invokeActionReducer(currentState, userUnauthenticated)).toBeFalsy(); +}); + +``` + +[Source](https://github.com/ngrx/platform/tree/master/modules/store/spec/meta-reducers)","This might not be all of it but something like this should work: + +``` +let store: Store; +.... +store = TestBed.inject(Store); // TestBed.inject is TestBed.get in older versions of Angular +TestBed.configureTEstingModule({ + imports: [StoreModule.forRoot(/* put your reducers here */, { metaReducers })], +}); + +it('should re-initialize the state once unauthenticated is dispatched', async () => { + store.dispatch(/* dispatch an action that will change the store */); + const newPieceOfState = await this.store.select(state => ...).pipe(take(1)).toPromise(); // ensure the change took place + expect(newPieceOfState).toEqual(...); + store.dispatch(/* dispatch UNAUTHENTICATED */); + const state = await this.store.select(state => ....).pipe(take(1)).toPromise(); + expect(state).toEqual(...); // do your assertions that the meta reducer took effect and the state changed +}); + +```" +39487308,"I want to backup configuration of job, I am using to do this ThinBackup plugin in version 1.7.4 . And in every configuration of the job, there is something like `Promote builds when..`, how to backup this?",2016/09/14,"['https://Stackoverflow.com/questions/39487308', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5612084/']","I ran into same issue and found this is an [open bug](https://issues.jenkins-ci.org/browse/JENKINS-21472). Looks to have a fix but a new version of the plugin hasn't been released. + +A workaround which seems to work OK so far, is to separately backup the `config.xml` files under the `JENKINS_HOME/jobs/`. On Linux I ran the below from the Jenkins home directory to create this additional backup: + +``` + $ find jobs -name config.xml -exec tar -rzvf /tmp/config.xml-BACKUP.tgz {} \; + +``` + +So I'm still using ThinBackup to get all the other bits but after restoring its backup: + +``` +tar -xzf /tmp/config.xml-BACKUP.tgz + +``` + +I then restored the jobs `config.xml` backup and restarted Jenkins.","They are a some options with the ThinBackup plugin: + +[![enter image description here](https://i.stack.imgur.com/KlCz9.png)](https://i.stack.imgur.com/KlCz9.png) + +Did you try to enable the ""Backup build archive"" option?" +3604,"Still with software science translations.. Now I'm coming to you with this expression that have always bothered me: ""on the fly"" + +How the hood would you translate that *elegantly* to spanish? + +It feels like ""sobre la marcha"" is way overkill, at least from a structure point of view. Also ""al toque"", sounds maybe too coloquial. + +What do you think? + +edit: so the english sentence could be: + +> +> The value is returned from a new function executed on the fly. +> +> +>",2013/04/24,"['https://spanish.stackexchange.com/questions/3604', 'https://spanish.stackexchange.com', 'https://spanish.stackexchange.com/users/831/']","I would generally use *sobre la marcha* and I don't see it as overkill. + +What does this phrase have to do with Scientific translations? Maybe a few examples would help.","I'm from Latin America and ""al toque"" doesn't mean exactly ""on the fly"", the correct translation would be ""sobre la marcha"". + +""Al toque"" it's more like a ""immediately after""." +3604,"Still with software science translations.. Now I'm coming to you with this expression that have always bothered me: ""on the fly"" + +How the hood would you translate that *elegantly* to spanish? + +It feels like ""sobre la marcha"" is way overkill, at least from a structure point of view. Also ""al toque"", sounds maybe too coloquial. + +What do you think? + +edit: so the english sentence could be: + +> +> The value is returned from a new function executed on the fly. +> +> +>",2013/04/24,"['https://spanish.stackexchange.com/questions/3604', 'https://spanish.stackexchange.com', 'https://spanish.stackexchange.com/users/831/']","No, I don’t like very much `sobre la marcha`. I mean, not always, and in “*software science translations*” almost never. I don’t feel it translate the whole idea exactly, with sometimes is: immediately and automatically, without user’s or external elements intervention. + +There are many other possibilities. + +My favorite is the simple direct translation: “`al vuelo`”. + +Let’s see what the RAE said about “vuelo”: + +> +> al ~, o a ~. +> +> +> 1. locs. advs. Con prontitud. +> +> +> cazarlas alguien al ~. +> +> +> 1. loc. verb. Entender o notar con prontitud las cosas que no se dicen claramente o que se hacen ocultamente. +> +> +> coger al ~ algo. +> +> +> 1. loc. verb. Lograrlo de paso o casualmente. +> +> +> cogerlas alguien al ~. +> +> +> 1. loc. verb. coloq. cazarlas al vuelo. +> +> +> alzar el ~. +> +> +> 1. loc. verb. Echar a volar. +> 2. loc. verb. coloq. Marcharse de repente. +> +> +> + +I like this more than “`sobre la marcha`”, with the bonus that many people will automatically translate it to `on the fly` with the exact original meaning. + +Some of the other possibilities are: + +“sobre la marcha” (of course), + +inmediátamente, + +automáticamente, + +dinámicamente (this is probably my second favorite). *The windows layout change on the fly.* **El diseno de la pantalla cambia dinámicamente.** (a sort of this) + +simultáneamente + +Let’s see some concrete examples: + +[I have a class which calculates it's property on-the-fly, for example:](https://stackoverflow.com/q/15744634/1458030) + +Tengo una clase que calcula sus propiedades al vuelo. (dinámicamente, en tiempo real)(I’m not sure how to correctly translate `class` and `properties`) + +[An example enlightens the kerning-on-the-fly functionality:](https://stackoverflow.com/q/12654826/1458030) + +Un ejemplo aclara esta funcionalidad de posicionamiento al vuelo. (dinámico, instantaneo, sobre la marcha) + +[Encryption on the fly.](https://stackoverflow.com/q/16215990/1458030) +Cifrado al vuelo. Cifrado simultaneo, en tiempo real, dinámico, automático… + +On the fly translation. +Traduccion simultanuea. (al vuelo, instantanea, sobre la marcha) + +[More examples are here.](http://www.linguee.com/english-spanish?query=on%20the%20fly&source=english)","I would generally use *sobre la marcha* and I don't see it as overkill. + +What does this phrase have to do with Scientific translations? Maybe a few examples would help." +3604,"Still with software science translations.. Now I'm coming to you with this expression that have always bothered me: ""on the fly"" + +How the hood would you translate that *elegantly* to spanish? + +It feels like ""sobre la marcha"" is way overkill, at least from a structure point of view. Also ""al toque"", sounds maybe too coloquial. + +What do you think? + +edit: so the english sentence could be: + +> +> The value is returned from a new function executed on the fly. +> +> +>",2013/04/24,"['https://spanish.stackexchange.com/questions/3604', 'https://spanish.stackexchange.com', 'https://spanish.stackexchange.com/users/831/']","""Al toque"" sounds to me like Latin America spanish... in Spain, al least in Madrid, we don't use that expression. + +""On the fly"" can be translated in several forms, but ""sobre la marcha"" I think is the most accurate. Other forms can be ""al momento"", ""instantáneo"" or ""conforme se vea"". Depends from context, but I think ""sobre la marcha"" is the most elegant, formal and easy. + +Some examples: + +> +> We will fix the errors on the fly. - Iremos corrigiendo los errores +> *sobre la marcha* / *conforme los veamos*. +> +> +> The system enables 'on-the-fly' processing of queries. - El sistema +> permite el procesamiento *instantáneo* de consultas. +> +> +>","I'm from Latin America and ""al toque"" doesn't mean exactly ""on the fly"", the correct translation would be ""sobre la marcha"". + +""Al toque"" it's more like a ""immediately after""." +3604,"Still with software science translations.. Now I'm coming to you with this expression that have always bothered me: ""on the fly"" + +How the hood would you translate that *elegantly* to spanish? + +It feels like ""sobre la marcha"" is way overkill, at least from a structure point of view. Also ""al toque"", sounds maybe too coloquial. + +What do you think? + +edit: so the english sentence could be: + +> +> The value is returned from a new function executed on the fly. +> +> +>",2013/04/24,"['https://spanish.stackexchange.com/questions/3604', 'https://spanish.stackexchange.com', 'https://spanish.stackexchange.com/users/831/']","No, I don’t like very much `sobre la marcha`. I mean, not always, and in “*software science translations*” almost never. I don’t feel it translate the whole idea exactly, with sometimes is: immediately and automatically, without user’s or external elements intervention. + +There are many other possibilities. + +My favorite is the simple direct translation: “`al vuelo`”. + +Let’s see what the RAE said about “vuelo”: + +> +> al ~, o a ~. +> +> +> 1. locs. advs. Con prontitud. +> +> +> cazarlas alguien al ~. +> +> +> 1. loc. verb. Entender o notar con prontitud las cosas que no se dicen claramente o que se hacen ocultamente. +> +> +> coger al ~ algo. +> +> +> 1. loc. verb. Lograrlo de paso o casualmente. +> +> +> cogerlas alguien al ~. +> +> +> 1. loc. verb. coloq. cazarlas al vuelo. +> +> +> alzar el ~. +> +> +> 1. loc. verb. Echar a volar. +> 2. loc. verb. coloq. Marcharse de repente. +> +> +> + +I like this more than “`sobre la marcha`”, with the bonus that many people will automatically translate it to `on the fly` with the exact original meaning. + +Some of the other possibilities are: + +“sobre la marcha” (of course), + +inmediátamente, + +automáticamente, + +dinámicamente (this is probably my second favorite). *The windows layout change on the fly.* **El diseno de la pantalla cambia dinámicamente.** (a sort of this) + +simultáneamente + +Let’s see some concrete examples: + +[I have a class which calculates it's property on-the-fly, for example:](https://stackoverflow.com/q/15744634/1458030) + +Tengo una clase que calcula sus propiedades al vuelo. (dinámicamente, en tiempo real)(I’m not sure how to correctly translate `class` and `properties`) + +[An example enlightens the kerning-on-the-fly functionality:](https://stackoverflow.com/q/12654826/1458030) + +Un ejemplo aclara esta funcionalidad de posicionamiento al vuelo. (dinámico, instantaneo, sobre la marcha) + +[Encryption on the fly.](https://stackoverflow.com/q/16215990/1458030) +Cifrado al vuelo. Cifrado simultaneo, en tiempo real, dinámico, automático… + +On the fly translation. +Traduccion simultanuea. (al vuelo, instantanea, sobre la marcha) + +[More examples are here.](http://www.linguee.com/english-spanish?query=on%20the%20fly&source=english)","""Al toque"" sounds to me like Latin America spanish... in Spain, al least in Madrid, we don't use that expression. + +""On the fly"" can be translated in several forms, but ""sobre la marcha"" I think is the most accurate. Other forms can be ""al momento"", ""instantáneo"" or ""conforme se vea"". Depends from context, but I think ""sobre la marcha"" is the most elegant, formal and easy. + +Some examples: + +> +> We will fix the errors on the fly. - Iremos corrigiendo los errores +> *sobre la marcha* / *conforme los veamos*. +> +> +> The system enables 'on-the-fly' processing of queries. - El sistema +> permite el procesamiento *instantáneo* de consultas. +> +> +>" +3604,"Still with software science translations.. Now I'm coming to you with this expression that have always bothered me: ""on the fly"" + +How the hood would you translate that *elegantly* to spanish? + +It feels like ""sobre la marcha"" is way overkill, at least from a structure point of view. Also ""al toque"", sounds maybe too coloquial. + +What do you think? + +edit: so the english sentence could be: + +> +> The value is returned from a new function executed on the fly. +> +> +>",2013/04/24,"['https://spanish.stackexchange.com/questions/3604', 'https://spanish.stackexchange.com', 'https://spanish.stackexchange.com/users/831/']","No, I don’t like very much `sobre la marcha`. I mean, not always, and in “*software science translations*” almost never. I don’t feel it translate the whole idea exactly, with sometimes is: immediately and automatically, without user’s or external elements intervention. + +There are many other possibilities. + +My favorite is the simple direct translation: “`al vuelo`”. + +Let’s see what the RAE said about “vuelo”: + +> +> al ~, o a ~. +> +> +> 1. locs. advs. Con prontitud. +> +> +> cazarlas alguien al ~. +> +> +> 1. loc. verb. Entender o notar con prontitud las cosas que no se dicen claramente o que se hacen ocultamente. +> +> +> coger al ~ algo. +> +> +> 1. loc. verb. Lograrlo de paso o casualmente. +> +> +> cogerlas alguien al ~. +> +> +> 1. loc. verb. coloq. cazarlas al vuelo. +> +> +> alzar el ~. +> +> +> 1. loc. verb. Echar a volar. +> 2. loc. verb. coloq. Marcharse de repente. +> +> +> + +I like this more than “`sobre la marcha`”, with the bonus that many people will automatically translate it to `on the fly` with the exact original meaning. + +Some of the other possibilities are: + +“sobre la marcha” (of course), + +inmediátamente, + +automáticamente, + +dinámicamente (this is probably my second favorite). *The windows layout change on the fly.* **El diseno de la pantalla cambia dinámicamente.** (a sort of this) + +simultáneamente + +Let’s see some concrete examples: + +[I have a class which calculates it's property on-the-fly, for example:](https://stackoverflow.com/q/15744634/1458030) + +Tengo una clase que calcula sus propiedades al vuelo. (dinámicamente, en tiempo real)(I’m not sure how to correctly translate `class` and `properties`) + +[An example enlightens the kerning-on-the-fly functionality:](https://stackoverflow.com/q/12654826/1458030) + +Un ejemplo aclara esta funcionalidad de posicionamiento al vuelo. (dinámico, instantaneo, sobre la marcha) + +[Encryption on the fly.](https://stackoverflow.com/q/16215990/1458030) +Cifrado al vuelo. Cifrado simultaneo, en tiempo real, dinámico, automático… + +On the fly translation. +Traduccion simultanuea. (al vuelo, instantanea, sobre la marcha) + +[More examples are here.](http://www.linguee.com/english-spanish?query=on%20the%20fly&source=english)","I'm from Latin America and ""al toque"" doesn't mean exactly ""on the fly"", the correct translation would be ""sobre la marcha"". + +""Al toque"" it's more like a ""immediately after""." +19673842,"I'm a Beginner in android development. I'm using Google Maps API V2 in my Application. I want to show the street name, postcode/zip-code, city automatically of the current location. Currently I'm just displaying the longitude and latitude of the current location but don't know how to get this information as well. Can Anyone please tell me the right way, that how can I get these information(street name, postcode/zipcode, city) from the maps api v2..",2013/10/30,"['https://Stackoverflow.com/questions/19673842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2933576/']","As per your question + +**`How to fetch all DIVs that have some specific css rules (e.g. their color are red)?`** + +``` +$.each($('*'), function () { + if ($(this).css('color') == 'rgb(255, 0, 0)') { + alert($(this).text()); + } + }); + +This will get all elements with color Red + +``` + +[**Live Demo**](http://jsfiddle.net/jpGER/3/) + +**Addition** + +As **`*`** will be selecting all the elements in Dom, we can narrow down our search by specifying the type of elements we are looking for. for example here we have `div` elements only so we can use + +``` +$.each($('div'), function () { + if ($(this).css('color') == 'rgb(255, 0, 0)') { + alert($(this).text()); + } + }); + +```","Try this: + +``` +$(""body"").find(""div:hidden"") + +```" +19673842,"I'm a Beginner in android development. I'm using Google Maps API V2 in my Application. I want to show the street name, postcode/zip-code, city automatically of the current location. Currently I'm just displaying the longitude and latitude of the current location but don't know how to get this information as well. Can Anyone please tell me the right way, that how can I get these information(street name, postcode/zipcode, city) from the maps api v2..",2013/10/30,"['https://Stackoverflow.com/questions/19673842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2933576/']","As per your question + +**`How to fetch all DIVs that have some specific css rules (e.g. their color are red)?`** + +``` +$.each($('*'), function () { + if ($(this).css('color') == 'rgb(255, 0, 0)') { + alert($(this).text()); + } + }); + +This will get all elements with color Red + +``` + +[**Live Demo**](http://jsfiddle.net/jpGER/3/) + +**Addition** + +As **`*`** will be selecting all the elements in Dom, we can narrow down our search by specifying the type of elements we are looking for. for example here we have `div` elements only so we can use + +``` +$.each($('div'), function () { + if ($(this).css('color') == 'rgb(255, 0, 0)') { + alert($(this).text()); + } + }); + +```","Try this + +``` +$(""div[style*=display:block]"") + +```" +19673842,"I'm a Beginner in android development. I'm using Google Maps API V2 in my Application. I want to show the street name, postcode/zip-code, city automatically of the current location. Currently I'm just displaying the longitude and latitude of the current location but don't know how to get this information as well. Can Anyone please tell me the right way, that how can I get these information(street name, postcode/zipcode, city) from the maps api v2..",2013/10/30,"['https://Stackoverflow.com/questions/19673842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2933576/']","As per your question + +**`How to fetch all DIVs that have some specific css rules (e.g. their color are red)?`** + +``` +$.each($('*'), function () { + if ($(this).css('color') == 'rgb(255, 0, 0)') { + alert($(this).text()); + } + }); + +This will get all elements with color Red + +``` + +[**Live Demo**](http://jsfiddle.net/jpGER/3/) + +**Addition** + +As **`*`** will be selecting all the elements in Dom, we can narrow down our search by specifying the type of elements we are looking for. for example here we have `div` elements only so we can use + +``` +$.each($('div'), function () { + if ($(this).css('color') == 'rgb(255, 0, 0)') { + alert($(this).text()); + } + }); + +```","You could try using [attribute selectors](http://www.w3.org/TR/css3-selectors/#attribute-selectors). + +``` +document.querySelectorAll('[style=""display: none""]') + +``` + +but that would require that your `style` attributes are consistently formatted... + +If you are looking to get *all* elements that have a certain css property (not just in the `style=` attribute), you may have to do it manually, by looking through the [document stylesheets](https://developer.mozilla.org/en-US/docs/Web/API/document.styleSheets)." +19673842,"I'm a Beginner in android development. I'm using Google Maps API V2 in my Application. I want to show the street name, postcode/zip-code, city automatically of the current location. Currently I'm just displaying the longitude and latitude of the current location but don't know how to get this information as well. Can Anyone please tell me the right way, that how can I get these information(street name, postcode/zipcode, city) from the maps api v2..",2013/10/30,"['https://Stackoverflow.com/questions/19673842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2933576/']","As per your question + +**`How to fetch all DIVs that have some specific css rules (e.g. their color are red)?`** + +``` +$.each($('*'), function () { + if ($(this).css('color') == 'rgb(255, 0, 0)') { + alert($(this).text()); + } + }); + +This will get all elements with color Red + +``` + +[**Live Demo**](http://jsfiddle.net/jpGER/3/) + +**Addition** + +As **`*`** will be selecting all the elements in Dom, we can narrow down our search by specifying the type of elements we are looking for. for example here we have `div` elements only so we can use + +``` +$.each($('div'), function () { + if ($(this).css('color') == 'rgb(255, 0, 0)') { + alert($(this).text()); + } + }); + +```","You might not be able to depend upon [:hidden](http://api.jquery.com/hidden-selector/) because it selects + +* They have a CSS display value of none. +* They are form elements with type=""hidden"". +* Their width and height are explicitly set to 0. +* An ancestor element is hidden, so the element is not shown on the page. + +So try + +``` +$('div').filter(function () { + return $(this).css('display') == 'none'; +}).doSomething() + +```" +6123544,"In header files I've seen two main ways for defining macro to avoid including the file more than once. + +1. + +``` +#ifndef SOME_CLASS +#define SOME_CLASS +//code ... +#endif + +``` + +2. + +``` +#ifndef SOME_CLASS +//code... +#define SOME_CLASS +#endif + +``` + +Which is more preferable and why?",2011/05/25,"['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']","I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.","I'd go for the first one. + +Reason: If you ever want to change the guard name (say, `SOME_CLASS` to `SOMECLASS`), you don't have to scroll all the way down to the end of file to change it too." +6123544,"In header files I've seen two main ways for defining macro to avoid including the file more than once. + +1. + +``` +#ifndef SOME_CLASS +#define SOME_CLASS +//code ... +#endif + +``` + +2. + +``` +#ifndef SOME_CLASS +//code... +#define SOME_CLASS +#endif + +``` + +Which is more preferable and why?",2011/05/25,"['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']","I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.",The best option is to use `#pragma once`. With `#define` you must be very careful when using multiple libraries as the guard name may not be unique. +6123544,"In header files I've seen two main ways for defining macro to avoid including the file more than once. + +1. + +``` +#ifndef SOME_CLASS +#define SOME_CLASS +//code ... +#endif + +``` + +2. + +``` +#ifndef SOME_CLASS +//code... +#define SOME_CLASS +#endif + +``` + +Which is more preferable and why?",2011/05/25,"['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']","I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.","I prefer the first option. Suppose you include more files, and these files in turn include the file containing `#ifndef SOME_CLASS`. + +I think it's fairly easy to spot include errors, if the `#define SOME_CLASS` isn't adjacent to `#ifndef SOME_CLASS`. + +``` +// SomeClass.h +#ifndef SOME_CLASS +#include ""OtherFile.h"" // will eventually lead to #include ""SomeClass.h"" +#define SOME_CLASS + +... boat load of code here... + +#endif // SOME_CLASS + +```" +6123544,"In header files I've seen two main ways for defining macro to avoid including the file more than once. + +1. + +``` +#ifndef SOME_CLASS +#define SOME_CLASS +//code ... +#endif + +``` + +2. + +``` +#ifndef SOME_CLASS +//code... +#define SOME_CLASS +#endif + +``` + +Which is more preferable and why?",2011/05/25,"['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']","I prefer the first method, because it doesn't matter what happens after the ifndef because it will be defined straight after.","The first option is commonly optimized by compilers to behave like the non-standard `#pragma once`. + +It is also safer in case of recursive includes. If, in the `//code...` part, you include another header which includes .... which includes the header you're currently editing, then the second version won't work." +6123544,"In header files I've seen two main ways for defining macro to avoid including the file more than once. + +1. + +``` +#ifndef SOME_CLASS +#define SOME_CLASS +//code ... +#endif + +``` + +2. + +``` +#ifndef SOME_CLASS +//code... +#define SOME_CLASS +#endif + +``` + +Which is more preferable and why?",2011/05/25,"['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']","I'd go for the first one. + +Reason: If you ever want to change the guard name (say, `SOME_CLASS` to `SOMECLASS`), you don't have to scroll all the way down to the end of file to change it too.",The best option is to use `#pragma once`. With `#define` you must be very careful when using multiple libraries as the guard name may not be unique. +6123544,"In header files I've seen two main ways for defining macro to avoid including the file more than once. + +1. + +``` +#ifndef SOME_CLASS +#define SOME_CLASS +//code ... +#endif + +``` + +2. + +``` +#ifndef SOME_CLASS +//code... +#define SOME_CLASS +#endif + +``` + +Which is more preferable and why?",2011/05/25,"['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']","I'd go for the first one. + +Reason: If you ever want to change the guard name (say, `SOME_CLASS` to `SOMECLASS`), you don't have to scroll all the way down to the end of file to change it too.","I prefer the first option. Suppose you include more files, and these files in turn include the file containing `#ifndef SOME_CLASS`. + +I think it's fairly easy to spot include errors, if the `#define SOME_CLASS` isn't adjacent to `#ifndef SOME_CLASS`. + +``` +// SomeClass.h +#ifndef SOME_CLASS +#include ""OtherFile.h"" // will eventually lead to #include ""SomeClass.h"" +#define SOME_CLASS + +... boat load of code here... + +#endif // SOME_CLASS + +```" +6123544,"In header files I've seen two main ways for defining macro to avoid including the file more than once. + +1. + +``` +#ifndef SOME_CLASS +#define SOME_CLASS +//code ... +#endif + +``` + +2. + +``` +#ifndef SOME_CLASS +//code... +#define SOME_CLASS +#endif + +``` + +Which is more preferable and why?",2011/05/25,"['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']",The best option is to use `#pragma once`. With `#define` you must be very careful when using multiple libraries as the guard name may not be unique.,"I prefer the first option. Suppose you include more files, and these files in turn include the file containing `#ifndef SOME_CLASS`. + +I think it's fairly easy to spot include errors, if the `#define SOME_CLASS` isn't adjacent to `#ifndef SOME_CLASS`. + +``` +// SomeClass.h +#ifndef SOME_CLASS +#include ""OtherFile.h"" // will eventually lead to #include ""SomeClass.h"" +#define SOME_CLASS + +... boat load of code here... + +#endif // SOME_CLASS + +```" +6123544,"In header files I've seen two main ways for defining macro to avoid including the file more than once. + +1. + +``` +#ifndef SOME_CLASS +#define SOME_CLASS +//code ... +#endif + +``` + +2. + +``` +#ifndef SOME_CLASS +//code... +#define SOME_CLASS +#endif + +``` + +Which is more preferable and why?",2011/05/25,"['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']","The first option is commonly optimized by compilers to behave like the non-standard `#pragma once`. + +It is also safer in case of recursive includes. If, in the `//code...` part, you include another header which includes .... which includes the header you're currently editing, then the second version won't work.",The best option is to use `#pragma once`. With `#define` you must be very careful when using multiple libraries as the guard name may not be unique. +6123544,"In header files I've seen two main ways for defining macro to avoid including the file more than once. + +1. + +``` +#ifndef SOME_CLASS +#define SOME_CLASS +//code ... +#endif + +``` + +2. + +``` +#ifndef SOME_CLASS +//code... +#define SOME_CLASS +#endif + +``` + +Which is more preferable and why?",2011/05/25,"['https://Stackoverflow.com/questions/6123544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509233/']","The first option is commonly optimized by compilers to behave like the non-standard `#pragma once`. + +It is also safer in case of recursive includes. If, in the `//code...` part, you include another header which includes .... which includes the header you're currently editing, then the second version won't work.","I prefer the first option. Suppose you include more files, and these files in turn include the file containing `#ifndef SOME_CLASS`. + +I think it's fairly easy to spot include errors, if the `#define SOME_CLASS` isn't adjacent to `#ifndef SOME_CLASS`. + +``` +// SomeClass.h +#ifndef SOME_CLASS +#include ""OtherFile.h"" // will eventually lead to #include ""SomeClass.h"" +#define SOME_CLASS + +... boat load of code here... + +#endif // SOME_CLASS + +```" +255287,"> +> If $n\_p=1$, then the $p$-Sylow subgroup is normal. +> +> +> + +I've used this fact several times, and it's about time I knew why it's true.",2012/12/10,"['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']","Let $N$ be a p-sylow subgroup. + +For all $x$ ,$xNx^{-1}$ is a conjugate of $N$. If the set of groups conjugate to $N$ has size $1$ we find that $xNx^{-1}=N$ for all $x$.","Well, $n\_p$ is the number of $p$-Sylow subgroups. The conjugates of $p$-Sylow subgroup are precisely the other $p$-Sylow sugroups. So if $n\_p=1$ then the $p$-Sylow subgroup is conjugate only to itself, i.e. it is normal." +255287,"> +> If $n\_p=1$, then the $p$-Sylow subgroup is normal. +> +> +> + +I've used this fact several times, and it's about time I knew why it's true.",2012/12/10,"['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']","Let $N$ be a p-sylow subgroup. + +For all $x$ ,$xNx^{-1}$ is a conjugate of $N$. If the set of groups conjugate to $N$ has size $1$ we find that $xNx^{-1}=N$ for all $x$.","Let $N$ be the single Sylow $p$-group. Suppose it is not normal. Then conjugation by some element $g$ gives a group $gNg^{-1}$ different from $N$ with the same number of elements as $N$. This is another Sylow $p$-group, distinct from the first, a contradiction." +255287,"> +> If $n\_p=1$, then the $p$-Sylow subgroup is normal. +> +> +> + +I've used this fact several times, and it's about time I knew why it's true.",2012/12/10,"['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']","Let $N$ be a p-sylow subgroup. + +For all $x$ ,$xNx^{-1}$ is a conjugate of $N$. If the set of groups conjugate to $N$ has size $1$ we find that $xNx^{-1}=N$ for all $x$.","I don't want to add something different here, but good to know that $n\_p=[G:N\_G(P)]$ when $P$ is a $p$- sylow of $G$. So if $n\_p=1$ then $N\_G(P)=G$ so $P$ is normal in $G$." +255287,"> +> If $n\_p=1$, then the $p$-Sylow subgroup is normal. +> +> +> + +I've used this fact several times, and it's about time I knew why it's true.",2012/12/10,"['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']","Let $N$ be a p-sylow subgroup. + +For all $x$ ,$xNx^{-1}$ is a conjugate of $N$. If the set of groups conjugate to $N$ has size $1$ we find that $xNx^{-1}=N$ for all $x$.","If I may add something. +The following statement is true: + +Let $U\leq G$ be a subgroup such that there is no other subgroup that has the same order. Then $U$ is a characteristic subgroup. That is, *every automorphism* of $G$ maps $U$ to itself." +255287,"> +> If $n\_p=1$, then the $p$-Sylow subgroup is normal. +> +> +> + +I've used this fact several times, and it's about time I knew why it's true.",2012/12/10,"['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']","I don't want to add something different here, but good to know that $n\_p=[G:N\_G(P)]$ when $P$ is a $p$- sylow of $G$. So if $n\_p=1$ then $N\_G(P)=G$ so $P$ is normal in $G$.","Well, $n\_p$ is the number of $p$-Sylow subgroups. The conjugates of $p$-Sylow subgroup are precisely the other $p$-Sylow sugroups. So if $n\_p=1$ then the $p$-Sylow subgroup is conjugate only to itself, i.e. it is normal." +255287,"> +> If $n\_p=1$, then the $p$-Sylow subgroup is normal. +> +> +> + +I've used this fact several times, and it's about time I knew why it's true.",2012/12/10,"['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']","I don't want to add something different here, but good to know that $n\_p=[G:N\_G(P)]$ when $P$ is a $p$- sylow of $G$. So if $n\_p=1$ then $N\_G(P)=G$ so $P$ is normal in $G$.","Let $N$ be the single Sylow $p$-group. Suppose it is not normal. Then conjugation by some element $g$ gives a group $gNg^{-1}$ different from $N$ with the same number of elements as $N$. This is another Sylow $p$-group, distinct from the first, a contradiction." +255287,"> +> If $n\_p=1$, then the $p$-Sylow subgroup is normal. +> +> +> + +I've used this fact several times, and it's about time I knew why it's true.",2012/12/10,"['https://math.stackexchange.com/questions/255287', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51426/']","I don't want to add something different here, but good to know that $n\_p=[G:N\_G(P)]$ when $P$ is a $p$- sylow of $G$. So if $n\_p=1$ then $N\_G(P)=G$ so $P$ is normal in $G$.","If I may add something. +The following statement is true: + +Let $U\leq G$ be a subgroup such that there is no other subgroup that has the same order. Then $U$ is a characteristic subgroup. That is, *every automorphism* of $G$ maps $U$ to itself." +70968102,"What I want is to define an array of Strings in Ada. + +I'm trying to execute this code: + +``` +type String is array (Positive range <>) of Character; +type lexicon is array(1..7) of String(1..20); +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +And the compiler says: + +``` +warning:wrong length for array of subtype of ""String"" defined at line 42 + +``` + +My line 42 is this: + +``` +type lexicon is array(1..7) of String(1..20); + +``` + +But compailer says the warning is in line 43 and 44: what are these: + +``` +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +Can somebody help me with that?",2022/02/03,"['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']","You declared your array to hold Strings of length 20. The String literals you give are less than 20 Characters long. Hence the error. + +You seem to be looking for a string type that contains a *maximum* of 20 characters. This is provided in `Ada.Strings.Bounded`: + +```vhdl +package Max_20_String is new Ada.Strings.Bounded.Generic_Bounded_Length (20); +use Max_20_String; + +type Lexicon is array (1..7) of Bounded_String; -- from Max_20_String +nomFumadors : Lexicon := (To_Bounded_String (""Macia""), + To_Bounded_String (""Xisco""), + To_Bounded_String (""Toni""), + To_Bounded_String (""Laura""), + To_Bounded_String (""Rocky""), + To_Bounded_String (""Paz"")); + +``` + +To get back a String from a Bounded\_String, use e.g. `To_String (Lexicon (2))`.","Another solution is to use String, truncate long strings, and pad short strings: + +``` +Max : constant := 20; +subtype S20 is String (1 .. Max); +type Lexicon is array (1 .. 7) of S20; +function To20 (S : in String) return S20 is + (if S'Length >= Max then S (S'First .. S'First + Max - 1) + else S & (S'Length + 1 .. Max => ' ') ); +V : Lexicon := (To20 (""""), To20 (""Hello""), To20 (""1234567890123456789012345""), ... + +```" +70968102,"What I want is to define an array of Strings in Ada. + +I'm trying to execute this code: + +``` +type String is array (Positive range <>) of Character; +type lexicon is array(1..7) of String(1..20); +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +And the compiler says: + +``` +warning:wrong length for array of subtype of ""String"" defined at line 42 + +``` + +My line 42 is this: + +``` +type lexicon is array(1..7) of String(1..20); + +``` + +But compailer says the warning is in line 43 and 44: what are these: + +``` +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +Can somebody help me with that?",2022/02/03,"['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']","Another solution is to use String, truncate long strings, and pad short strings: + +``` +Max : constant := 20; +subtype S20 is String (1 .. Max); +type Lexicon is array (1 .. 7) of S20; +function To20 (S : in String) return S20 is + (if S'Length >= Max then S (S'First .. S'First + Max - 1) + else S & (S'Length + 1 .. Max => ' ') ); +V : Lexicon := (To20 (""""), To20 (""Hello""), To20 (""1234567890123456789012345""), ... + +```","Building upon the solution by Mark, but simplifying thanks to the operations from [`Ada.Strings.Fixed`](https://en.wikibooks.org/wiki/Ada_Programming/Libraries/Ada.Strings.Fixed). + +```ada +with Ada.Strings.Fixed; +with Ada.Text_IO; + +procedure Main is + + subtype Lexicon_Data is String (1 .. 20); + type Lexicon is array (1 .. 7) of Lexicon_Data; + + function To_Lexicon_Data + (Value : in String) + return Lexicon_Data + is + begin + return Ada.Strings.Fixed.Head (Value, Lexicon_Data'Length); + end To_Lexicon_Data; + + nomFumadors : constant Lexicon := + (To_Lexicon_Data (""Macia""), + To_Lexicon_Data (""Xisco""), + To_Lexicon_Data (""Toni""), + To_Lexicon_Data (""Laura""), + To_Lexicon_Data (""Rocky""), + To_Lexicon_Data (""Paz""), + To_Lexicon_Data (""Mark"")); + +begin + + for Item of nomFumadors loop + Ada.Text_IO.Put_Line (Ada.Strings.Fixed.Trim (Item, Ada.Strings.Both)); + end loop; + +end Main; + +```" +70968102,"What I want is to define an array of Strings in Ada. + +I'm trying to execute this code: + +``` +type String is array (Positive range <>) of Character; +type lexicon is array(1..7) of String(1..20); +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +And the compiler says: + +``` +warning:wrong length for array of subtype of ""String"" defined at line 42 + +``` + +My line 42 is this: + +``` +type lexicon is array(1..7) of String(1..20); + +``` + +But compailer says the warning is in line 43 and 44: what are these: + +``` +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +Can somebody help me with that?",2022/02/03,"['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']","Others have mentioned bounded and unbounded strings. You can also use Indefinite\_Vectors. You can use the ""&"" operator to initialize them (as opposed to the initializer list though the next version of Ada is adding initializer lists to containers). You can use a vector just like an array by passing indexes in plus you get a lot of other additional functionality. + +```ada +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Containers.Indefinite_Vectors; + +procedure Hello is + + package Vectors is new Ada.Containers.Indefinite_Vectors + (Index_Type => Positive, + Element_Type => String); + + use type Vectors.Vector; + + nomFumadors : Vectors.Vector + := Vectors.Empty_Vector + & ""Macia"" + & ""Xisco"" + & ""Toni"" + & ""Laura"" + & ""Rocky"" + & ""Paz""; + nomNoFumadors : Vectors.Vector + := Vectors.Empty_Vector + & ""Marina"" + & ""Marta"" + & ""Joan"" + & ""Africa"" + & ""America""; +begin + Put_Line(""Hello, world!""); + + -- Loop through Elements + for Name of nomFumadors loop + Put_Line(Name); + end loop; + + -- Loop by index + for Index in nomNoFumadors.Iterate loop + Put_Line(nomNoFumadors(Index)); + end loop; + +end Hello; + +```","Another solution is to use String, truncate long strings, and pad short strings: + +``` +Max : constant := 20; +subtype S20 is String (1 .. Max); +type Lexicon is array (1 .. 7) of S20; +function To20 (S : in String) return S20 is + (if S'Length >= Max then S (S'First .. S'First + Max - 1) + else S & (S'Length + 1 .. Max => ' ') ); +V : Lexicon := (To20 (""""), To20 (""Hello""), To20 (""1234567890123456789012345""), ... + +```" +70968102,"What I want is to define an array of Strings in Ada. + +I'm trying to execute this code: + +``` +type String is array (Positive range <>) of Character; +type lexicon is array(1..7) of String(1..20); +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +And the compiler says: + +``` +warning:wrong length for array of subtype of ""String"" defined at line 42 + +``` + +My line 42 is this: + +``` +type lexicon is array(1..7) of String(1..20); + +``` + +But compailer says the warning is in line 43 and 44: what are these: + +``` +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +Can somebody help me with that?",2022/02/03,"['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']","You declared your array to hold Strings of length 20. The String literals you give are less than 20 Characters long. Hence the error. + +You seem to be looking for a string type that contains a *maximum* of 20 characters. This is provided in `Ada.Strings.Bounded`: + +```vhdl +package Max_20_String is new Ada.Strings.Bounded.Generic_Bounded_Length (20); +use Max_20_String; + +type Lexicon is array (1..7) of Bounded_String; -- from Max_20_String +nomFumadors : Lexicon := (To_Bounded_String (""Macia""), + To_Bounded_String (""Xisco""), + To_Bounded_String (""Toni""), + To_Bounded_String (""Laura""), + To_Bounded_String (""Rocky""), + To_Bounded_String (""Paz"")); + +``` + +To get back a String from a Bounded\_String, use e.g. `To_String (Lexicon (2))`.","Similar to Jeff Carter's answer, but using a function to coerce any string into a fixed string ... + +``` +procedure Main is + + subtype Lexicon_Data is String (1 .. 20); + type Lexicon is array (1 .. 7) of Lexicon_Data; + + function To_Lexicon_Data + (Value : in String) + return Lexicon_Data + is + Result : Lexicon_Data; + begin + + if Value'Length < 1 then + -- Empty string returns a bunch of spaces + Result := (others => ' '); + + else + declare + Offset : constant Natural := + Value'First - Lexicon_Data'First; + begin + + if Value'Length > Lexicon_Data'Length then + -- Length exceeds range, so truncate + Result (Lexicon_Data'Range) := Lexicon_Data + (Value (Offset + 1 .. Offset + Lexicon_Data'Length)); + + else + -- Copy into result, and pad right with spaces + Result := (others => ' '); + Result (Lexicon_Data'First .. Value'Length) := + (Value (Offset + 1 .. Offset + Value'Length)); + + end if; + + end; + + end if; + + return Result; + + end To_Lexicon_Data; + + nomFumadors : constant Lexicon := + (To_Lexicon_Data (""Macia""), + To_Lexicon_Data (""Xisco""), + To_Lexicon_Data (""Toni""), + To_Lexicon_Data (""Laura""), + To_Lexicon_Data (""Rocky""), + To_Lexicon_Data (""Paz""), + To_Lexicon_Data (""Mark"")); + +begin + -- Insert code here. + null; +end Main; + +``` + +If you wanted to prove AoRTE (ie SparkAda) then the declaration for Result in the function becomes + +``` +Result : Lexicon_Data + with Relaxed_Initialization; + +``` + +.. and the function To\_Lexicon\_Data is proved as being runtime error free. + +Note the extra item for Lexicon, Mark, since you need seven items for the Lexicon declaration to be valid." +70968102,"What I want is to define an array of Strings in Ada. + +I'm trying to execute this code: + +``` +type String is array (Positive range <>) of Character; +type lexicon is array(1..7) of String(1..20); +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +And the compiler says: + +``` +warning:wrong length for array of subtype of ""String"" defined at line 42 + +``` + +My line 42 is this: + +``` +type lexicon is array(1..7) of String(1..20); + +``` + +But compailer says the warning is in line 43 and 44: what are these: + +``` +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +Can somebody help me with that?",2022/02/03,"['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']","Others have mentioned bounded and unbounded strings. You can also use Indefinite\_Vectors. You can use the ""&"" operator to initialize them (as opposed to the initializer list though the next version of Ada is adding initializer lists to containers). You can use a vector just like an array by passing indexes in plus you get a lot of other additional functionality. + +```ada +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Containers.Indefinite_Vectors; + +procedure Hello is + + package Vectors is new Ada.Containers.Indefinite_Vectors + (Index_Type => Positive, + Element_Type => String); + + use type Vectors.Vector; + + nomFumadors : Vectors.Vector + := Vectors.Empty_Vector + & ""Macia"" + & ""Xisco"" + & ""Toni"" + & ""Laura"" + & ""Rocky"" + & ""Paz""; + nomNoFumadors : Vectors.Vector + := Vectors.Empty_Vector + & ""Marina"" + & ""Marta"" + & ""Joan"" + & ""Africa"" + & ""America""; +begin + Put_Line(""Hello, world!""); + + -- Loop through Elements + for Name of nomFumadors loop + Put_Line(Name); + end loop; + + -- Loop by index + for Index in nomNoFumadors.Iterate loop + Put_Line(nomNoFumadors(Index)); + end loop; + +end Hello; + +```","Building upon the solution by Mark, but simplifying thanks to the operations from [`Ada.Strings.Fixed`](https://en.wikibooks.org/wiki/Ada_Programming/Libraries/Ada.Strings.Fixed). + +```ada +with Ada.Strings.Fixed; +with Ada.Text_IO; + +procedure Main is + + subtype Lexicon_Data is String (1 .. 20); + type Lexicon is array (1 .. 7) of Lexicon_Data; + + function To_Lexicon_Data + (Value : in String) + return Lexicon_Data + is + begin + return Ada.Strings.Fixed.Head (Value, Lexicon_Data'Length); + end To_Lexicon_Data; + + nomFumadors : constant Lexicon := + (To_Lexicon_Data (""Macia""), + To_Lexicon_Data (""Xisco""), + To_Lexicon_Data (""Toni""), + To_Lexicon_Data (""Laura""), + To_Lexicon_Data (""Rocky""), + To_Lexicon_Data (""Paz""), + To_Lexicon_Data (""Mark"")); + +begin + + for Item of nomFumadors loop + Ada.Text_IO.Put_Line (Ada.Strings.Fixed.Trim (Item, Ada.Strings.Both)); + end loop; + +end Main; + +```" +70968102,"What I want is to define an array of Strings in Ada. + +I'm trying to execute this code: + +``` +type String is array (Positive range <>) of Character; +type lexicon is array(1..7) of String(1..20); +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +And the compiler says: + +``` +warning:wrong length for array of subtype of ""String"" defined at line 42 + +``` + +My line 42 is this: + +``` +type lexicon is array(1..7) of String(1..20); + +``` + +But compailer says the warning is in line 43 and 44: what are these: + +``` +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +Can somebody help me with that?",2022/02/03,"['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']","Others have mentioned bounded and unbounded strings. You can also use Indefinite\_Vectors. You can use the ""&"" operator to initialize them (as opposed to the initializer list though the next version of Ada is adding initializer lists to containers). You can use a vector just like an array by passing indexes in plus you get a lot of other additional functionality. + +```ada +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Containers.Indefinite_Vectors; + +procedure Hello is + + package Vectors is new Ada.Containers.Indefinite_Vectors + (Index_Type => Positive, + Element_Type => String); + + use type Vectors.Vector; + + nomFumadors : Vectors.Vector + := Vectors.Empty_Vector + & ""Macia"" + & ""Xisco"" + & ""Toni"" + & ""Laura"" + & ""Rocky"" + & ""Paz""; + nomNoFumadors : Vectors.Vector + := Vectors.Empty_Vector + & ""Marina"" + & ""Marta"" + & ""Joan"" + & ""Africa"" + & ""America""; +begin + Put_Line(""Hello, world!""); + + -- Loop through Elements + for Name of nomFumadors loop + Put_Line(Name); + end loop; + + -- Loop by index + for Index in nomNoFumadors.Iterate loop + Put_Line(nomNoFumadors(Index)); + end loop; + +end Hello; + +```","Similar to Jeff Carter's answer, but using a function to coerce any string into a fixed string ... + +``` +procedure Main is + + subtype Lexicon_Data is String (1 .. 20); + type Lexicon is array (1 .. 7) of Lexicon_Data; + + function To_Lexicon_Data + (Value : in String) + return Lexicon_Data + is + Result : Lexicon_Data; + begin + + if Value'Length < 1 then + -- Empty string returns a bunch of spaces + Result := (others => ' '); + + else + declare + Offset : constant Natural := + Value'First - Lexicon_Data'First; + begin + + if Value'Length > Lexicon_Data'Length then + -- Length exceeds range, so truncate + Result (Lexicon_Data'Range) := Lexicon_Data + (Value (Offset + 1 .. Offset + Lexicon_Data'Length)); + + else + -- Copy into result, and pad right with spaces + Result := (others => ' '); + Result (Lexicon_Data'First .. Value'Length) := + (Value (Offset + 1 .. Offset + Value'Length)); + + end if; + + end; + + end if; + + return Result; + + end To_Lexicon_Data; + + nomFumadors : constant Lexicon := + (To_Lexicon_Data (""Macia""), + To_Lexicon_Data (""Xisco""), + To_Lexicon_Data (""Toni""), + To_Lexicon_Data (""Laura""), + To_Lexicon_Data (""Rocky""), + To_Lexicon_Data (""Paz""), + To_Lexicon_Data (""Mark"")); + +begin + -- Insert code here. + null; +end Main; + +``` + +If you wanted to prove AoRTE (ie SparkAda) then the declaration for Result in the function becomes + +``` +Result : Lexicon_Data + with Relaxed_Initialization; + +``` + +.. and the function To\_Lexicon\_Data is proved as being runtime error free. + +Note the extra item for Lexicon, Mark, since you need seven items for the Lexicon declaration to be valid." +70968102,"What I want is to define an array of Strings in Ada. + +I'm trying to execute this code: + +``` +type String is array (Positive range <>) of Character; +type lexicon is array(1..7) of String(1..20); +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +And the compiler says: + +``` +warning:wrong length for array of subtype of ""String"" defined at line 42 + +``` + +My line 42 is this: + +``` +type lexicon is array(1..7) of String(1..20); + +``` + +But compailer says the warning is in line 43 and 44: what are these: + +``` +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +Can somebody help me with that?",2022/02/03,"['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']","Another option is `Unbounded_String` (as its name suggests, length is variable and unlimited): + +``` +with Ada.Strings.Unbounded; + +procedure Fumador is + use Ada.Strings.Unbounded; + + subtype VString is Unbounded_String; + function ""+"" (Source : in String) return VString renames To_Unbounded_String; + + type Lexicon is array (Integer range <>) of VString; -- Unknown number of people. + nomFumadors : Lexicon := (+""Macia"", +""Xisco"", +""Toni"", +""Laura"", +""Rocky"", +""Paz""); + nomNoFumadors : Lexicon := (+""Marina"", +""Marta"", +""Joan"", +""Africa"", +""America""); + +begin + null; +end; + +```","Similar to Jeff Carter's answer, but using a function to coerce any string into a fixed string ... + +``` +procedure Main is + + subtype Lexicon_Data is String (1 .. 20); + type Lexicon is array (1 .. 7) of Lexicon_Data; + + function To_Lexicon_Data + (Value : in String) + return Lexicon_Data + is + Result : Lexicon_Data; + begin + + if Value'Length < 1 then + -- Empty string returns a bunch of spaces + Result := (others => ' '); + + else + declare + Offset : constant Natural := + Value'First - Lexicon_Data'First; + begin + + if Value'Length > Lexicon_Data'Length then + -- Length exceeds range, so truncate + Result (Lexicon_Data'Range) := Lexicon_Data + (Value (Offset + 1 .. Offset + Lexicon_Data'Length)); + + else + -- Copy into result, and pad right with spaces + Result := (others => ' '); + Result (Lexicon_Data'First .. Value'Length) := + (Value (Offset + 1 .. Offset + Value'Length)); + + end if; + + end; + + end if; + + return Result; + + end To_Lexicon_Data; + + nomFumadors : constant Lexicon := + (To_Lexicon_Data (""Macia""), + To_Lexicon_Data (""Xisco""), + To_Lexicon_Data (""Toni""), + To_Lexicon_Data (""Laura""), + To_Lexicon_Data (""Rocky""), + To_Lexicon_Data (""Paz""), + To_Lexicon_Data (""Mark"")); + +begin + -- Insert code here. + null; +end Main; + +``` + +If you wanted to prove AoRTE (ie SparkAda) then the declaration for Result in the function becomes + +``` +Result : Lexicon_Data + with Relaxed_Initialization; + +``` + +.. and the function To\_Lexicon\_Data is proved as being runtime error free. + +Note the extra item for Lexicon, Mark, since you need seven items for the Lexicon declaration to be valid." +70968102,"What I want is to define an array of Strings in Ada. + +I'm trying to execute this code: + +``` +type String is array (Positive range <>) of Character; +type lexicon is array(1..7) of String(1..20); +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +And the compiler says: + +``` +warning:wrong length for array of subtype of ""String"" defined at line 42 + +``` + +My line 42 is this: + +``` +type lexicon is array(1..7) of String(1..20); + +``` + +But compailer says the warning is in line 43 and 44: what are these: + +``` +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +Can somebody help me with that?",2022/02/03,"['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']","Another option is `Unbounded_String` (as its name suggests, length is variable and unlimited): + +``` +with Ada.Strings.Unbounded; + +procedure Fumador is + use Ada.Strings.Unbounded; + + subtype VString is Unbounded_String; + function ""+"" (Source : in String) return VString renames To_Unbounded_String; + + type Lexicon is array (Integer range <>) of VString; -- Unknown number of people. + nomFumadors : Lexicon := (+""Macia"", +""Xisco"", +""Toni"", +""Laura"", +""Rocky"", +""Paz""); + nomNoFumadors : Lexicon := (+""Marina"", +""Marta"", +""Joan"", +""Africa"", +""America""); + +begin + null; +end; + +```","Another solution is to use String, truncate long strings, and pad short strings: + +``` +Max : constant := 20; +subtype S20 is String (1 .. Max); +type Lexicon is array (1 .. 7) of S20; +function To20 (S : in String) return S20 is + (if S'Length >= Max then S (S'First .. S'First + Max - 1) + else S & (S'Length + 1 .. Max => ' ') ); +V : Lexicon := (To20 (""""), To20 (""Hello""), To20 (""1234567890123456789012345""), ... + +```" +70968102,"What I want is to define an array of Strings in Ada. + +I'm trying to execute this code: + +``` +type String is array (Positive range <>) of Character; +type lexicon is array(1..7) of String(1..20); +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +And the compiler says: + +``` +warning:wrong length for array of subtype of ""String"" defined at line 42 + +``` + +My line 42 is this: + +``` +type lexicon is array(1..7) of String(1..20); + +``` + +But compailer says the warning is in line 43 and 44: what are these: + +``` +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +Can somebody help me with that?",2022/02/03,"['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']","Another option is `Unbounded_String` (as its name suggests, length is variable and unlimited): + +``` +with Ada.Strings.Unbounded; + +procedure Fumador is + use Ada.Strings.Unbounded; + + subtype VString is Unbounded_String; + function ""+"" (Source : in String) return VString renames To_Unbounded_String; + + type Lexicon is array (Integer range <>) of VString; -- Unknown number of people. + nomFumadors : Lexicon := (+""Macia"", +""Xisco"", +""Toni"", +""Laura"", +""Rocky"", +""Paz""); + nomNoFumadors : Lexicon := (+""Marina"", +""Marta"", +""Joan"", +""Africa"", +""America""); + +begin + null; +end; + +```","Building upon the solution by Mark, but simplifying thanks to the operations from [`Ada.Strings.Fixed`](https://en.wikibooks.org/wiki/Ada_Programming/Libraries/Ada.Strings.Fixed). + +```ada +with Ada.Strings.Fixed; +with Ada.Text_IO; + +procedure Main is + + subtype Lexicon_Data is String (1 .. 20); + type Lexicon is array (1 .. 7) of Lexicon_Data; + + function To_Lexicon_Data + (Value : in String) + return Lexicon_Data + is + begin + return Ada.Strings.Fixed.Head (Value, Lexicon_Data'Length); + end To_Lexicon_Data; + + nomFumadors : constant Lexicon := + (To_Lexicon_Data (""Macia""), + To_Lexicon_Data (""Xisco""), + To_Lexicon_Data (""Toni""), + To_Lexicon_Data (""Laura""), + To_Lexicon_Data (""Rocky""), + To_Lexicon_Data (""Paz""), + To_Lexicon_Data (""Mark"")); + +begin + + for Item of nomFumadors loop + Ada.Text_IO.Put_Line (Ada.Strings.Fixed.Trim (Item, Ada.Strings.Both)); + end loop; + +end Main; + +```" +70968102,"What I want is to define an array of Strings in Ada. + +I'm trying to execute this code: + +``` +type String is array (Positive range <>) of Character; +type lexicon is array(1..7) of String(1..20); +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +And the compiler says: + +``` +warning:wrong length for array of subtype of ""String"" defined at line 42 + +``` + +My line 42 is this: + +``` +type lexicon is array(1..7) of String(1..20); + +``` + +But compailer says the warning is in line 43 and 44: what are these: + +``` +nomFumadors : lexicon := (""Macia"",""Xisco"",""Toni"",""Laura"",""Rocky"",""Paz""); +nomNoFumadors : lexicon := (""Marina"",""Marta"",""Joan"",""Africa"",""America""); + +``` + +Can somebody help me with that?",2022/02/03,"['https://Stackoverflow.com/questions/70968102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12058857/']","You declared your array to hold Strings of length 20. The String literals you give are less than 20 Characters long. Hence the error. + +You seem to be looking for a string type that contains a *maximum* of 20 characters. This is provided in `Ada.Strings.Bounded`: + +```vhdl +package Max_20_String is new Ada.Strings.Bounded.Generic_Bounded_Length (20); +use Max_20_String; + +type Lexicon is array (1..7) of Bounded_String; -- from Max_20_String +nomFumadors : Lexicon := (To_Bounded_String (""Macia""), + To_Bounded_String (""Xisco""), + To_Bounded_String (""Toni""), + To_Bounded_String (""Laura""), + To_Bounded_String (""Rocky""), + To_Bounded_String (""Paz"")); + +``` + +To get back a String from a Bounded\_String, use e.g. `To_String (Lexicon (2))`.","Building upon the solution by Mark, but simplifying thanks to the operations from [`Ada.Strings.Fixed`](https://en.wikibooks.org/wiki/Ada_Programming/Libraries/Ada.Strings.Fixed). + +```ada +with Ada.Strings.Fixed; +with Ada.Text_IO; + +procedure Main is + + subtype Lexicon_Data is String (1 .. 20); + type Lexicon is array (1 .. 7) of Lexicon_Data; + + function To_Lexicon_Data + (Value : in String) + return Lexicon_Data + is + begin + return Ada.Strings.Fixed.Head (Value, Lexicon_Data'Length); + end To_Lexicon_Data; + + nomFumadors : constant Lexicon := + (To_Lexicon_Data (""Macia""), + To_Lexicon_Data (""Xisco""), + To_Lexicon_Data (""Toni""), + To_Lexicon_Data (""Laura""), + To_Lexicon_Data (""Rocky""), + To_Lexicon_Data (""Paz""), + To_Lexicon_Data (""Mark"")); + +begin + + for Item of nomFumadors loop + Ada.Text_IO.Put_Line (Ada.Strings.Fixed.Trim (Item, Ada.Strings.Both)); + end loop; + +end Main; + +```" +19576214,"I have two click functions: one targets td.default and the second td.clicked. Both changes the class attribute to either 'clicked' or 'default' (and updates the text in the cell). The classes are getting changed from the first click function but the second click function that looks for td.click doesn't find it's target. + +``` +$(""td.default"").click(function() { + $(this).attr('class','clicked'); + $(this).text(""monkey""); + $(""#ouput"").append(""td.default clicked
""); //reporting message +}); +$(""td.clicked"").click(function() { + $(this).attr('class','default'); + $(this).text(""empty""); + $(""#ouput"").append(""td.clicked clicked
""); //reporting message +}); + +```",2013/10/24,"['https://Stackoverflow.com/questions/19576214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2237565/']","Use delegation instead + +``` +$(""table"").on(""click"", ""td.default"", function() { + $(this).attr('class','clicked'); + $(this).text(""monkey""); + $(""#ouput"").append(""td.default clicked
""); //reporting message +}); +$(""table"").on(""click"", ""td.clicked"", function() { + $(this).attr('class','default'); + $(this).text(""empty""); + $(""#ouput"").append(""td.clicked clicked
""); //reporting message +}); + +``` + +Delegation would handle the dynamic changes on the nodes v/s `.click()`, which would not rebind dynamically modified nodes. [Read more on delegation using `on` here](http://api.jquery.com/on/)","That seems like a lot of work, would it be easier to do it this way? + +``` +$('td.default,td.clicked').on('click', function() { + $(this).toggleClass('default').toggleClass('clicked').text( + $(this).text() === 'empty' ? 'monkey' : 'empty' + ); +}); + +``` + +made a fiddle: " +19576214,"I have two click functions: one targets td.default and the second td.clicked. Both changes the class attribute to either 'clicked' or 'default' (and updates the text in the cell). The classes are getting changed from the first click function but the second click function that looks for td.click doesn't find it's target. + +``` +$(""td.default"").click(function() { + $(this).attr('class','clicked'); + $(this).text(""monkey""); + $(""#ouput"").append(""td.default clicked
""); //reporting message +}); +$(""td.clicked"").click(function() { + $(this).attr('class','default'); + $(this).text(""empty""); + $(""#ouput"").append(""td.clicked clicked
""); //reporting message +}); + +```",2013/10/24,"['https://Stackoverflow.com/questions/19576214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2237565/']","When you bind a click handler, you are binding to the element. Changing the class of the element doesn't change that handler that you've bound to it. If you want that behavior, you'll need to use `on()` with event delegation. See [`on()`](http://api.jquery.com/on/), especially the section about ""direct and delegated events"". + +[**Demo Click Here**](http://jsfiddle.net/hEQMe/) : + +``` +$(document).on('click', ""td.default"", function() { + $(this).attr('class','clicked'); + $(this).text(""monkey""); + $(""#ouput"").append(""td.default clicked
""); //reporting message +}); +$(document).on('click', ""td.clicked"", function() { + $(this).attr('class','default'); + $(this).text(""empty""); + $(""#ouput"").append(""td.clicked clicked
""); //reporting message +}); + +```","That seems like a lot of work, would it be easier to do it this way? + +``` +$('td.default,td.clicked').on('click', function() { + $(this).toggleClass('default').toggleClass('clicked').text( + $(this).text() === 'empty' ? 'monkey' : 'empty' + ); +}); + +``` + +made a fiddle: " +296482,"I just landed at LAX and the flight attendant (who had a slight Latino accent, but was a native or near-native English speaker) gave the last announcement: + +> +> ""As we prepare to land please have cups and other items ready to throw away, as we're going to make one last pass through the cabin *at which time*."" Full stop. +> +> +> + +There were several such utterances during the flight which ended with ""at which time,"" each of which was clearly meant to signify ""at this time."" Is this a common usage in a variety of English I'm unfamiliar with, or is it more likely to be this one speaker's quirk?",2015/12/28,"['https://english.stackexchange.com/questions/296482', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/-1/']","In this context, the word ""suppose"" means ""believe""; see [Merriam-Webster](http://www.merriam-webster.com/dictionary/suppose): + +> +> b (1) : to hold as an opinion : believe [they *supposed* they were early] +> +> +> (2) : to think probable or in keeping with the facts [seems reasonable to *suppose* that he would profit] +> +> +> + +So the key phrase: + +> +> ""...the proudest of men, the philosopher, supposes that he sees on all sides the eyes of the universe telescopically focused upon his action and thought."" +> +> +> + +...may be treated as: + +> +> ""...the philosopher supposes (believes) that he sees (on all sides) the eyes of the universe."" +> +> +> + +Note that the philosopher *is* the ""proudest of men"" in this sentence; they are the same person. + +So, yes, the ""proudest of men"" believes that the whole universe is fixated on him.","You are pretty correct in your assumption of what this sentence means. The author is comparing the proud to porters, saying that everyone wants an admirer. Nietzsche goes a step further to say outright that philosophers are the proudest men, and that they want the universe to admire them. + +Onward, to definitions. To *suppose* something is to assume it as truth. Nietzsche here is saying that philosophers (the proudest men) already assume the universe admires them. + +As for ""all sides"", the philosopher sees all sides around him looking on. Going back to that pride (a pretty common motif for Nietzsche), the philosopher sees himself at the center, and all sides around that center are focused on him." +296482,"I just landed at LAX and the flight attendant (who had a slight Latino accent, but was a native or near-native English speaker) gave the last announcement: + +> +> ""As we prepare to land please have cups and other items ready to throw away, as we're going to make one last pass through the cabin *at which time*."" Full stop. +> +> +> + +There were several such utterances during the flight which ended with ""at which time,"" each of which was clearly meant to signify ""at this time."" Is this a common usage in a variety of English I'm unfamiliar with, or is it more likely to be this one speaker's quirk?",2015/12/28,"['https://english.stackexchange.com/questions/296482', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/-1/']","> +> ""And just as every porter wants to have an admirer, so even the proudest of men, the philosopher, supposes that he sees on all sides the eyes of the universe telescopically focused upon his action and thought."" +> +> +> + +I may be wrong, but Nietzsche seems to be saying that just as the supposedly humblest of men (viz., the porter, or [a person employed to carry burdens, especially an attendant who carries travelers' baggage at a hotel or transportation station](http://www.thefreedictionary.com/porter)) wants to be seen and admired, so too does the proudest man want to be seen and admired. + +The difference between the desire of the humble man and the desire of the proud man is a matter of degree. While the humble man is satisfied in knowing at least one person sees him and admires him (for whatever reason, perhaps for the professional way in which he carries someone's baggage), the proud person, on the other hand, is satisfied only when many, many people see him and admire him. + +Moreover, he doesn't need just an admiring glance, but he needs continually the admiring and focused attention of all kinds of people, whether his peers, whether those whom he considers to be his ""inferiors,"" or whether anyone, really. + +For the humble man, his desire is really a search for dignity. For the proud man, his desire is not for dignity, which he has in truckloads, but for the feeling of superiority. + +Whether Nietzsche's ""take"" on philosophers is accurate or not, all people, regardless of their station in life want to be noticed and admired for something. In other words, we all long for significance. That longing takes an ugly turn, however, when it morphs into a superiority complex, complete with delusions of grandeur! + +In Christian circles, the saying goes, ""The ground is level at the cross."" I like that, and I think it speaks volumes to the blatently narcissistic age in which we live.","You are pretty correct in your assumption of what this sentence means. The author is comparing the proud to porters, saying that everyone wants an admirer. Nietzsche goes a step further to say outright that philosophers are the proudest men, and that they want the universe to admire them. + +Onward, to definitions. To *suppose* something is to assume it as truth. Nietzsche here is saying that philosophers (the proudest men) already assume the universe admires them. + +As for ""all sides"", the philosopher sees all sides around him looking on. Going back to that pride (a pretty common motif for Nietzsche), the philosopher sees himself at the center, and all sides around that center are focused on him." +296482,"I just landed at LAX and the flight attendant (who had a slight Latino accent, but was a native or near-native English speaker) gave the last announcement: + +> +> ""As we prepare to land please have cups and other items ready to throw away, as we're going to make one last pass through the cabin *at which time*."" Full stop. +> +> +> + +There were several such utterances during the flight which ended with ""at which time,"" each of which was clearly meant to signify ""at this time."" Is this a common usage in a variety of English I'm unfamiliar with, or is it more likely to be this one speaker's quirk?",2015/12/28,"['https://english.stackexchange.com/questions/296482', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/-1/']","In this context, the word ""suppose"" means ""believe""; see [Merriam-Webster](http://www.merriam-webster.com/dictionary/suppose): + +> +> b (1) : to hold as an opinion : believe [they *supposed* they were early] +> +> +> (2) : to think probable or in keeping with the facts [seems reasonable to *suppose* that he would profit] +> +> +> + +So the key phrase: + +> +> ""...the proudest of men, the philosopher, supposes that he sees on all sides the eyes of the universe telescopically focused upon his action and thought."" +> +> +> + +...may be treated as: + +> +> ""...the philosopher supposes (believes) that he sees (on all sides) the eyes of the universe."" +> +> +> + +Note that the philosopher *is* the ""proudest of men"" in this sentence; they are the same person. + +So, yes, the ""proudest of men"" believes that the whole universe is fixated on him.","> +> ""And just as every porter wants to have an admirer, so even the proudest of men, the philosopher, supposes that he sees on all sides the eyes of the universe telescopically focused upon his action and thought."" +> +> +> + +I may be wrong, but Nietzsche seems to be saying that just as the supposedly humblest of men (viz., the porter, or [a person employed to carry burdens, especially an attendant who carries travelers' baggage at a hotel or transportation station](http://www.thefreedictionary.com/porter)) wants to be seen and admired, so too does the proudest man want to be seen and admired. + +The difference between the desire of the humble man and the desire of the proud man is a matter of degree. While the humble man is satisfied in knowing at least one person sees him and admires him (for whatever reason, perhaps for the professional way in which he carries someone's baggage), the proud person, on the other hand, is satisfied only when many, many people see him and admire him. + +Moreover, he doesn't need just an admiring glance, but he needs continually the admiring and focused attention of all kinds of people, whether his peers, whether those whom he considers to be his ""inferiors,"" or whether anyone, really. + +For the humble man, his desire is really a search for dignity. For the proud man, his desire is not for dignity, which he has in truckloads, but for the feeling of superiority. + +Whether Nietzsche's ""take"" on philosophers is accurate or not, all people, regardless of their station in life want to be noticed and admired for something. In other words, we all long for significance. That longing takes an ugly turn, however, when it morphs into a superiority complex, complete with delusions of grandeur! + +In Christian circles, the saying goes, ""The ground is level at the cross."" I like that, and I think it speaks volumes to the blatently narcissistic age in which we live." +48884451,"I am comparing two files in my script. using the command + +``` +comm -3 123.txt 321.txt"" + +``` + +These two files 123 and 321 has only numeric content. + +Also I use + +``` +diff -ibw abc.txt cba.txt + +``` + +These files abc and cba has alphanumeric content + +If there is no mismatch no output is printed can you help me how to write a condition as below. + +If there is no difference I need to print `files match` +If there is a difference I want to print `mismatch found` along with the mismatched output.",2018/02/20,"['https://Stackoverflow.com/questions/48884451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9054895/']","``` +- (void)collectionView:(UICollectionView *)collectionView + willDisplayCell:(UICollectionViewCell *)cell +forItemAtIndexPath:(NSIndexPath *)indexPath{ + +CGFloat collectionHeight = self.CollectionView.bounds.size.height; +CGFloat contentOffsetY = self.CollectionView.contentOffset.y; +CGFloat contentSizeHeight = self.CollectionView.contentSize.height; +CGFloat height = 0.0; + +if(isCollectionViewScrollUp && contentOffsetY + self.CollectionView.frame.size.height < contentSizeHeight) { + + int index = (int)indexPath.row + 1; + + if (index % 3 == 1){ + height = collectionHeight + 300; + }else if(index % 3 == 2){ + height = collectionHeight + 300 * 2; + + }else{ + height = collectionHeight + 300 * 3; + } + cell.transform = CGAffineTransformMakeTranslation(0, height); + +}else if(!isCollectionViewScrollUp && contentOffsetY > 0.0){ + + int index = (int)indexPath.row + 1; + + if(index % 3 == 1){ + height = collectionHeight + 300 * 3; + }else if(index % 3 == 2){ + height = collectionHeight + 300 * 2; + }else{ + height = collectionHeight + 300; + } + + cell.transform = CGAffineTransformMakeTranslation(0, -height); +} + +[UIView animateWithDuration:1 delay:0.03 usingSpringWithDamping:0.8 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseIn animations:^{ + + cell.transform = CGAffineTransformMakeTranslation(0, 0); + +} completion:nil]; +} + +-(void) scrollViewDidScroll:(UIScrollView *)scrollView { +CGPoint scrollVelocity = [CollectionView.panGestureRecognizer velocityInView:CollectionView.superview]; +if (scrollVelocity.y > 0.0) { //ScrollDown + isCollectionViewScrollUp = NO; +} else if (scrollVelocity.y < 0.0 ){ //ScrollUp + isCollectionViewScrollUp = YES; +} +} + +```","Try This: + +``` +var isCollectionViewScrollUp: Bool = true + +func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { + let collectionHeight: CGFloat = self.collectionView!.bounds.size.height + + let contentOffsetY: CGFloat = self.collectionView.contentOffset.y + let contentSizeHeight: CGFloat = self.collectionView.contentSize.height + + var height:CGFloat = 0.0//collectionHeight * CGFloat(indexPath.row) + + if isCollectionViewScrollUp && (contentOffsetY + self.collectionView.frame.size.height) < contentSizeHeight { + + let index = Int(indexPath.row) + Int(1) + if index % 3 == 1 { + height = collectionHeight + 300 + } + else if index % 3 == 2 { + height = collectionHeight + 300 * 2 + } + else { + height = collectionHeight + 300 * 3 + } + + cell.transform = CGAffineTransform(translationX: 0, y: height) + } else if !isCollectionViewScrollUp && contentOffsetY > 0.0 { + let index = Int(indexPath.row) + Int(1) + if index % 3 == 1 { + height = collectionHeight + 300 * 3 + } + else if index % 3 == 2 { + height = collectionHeight + 300 * 2 + } + else { + height = collectionHeight + 300 + } + + cell.transform = CGAffineTransform(translationX: 0, y: -height) + } + + UIView.animate(withDuration: 1, delay: 0.03, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: { + cell.transform = CGAffineTransform(translationX: 0, y: 0); + }, completion: nil) + +} + +func scrollViewDidScroll(_ scrollView: UIScrollView) { + let scrollVelocity:CGPoint = self.collectionView.panGestureRecognizer.velocity(in: self.collectionView?.superview) + if scrollVelocity.y > 0.0 { //ScrollDown + isCollectionViewScrollUp = false + } else if scrollVelocity.y < 0.0 { //ScrollUp + isCollectionViewScrollUp = true + } +} + +```" +1103899,"One of my friends is a real Linux fan, so I decided to try Ubuntu on a VM. I mostly enjoyed the experience, but it was very slow, which I assume is the fault VirtualBox, as my laptop has 16 gigs of ram and an i7 6500u. Partly out of a desire to make sure it works for me, and partly out of thinking ""this would be cool,"" I downloaded the Windows subsystem for Linux. It has official support from Microsoft, and it is specialized for just one OS, so I figured that it would be faster and closer to the performance I can expect were it my primary OS. However, it is only the terminal, not the full DE. Anyway, I had some fun with text-based programs like Lynx, but wanted more. With a few guides from the internet, I downloaded an X server to Windows, and got Ubuntu to use that. Now I can run Ubuntu apps mostly natively, interacting with other windows just like regular programs. However, this still is not how I would use Ubuntu; I want a desktop environment. I ran + +`sudo apt install ubuntu-desktop` and then `startx`, + +but that didn't work, throwing the error ""Fatal server error: +xf86OpenConsole: Switching VT failed."" Can anyone help? + +P.S. I know I could run both OS's partitioned, but putting that aside, it would be very cool to run Linux apps inside Windows.",2018/12/22,"['https://askubuntu.com/questions/1103899', 'https://askubuntu.com', 'https://askubuntu.com/users/906713/']","I would suggest that you install a lighter desktop than ubuntu in WSL. XFCE seems to work fine with WSL. + +``` +sudo apt update +sudo apt install xfce4 +startxfce4 + +```","If you only want to try Ubuntu I suggest running Ubuntu from USB stick (Ubuntu Live) + +* - You can try this tool to prepare USB stick. + +There also other options: + +* +* + +There You can try it without installing it on HDD. If You like it you can divide your drive into two partitions and on first install Windows, on second Linux and you can use both system on your computer." +37833775,"I wanted to find how many times 1 number appears in provided another number. I've found a solution for finding 2-digit numbers in another number, but what I wanted to do is to find 1-digit, 2-digit, ..., n-digit numbers in provided number. I dont want to create another case in switch instruction, so my question how can I avoid doing switch to make it work. Code below: + +``` +public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + System.out.println(""Provide number:""); + int number1 = sc.nextInt(); + + System.out.println(""Provide number you want to find in number1:""); + int number2 = sc.nextInt(); + + int counter = 0; + int digit = 1; + int a = 10; + + while(number2/a>0){ + digit++; + a = a*10; + } + + switch(digit){ + case 1:{ + while(number1 > 0 ){ + if(number1 % 10 == number2){ + counter++; + } + number1 = number1/10; + } + } + case 2:{ + while(number1 > 0){ + if(number1 % 100 == number2){ + counter++; + } + number1 = number1/10; + } + } + } + System.out.println(counter); +} + +``` + +Thanks for your help.",2016/06/15,"['https://Stackoverflow.com/questions/37833775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6469057/']","You have declared `i` inside of the `for` loop: + +``` +for(int i=0;i +using namespace std; + +int main() +{ + int temp,t,a[10]; + cin>>t; + for(int i=0;i>a[i]; + } + for(int i=0;ia[j]) + { + temp=a[i]; + a[i]=a[j]; + a[j]=temp; + } + } + } + for(int i=0;i0){ + digit++; + a = a*10; + } + + switch(digit){ + case 1:{ + while(number1 > 0 ){ + if(number1 % 10 == number2){ + counter++; + } + number1 = number1/10; + } + } + case 2:{ + while(number1 > 0){ + if(number1 % 100 == number2){ + counter++; + } + number1 = number1/10; + } + } + } + System.out.println(counter); +} + +``` + +Thanks for your help.",2016/06/15,"['https://Stackoverflow.com/questions/37833775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6469057/']","You have declared `i` inside of the `for` loop: + +``` +for(int i=0;i +using namespace std; + +int main() +{ + int temp,t,a[10]; + cin>>t; + for(int i=0;i>a[i]; + } + for(int i=0;ia[j]) + { + temp=a[i]; + a[i]=a[j]; + a[j]=temp; + } + } + } + for(int i=0;i0){ + digit++; + a = a*10; + } + + switch(digit){ + case 1:{ + while(number1 > 0 ){ + if(number1 % 10 == number2){ + counter++; + } + number1 = number1/10; + } + } + case 2:{ + while(number1 > 0){ + if(number1 % 100 == number2){ + counter++; + } + number1 = number1/10; + } + } + } + System.out.println(counter); +} + +``` + +Thanks for your help.",2016/06/15,"['https://Stackoverflow.com/questions/37833775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6469057/']","You have declared `i` inside of the `for` loop: + +``` +for(int i=0;i +using namespace std; + +int main() +{ + int temp,t,a[10]; + cin>>t; + for(int i=0;i>a[i]; + } + for(int i=0;ia[j]) + { + temp=a[i]; + a[i]=a[j]; + a[j]=temp; + } + } + } + for(int i=0;i +using namespace std; +int i = 0; +int a[10]; +int temp = a[i]; +int t; +int main() +{ + + cin>>t; + for(int i=0;i>a[i]; + } + for(i=0;ia[j]) + { + temp=a[i]; + a[i]=a[j]; + a[j]=temp; + } + } + } + for(i=0;i0){ + digit++; + a = a*10; + } + + switch(digit){ + case 1:{ + while(number1 > 0 ){ + if(number1 % 10 == number2){ + counter++; + } + number1 = number1/10; + } + } + case 2:{ + while(number1 > 0){ + if(number1 % 100 == number2){ + counter++; + } + number1 = number1/10; + } + } + } + System.out.println(counter); +} + +``` + +Thanks for your help.",2016/06/15,"['https://Stackoverflow.com/questions/37833775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6469057/']","You have declared `i` inside of the `for` loop: + +``` +for(int i=0;i +using namespace std; + +int main() +{ + int temp,t,a[10]; + cin>>t; + for(int i=0;i>a[i]; + } + for(int i=0;ia[j]) + { + temp=a[i]; + a[i]=a[j]; + a[j]=temp; + } + } + } + for(int i=0;i +using namespace std; + +int main() +{ + int temp, t, a[10]; + cin >> t; + + int i; + for(i=0; i> a[i]; + } + + for(i=0; ia[j]) + { + temp=a[i]; + a[i]=a[j]; + a[j]=temp; + } + } + } + + for(i=0; i` tag. + +``` +function function1() +{ +var country=document.getElementById('id1').value; +switch(country) +{ + case ""India"": + logo=""rupee.png""; + break; + case ""US"": + logo=""dollar-logo.png""; + break; + case ""Britan"": + logo=""yen.png""; + break; +} + +``` + +Now i want to display flag of country according to selection has made.. +Below is HTML file where i want to display image.. + +``` + + +``` + +I also tried this one.. + +``` +"" width=30 height=30> + +```",2014/11/03,"['https://Stackoverflow.com/questions/26717000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4147229/']","This is standard behavior in the Groovy shell, not peculiar to the Grails shell. You probably don't want to `def` the variable. See the following: + +``` +~ $ groovysh +Groovy Shell (2.3.4, JVM: 1.7.0_45) +Type ':help' or ':h' for help. +------------------------------------------------------------------------------- +groovy:000> def x = 42 +===> 42 +groovy:000> x +Unknown property: x +groovy:000> y = 2112 +===> 2112 +groovy:000> y +===> 2112 +groovy:000> + +``` + +From + +> +> **1.3.4. Variables** +> +> +> Shell variables are **all** untyped (ie. no `def` or other type information). +> +> +> This will set a shell variable: +> +> +> +> ``` +> foo = ""bar"" +> +> ``` +> +> But, this will evaluate a local variable and will **not** be saved to the shell’s environment: +> +> +> +> ``` +> def foo = ""bar"" +> +> ``` +> +> + +You can change this behaviour by enabling [interpreterMode](http://groovy-lang.org/groovysh.html#GroovyShell-InterpreterMode ""interpreterMode"") + +``` +groovy:000> := interpreterMode +groovy:000> def x = 42 +===> 42 +groovy:000> x +===> 42 +groovy:000> + +```","""def"" are more like compiled variables in Java way (to some degree), compiled (maybe type is unknown/dynamic, but name/existence of variable / property is known). + +`def xyz = 1` -> `Object xyz = 1;` + +Without ""def"" are added to specific container Binder by name, in fully dynamic manner. Imagine this like specific Map *(sorry for simplicity)* + +``` +binder[""xyz""] = 1; + +``` + +My personal filling is that Groovy doc don't illustrate this (huge) difference clearly. Word ""untyped"" seems to weak. +Implementation of ""storage"" for this two is totally different." +11134610,"I have a object A move with Velocity (v1, v2, v3) in 3D space. +Object position is (px,py,pz) +Now i want to add certain particles around object A (in radius dis) on plane which perpendicular to its Velocity direction. + +I find something call ""cross product"" but seen that no use in this case. + +Anyone can help? +I'm new to python and don't really know how to crack it.",2012/06/21,"['https://Stackoverflow.com/questions/11134610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1471511/']","The plane perpendicular to a vector ⟨A, B, C⟩ has the general equation Ax + By + Cz + K = 0.","Lets say we have a point p1, and we want to build a circle of points around it with radius r so that all points on the circle are orthogonal to a vector n.. here is a working example + +``` +p1 = np.array([-21.03181359, 4.54876345, 19.26943601]) +n = np.array([-0.06592715, 0.00713031, -0.26809672]) +n = n / np.linalg.norm(n) # normalise n +r = 0.5 + +x = np.array([1,0,0]).astype(np.float64) # take a random vector of magnitude 1 +x -= x.dot(n) * n / np.linalg.norm(n)**2 # make it orthogonal to n +x /= np.linalg.norm(x) # normalize + +# find first point on circle (x1). +# currently it has magnitude of 1, so we multiply it by the r +x1 = p1 + (x*r) + +# vector from lumen centre to first circle point +p1x1 = x1 - p1 + +def rotation_matrix(axis, theta): + """""" + Return the rotation matrix associated with counterclockwise rotation about + the given axis by theta radians. + """""" + axis = np.asarray(axis) + axis = axis / math.sqrt(np.dot(axis, axis)) + a = math.cos(theta / 2.0) + b, c, d = -axis * math.sin(theta / 2.0) + aa, bb, cc, dd = a * a, b * b, c * c, d * d + bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d + return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)], + [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)], + [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]]) + +# rotate the vector p1x1 around the axis n with angle theta +circle = [] +for theta in range(0,360,6): + circle_i = np.dot(rotation_matrix(n, np.deg2rad(theta)), p1x1) + circle.append(circle_i+p1) + +ax = axes3d.Axes3D(plt.figure(figsize=(10,10))) +ax.scatter3D(*np.array(circle).T, s=10, c='red') +ax.scatter3D(*p1.T, s=10, c='black') +ax.set_xlabel('X', size=40) +ax.set_ylabel('Y', size=40) +ax.set_zlabel('Z', size=40) + +ax.set_xlim(-19,-22) +ax.set_ylim(2,5) +ax.set_zlim(18,21) + +```" +11134610,"I have a object A move with Velocity (v1, v2, v3) in 3D space. +Object position is (px,py,pz) +Now i want to add certain particles around object A (in radius dis) on plane which perpendicular to its Velocity direction. + +I find something call ""cross product"" but seen that no use in this case. + +Anyone can help? +I'm new to python and don't really know how to crack it.",2012/06/21,"['https://Stackoverflow.com/questions/11134610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1471511/']","The equation of the plane is: + +``` +v1*(x-px) + v2*(y-py) + v3*(z-pz) = 0 + +``` + +When you know `(x,y)` you can find `z` and so on. + +Example: + +z = pz - (v1\*(x-px) + v2\*(y-py))/v3","Lets say we have a point p1, and we want to build a circle of points around it with radius r so that all points on the circle are orthogonal to a vector n.. here is a working example + +``` +p1 = np.array([-21.03181359, 4.54876345, 19.26943601]) +n = np.array([-0.06592715, 0.00713031, -0.26809672]) +n = n / np.linalg.norm(n) # normalise n +r = 0.5 + +x = np.array([1,0,0]).astype(np.float64) # take a random vector of magnitude 1 +x -= x.dot(n) * n / np.linalg.norm(n)**2 # make it orthogonal to n +x /= np.linalg.norm(x) # normalize + +# find first point on circle (x1). +# currently it has magnitude of 1, so we multiply it by the r +x1 = p1 + (x*r) + +# vector from lumen centre to first circle point +p1x1 = x1 - p1 + +def rotation_matrix(axis, theta): + """""" + Return the rotation matrix associated with counterclockwise rotation about + the given axis by theta radians. + """""" + axis = np.asarray(axis) + axis = axis / math.sqrt(np.dot(axis, axis)) + a = math.cos(theta / 2.0) + b, c, d = -axis * math.sin(theta / 2.0) + aa, bb, cc, dd = a * a, b * b, c * c, d * d + bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d + return np.array([[aa + bb - cc - dd, 2 * (bc + ad), 2 * (bd - ac)], + [2 * (bc - ad), aa + cc - bb - dd, 2 * (cd + ab)], + [2 * (bd + ac), 2 * (cd - ab), aa + dd - bb - cc]]) + +# rotate the vector p1x1 around the axis n with angle theta +circle = [] +for theta in range(0,360,6): + circle_i = np.dot(rotation_matrix(n, np.deg2rad(theta)), p1x1) + circle.append(circle_i+p1) + +ax = axes3d.Axes3D(plt.figure(figsize=(10,10))) +ax.scatter3D(*np.array(circle).T, s=10, c='red') +ax.scatter3D(*p1.T, s=10, c='black') +ax.set_xlabel('X', size=40) +ax.set_ylabel('Y', size=40) +ax.set_zlabel('Z', size=40) + +ax.set_xlim(-19,-22) +ax.set_ylim(2,5) +ax.set_zlim(18,21) + +```" +37384772,"I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online. + +This is my code for JSON request. + +``` +Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON) + .responseJSON { (request, response, result) in + hud.hide(true) + // Set flag to disale poor internet connection alert + weakInternet = false + print(result.error) + if (result.value != nil) { + print(""API Response: \(result.value!)"") + // Pass the response JSON to the completion block + completion(json: result.value!) + } else { + // Response JSON is NULL + } + } + +``` + +When i hit the same service with particular request parameters i am getting this response. + +``` +{""error"":""success"",""post_data"":{""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""password"":""himanshu"",""confirm_password"":""himanshu"",""companies"":[""Big Rattle Technologies_Fg_yes""],""institutes"":[""""]},""msg"":""success"",""data"":{""_id"":""5742ae1564b35e37369f0838"",""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""profile_pic"":"""",""loc"":[0,0],""locs"":{""type"":""Point"",""coordinates"":[0,0]},""institutes"":[],""companies"":[{""comapny_id"":""555b2d0a678e79ed510041ce"",""group_id"":""556c2434678e79a1820041dd"",""name"":""Big Rattle Technologies"",""designation"":""Fg"",""is_current"":""yes""}],""device_token"":"""",""user_group"":""site_user"",""is_verified"":0,""is_disclose"":1,""is_discover"":1,""wallNotification"":1,""messageNotification"":1,""matchNotification"":1,""verificationSent"":0,""status"":1,""mobile"":"""",""linkedin_id"":"""",""facebook_id"":"""",""os"":"""",""qblox_id"":12957726,""updated_at"":""2016-05-23 07:15:33"",""created_at"":""2016-05-23 07:15:33"",""current_company"":""Big Rattle Technologies""}} + +``` + +Anybody knows what is the problem in my case?",2016/05/23,"['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']","There is an issue with my web service. They are giving me the response in ""text/HTML"" format rather than HTML. When i printed my response on debugger then i got: + +``` +""Content-Type"" = ""text/html; charset=UTF-8""; + +``` + +Now, i updated my webservice and everything is working like a charm.","I am getting same error last time because there will be problem is web service returns me response in array and i am trying to convert its into dictionary and extract its value. + +Check Your web service response." +37384772,"I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online. + +This is my code for JSON request. + +``` +Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON) + .responseJSON { (request, response, result) in + hud.hide(true) + // Set flag to disale poor internet connection alert + weakInternet = false + print(result.error) + if (result.value != nil) { + print(""API Response: \(result.value!)"") + // Pass the response JSON to the completion block + completion(json: result.value!) + } else { + // Response JSON is NULL + } + } + +``` + +When i hit the same service with particular request parameters i am getting this response. + +``` +{""error"":""success"",""post_data"":{""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""password"":""himanshu"",""confirm_password"":""himanshu"",""companies"":[""Big Rattle Technologies_Fg_yes""],""institutes"":[""""]},""msg"":""success"",""data"":{""_id"":""5742ae1564b35e37369f0838"",""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""profile_pic"":"""",""loc"":[0,0],""locs"":{""type"":""Point"",""coordinates"":[0,0]},""institutes"":[],""companies"":[{""comapny_id"":""555b2d0a678e79ed510041ce"",""group_id"":""556c2434678e79a1820041dd"",""name"":""Big Rattle Technologies"",""designation"":""Fg"",""is_current"":""yes""}],""device_token"":"""",""user_group"":""site_user"",""is_verified"":0,""is_disclose"":1,""is_discover"":1,""wallNotification"":1,""messageNotification"":1,""matchNotification"":1,""verificationSent"":0,""status"":1,""mobile"":"""",""linkedin_id"":"""",""facebook_id"":"""",""os"":"""",""qblox_id"":12957726,""updated_at"":""2016-05-23 07:15:33"",""created_at"":""2016-05-23 07:15:33"",""current_company"":""Big Rattle Technologies""}} + +``` + +Anybody knows what is the problem in my case?",2016/05/23,"['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']","I am getting same error last time because there will be problem is web service returns me response in array and i am trying to convert its into dictionary and extract its value. + +Check Your web service response.","Swift 5, Swift 4 + +``` +var headers = HTTPHeaders() + headers = [ + ""Content-Type"" :""text/html; charset=UTF-8"", + //""Content-Type"": ""application/json"", + //""Content-Type"": ""application/x-www-form-urlencoded"", + //""Accept"": ""application/json"", + ""Accept"": ""multipart/form-data"" + ] + +```" +37384772,"I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online. + +This is my code for JSON request. + +``` +Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON) + .responseJSON { (request, response, result) in + hud.hide(true) + // Set flag to disale poor internet connection alert + weakInternet = false + print(result.error) + if (result.value != nil) { + print(""API Response: \(result.value!)"") + // Pass the response JSON to the completion block + completion(json: result.value!) + } else { + // Response JSON is NULL + } + } + +``` + +When i hit the same service with particular request parameters i am getting this response. + +``` +{""error"":""success"",""post_data"":{""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""password"":""himanshu"",""confirm_password"":""himanshu"",""companies"":[""Big Rattle Technologies_Fg_yes""],""institutes"":[""""]},""msg"":""success"",""data"":{""_id"":""5742ae1564b35e37369f0838"",""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""profile_pic"":"""",""loc"":[0,0],""locs"":{""type"":""Point"",""coordinates"":[0,0]},""institutes"":[],""companies"":[{""comapny_id"":""555b2d0a678e79ed510041ce"",""group_id"":""556c2434678e79a1820041dd"",""name"":""Big Rattle Technologies"",""designation"":""Fg"",""is_current"":""yes""}],""device_token"":"""",""user_group"":""site_user"",""is_verified"":0,""is_disclose"":1,""is_discover"":1,""wallNotification"":1,""messageNotification"":1,""matchNotification"":1,""verificationSent"":0,""status"":1,""mobile"":"""",""linkedin_id"":"""",""facebook_id"":"""",""os"":"""",""qblox_id"":12957726,""updated_at"":""2016-05-23 07:15:33"",""created_at"":""2016-05-23 07:15:33"",""current_company"":""Big Rattle Technologies""}} + +``` + +Anybody knows what is the problem in my case?",2016/05/23,"['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']","I am getting same error last time because there will be problem is web service returns me response in array and i am trying to convert its into dictionary and extract its value. + +Check Your web service response.","I got this error when using the **wrong** Firebase Server key to send a remote push notification. + +Go to `Firebase` > `Project Overview` > `CogIcon` > `Project Settings` > `Cloud Messaging` > `Server Key` + +[![enter image description here](https://i.stack.imgur.com/CLK8F.png)](https://i.stack.imgur.com/CLK8F.png) + +``` +guard let url = URL(string: ""https://fcm.googleapis.com/fcm/send"") else { return } + +var request = URLRequest(url: url) +request.httpMethod = ""POST"" +request.httpBody = try? + +let paramDict = [String:Any]() // this has values +JSONSerialization.data(withJSONObject: paramDict, options: []) +request.setValue(""application/json"", forHTTPHeaderField: ""Content-Type"") + +let serverKey = ""firebase server key"" // *** SERVER KEY USED HERE *** +request.setValue(""key=\(serverKey)"", forHTTPHeaderField: ""Authorization"") + +let task = URLSession.shared.dataTask(with: request) { (data, response, error) in + + do { + if let jsonData = data { + + if let jsonDataDict = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] { + print(""jsonData Successfully Sent data: \n\(jsonDataDict))"") + } + } + } catch let err as NSError { + print(""jsonData Error: \(err.debugDescription)"") + } +} +task.resume() + +```" +37384772,"I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online. + +This is my code for JSON request. + +``` +Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON) + .responseJSON { (request, response, result) in + hud.hide(true) + // Set flag to disale poor internet connection alert + weakInternet = false + print(result.error) + if (result.value != nil) { + print(""API Response: \(result.value!)"") + // Pass the response JSON to the completion block + completion(json: result.value!) + } else { + // Response JSON is NULL + } + } + +``` + +When i hit the same service with particular request parameters i am getting this response. + +``` +{""error"":""success"",""post_data"":{""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""password"":""himanshu"",""confirm_password"":""himanshu"",""companies"":[""Big Rattle Technologies_Fg_yes""],""institutes"":[""""]},""msg"":""success"",""data"":{""_id"":""5742ae1564b35e37369f0838"",""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""profile_pic"":"""",""loc"":[0,0],""locs"":{""type"":""Point"",""coordinates"":[0,0]},""institutes"":[],""companies"":[{""comapny_id"":""555b2d0a678e79ed510041ce"",""group_id"":""556c2434678e79a1820041dd"",""name"":""Big Rattle Technologies"",""designation"":""Fg"",""is_current"":""yes""}],""device_token"":"""",""user_group"":""site_user"",""is_verified"":0,""is_disclose"":1,""is_discover"":1,""wallNotification"":1,""messageNotification"":1,""matchNotification"":1,""verificationSent"":0,""status"":1,""mobile"":"""",""linkedin_id"":"""",""facebook_id"":"""",""os"":"""",""qblox_id"":12957726,""updated_at"":""2016-05-23 07:15:33"",""created_at"":""2016-05-23 07:15:33"",""current_company"":""Big Rattle Technologies""}} + +``` + +Anybody knows what is the problem in my case?",2016/05/23,"['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']","I am getting same error last time because there will be problem is web service returns me response in array and i am trying to convert its into dictionary and extract its value. + +Check Your web service response.",Make Sure The firewall Off from Server +37384772,"I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online. + +This is my code for JSON request. + +``` +Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON) + .responseJSON { (request, response, result) in + hud.hide(true) + // Set flag to disale poor internet connection alert + weakInternet = false + print(result.error) + if (result.value != nil) { + print(""API Response: \(result.value!)"") + // Pass the response JSON to the completion block + completion(json: result.value!) + } else { + // Response JSON is NULL + } + } + +``` + +When i hit the same service with particular request parameters i am getting this response. + +``` +{""error"":""success"",""post_data"":{""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""password"":""himanshu"",""confirm_password"":""himanshu"",""companies"":[""Big Rattle Technologies_Fg_yes""],""institutes"":[""""]},""msg"":""success"",""data"":{""_id"":""5742ae1564b35e37369f0838"",""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""profile_pic"":"""",""loc"":[0,0],""locs"":{""type"":""Point"",""coordinates"":[0,0]},""institutes"":[],""companies"":[{""comapny_id"":""555b2d0a678e79ed510041ce"",""group_id"":""556c2434678e79a1820041dd"",""name"":""Big Rattle Technologies"",""designation"":""Fg"",""is_current"":""yes""}],""device_token"":"""",""user_group"":""site_user"",""is_verified"":0,""is_disclose"":1,""is_discover"":1,""wallNotification"":1,""messageNotification"":1,""matchNotification"":1,""verificationSent"":0,""status"":1,""mobile"":"""",""linkedin_id"":"""",""facebook_id"":"""",""os"":"""",""qblox_id"":12957726,""updated_at"":""2016-05-23 07:15:33"",""created_at"":""2016-05-23 07:15:33"",""current_company"":""Big Rattle Technologies""}} + +``` + +Anybody knows what is the problem in my case?",2016/05/23,"['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']","There is an issue with my web service. They are giving me the response in ""text/HTML"" format rather than HTML. When i printed my response on debugger then i got: + +``` +""Content-Type"" = ""text/html; charset=UTF-8""; + +``` + +Now, i updated my webservice and everything is working like a charm.","Swift 5, Swift 4 + +``` +var headers = HTTPHeaders() + headers = [ + ""Content-Type"" :""text/html; charset=UTF-8"", + //""Content-Type"": ""application/json"", + //""Content-Type"": ""application/x-www-form-urlencoded"", + //""Accept"": ""application/json"", + ""Accept"": ""multipart/form-data"" + ] + +```" +37384772,"I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online. + +This is my code for JSON request. + +``` +Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON) + .responseJSON { (request, response, result) in + hud.hide(true) + // Set flag to disale poor internet connection alert + weakInternet = false + print(result.error) + if (result.value != nil) { + print(""API Response: \(result.value!)"") + // Pass the response JSON to the completion block + completion(json: result.value!) + } else { + // Response JSON is NULL + } + } + +``` + +When i hit the same service with particular request parameters i am getting this response. + +``` +{""error"":""success"",""post_data"":{""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""password"":""himanshu"",""confirm_password"":""himanshu"",""companies"":[""Big Rattle Technologies_Fg_yes""],""institutes"":[""""]},""msg"":""success"",""data"":{""_id"":""5742ae1564b35e37369f0838"",""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""profile_pic"":"""",""loc"":[0,0],""locs"":{""type"":""Point"",""coordinates"":[0,0]},""institutes"":[],""companies"":[{""comapny_id"":""555b2d0a678e79ed510041ce"",""group_id"":""556c2434678e79a1820041dd"",""name"":""Big Rattle Technologies"",""designation"":""Fg"",""is_current"":""yes""}],""device_token"":"""",""user_group"":""site_user"",""is_verified"":0,""is_disclose"":1,""is_discover"":1,""wallNotification"":1,""messageNotification"":1,""matchNotification"":1,""verificationSent"":0,""status"":1,""mobile"":"""",""linkedin_id"":"""",""facebook_id"":"""",""os"":"""",""qblox_id"":12957726,""updated_at"":""2016-05-23 07:15:33"",""created_at"":""2016-05-23 07:15:33"",""current_company"":""Big Rattle Technologies""}} + +``` + +Anybody knows what is the problem in my case?",2016/05/23,"['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']","There is an issue with my web service. They are giving me the response in ""text/HTML"" format rather than HTML. When i printed my response on debugger then i got: + +``` +""Content-Type"" = ""text/html; charset=UTF-8""; + +``` + +Now, i updated my webservice and everything is working like a charm.","I got this error when using the **wrong** Firebase Server key to send a remote push notification. + +Go to `Firebase` > `Project Overview` > `CogIcon` > `Project Settings` > `Cloud Messaging` > `Server Key` + +[![enter image description here](https://i.stack.imgur.com/CLK8F.png)](https://i.stack.imgur.com/CLK8F.png) + +``` +guard let url = URL(string: ""https://fcm.googleapis.com/fcm/send"") else { return } + +var request = URLRequest(url: url) +request.httpMethod = ""POST"" +request.httpBody = try? + +let paramDict = [String:Any]() // this has values +JSONSerialization.data(withJSONObject: paramDict, options: []) +request.setValue(""application/json"", forHTTPHeaderField: ""Content-Type"") + +let serverKey = ""firebase server key"" // *** SERVER KEY USED HERE *** +request.setValue(""key=\(serverKey)"", forHTTPHeaderField: ""Authorization"") + +let task = URLSession.shared.dataTask(with: request) { (data, response, error) in + + do { + if let jsonData = data { + + if let jsonDataDict = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] { + print(""jsonData Successfully Sent data: \n\(jsonDataDict))"") + } + } + } catch let err as NSError { + print(""jsonData Error: \(err.debugDescription)"") + } +} +task.resume() + +```" +37384772,"I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online. + +This is my code for JSON request. + +``` +Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON) + .responseJSON { (request, response, result) in + hud.hide(true) + // Set flag to disale poor internet connection alert + weakInternet = false + print(result.error) + if (result.value != nil) { + print(""API Response: \(result.value!)"") + // Pass the response JSON to the completion block + completion(json: result.value!) + } else { + // Response JSON is NULL + } + } + +``` + +When i hit the same service with particular request parameters i am getting this response. + +``` +{""error"":""success"",""post_data"":{""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""password"":""himanshu"",""confirm_password"":""himanshu"",""companies"":[""Big Rattle Technologies_Fg_yes""],""institutes"":[""""]},""msg"":""success"",""data"":{""_id"":""5742ae1564b35e37369f0838"",""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""profile_pic"":"""",""loc"":[0,0],""locs"":{""type"":""Point"",""coordinates"":[0,0]},""institutes"":[],""companies"":[{""comapny_id"":""555b2d0a678e79ed510041ce"",""group_id"":""556c2434678e79a1820041dd"",""name"":""Big Rattle Technologies"",""designation"":""Fg"",""is_current"":""yes""}],""device_token"":"""",""user_group"":""site_user"",""is_verified"":0,""is_disclose"":1,""is_discover"":1,""wallNotification"":1,""messageNotification"":1,""matchNotification"":1,""verificationSent"":0,""status"":1,""mobile"":"""",""linkedin_id"":"""",""facebook_id"":"""",""os"":"""",""qblox_id"":12957726,""updated_at"":""2016-05-23 07:15:33"",""created_at"":""2016-05-23 07:15:33"",""current_company"":""Big Rattle Technologies""}} + +``` + +Anybody knows what is the problem in my case?",2016/05/23,"['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']","There is an issue with my web service. They are giving me the response in ""text/HTML"" format rather than HTML. When i printed my response on debugger then i got: + +``` +""Content-Type"" = ""text/html; charset=UTF-8""; + +``` + +Now, i updated my webservice and everything is working like a charm.",Make Sure The firewall Off from Server +37384772,"I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online. + +This is my code for JSON request. + +``` +Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON) + .responseJSON { (request, response, result) in + hud.hide(true) + // Set flag to disale poor internet connection alert + weakInternet = false + print(result.error) + if (result.value != nil) { + print(""API Response: \(result.value!)"") + // Pass the response JSON to the completion block + completion(json: result.value!) + } else { + // Response JSON is NULL + } + } + +``` + +When i hit the same service with particular request parameters i am getting this response. + +``` +{""error"":""success"",""post_data"":{""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""password"":""himanshu"",""confirm_password"":""himanshu"",""companies"":[""Big Rattle Technologies_Fg_yes""],""institutes"":[""""]},""msg"":""success"",""data"":{""_id"":""5742ae1564b35e37369f0838"",""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""profile_pic"":"""",""loc"":[0,0],""locs"":{""type"":""Point"",""coordinates"":[0,0]},""institutes"":[],""companies"":[{""comapny_id"":""555b2d0a678e79ed510041ce"",""group_id"":""556c2434678e79a1820041dd"",""name"":""Big Rattle Technologies"",""designation"":""Fg"",""is_current"":""yes""}],""device_token"":"""",""user_group"":""site_user"",""is_verified"":0,""is_disclose"":1,""is_discover"":1,""wallNotification"":1,""messageNotification"":1,""matchNotification"":1,""verificationSent"":0,""status"":1,""mobile"":"""",""linkedin_id"":"""",""facebook_id"":"""",""os"":"""",""qblox_id"":12957726,""updated_at"":""2016-05-23 07:15:33"",""created_at"":""2016-05-23 07:15:33"",""current_company"":""Big Rattle Technologies""}} + +``` + +Anybody knows what is the problem in my case?",2016/05/23,"['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']","Swift 5, Swift 4 + +``` +var headers = HTTPHeaders() + headers = [ + ""Content-Type"" :""text/html; charset=UTF-8"", + //""Content-Type"": ""application/json"", + //""Content-Type"": ""application/x-www-form-urlencoded"", + //""Accept"": ""application/json"", + ""Accept"": ""multipart/form-data"" + ] + +```","I got this error when using the **wrong** Firebase Server key to send a remote push notification. + +Go to `Firebase` > `Project Overview` > `CogIcon` > `Project Settings` > `Cloud Messaging` > `Server Key` + +[![enter image description here](https://i.stack.imgur.com/CLK8F.png)](https://i.stack.imgur.com/CLK8F.png) + +``` +guard let url = URL(string: ""https://fcm.googleapis.com/fcm/send"") else { return } + +var request = URLRequest(url: url) +request.httpMethod = ""POST"" +request.httpBody = try? + +let paramDict = [String:Any]() // this has values +JSONSerialization.data(withJSONObject: paramDict, options: []) +request.setValue(""application/json"", forHTTPHeaderField: ""Content-Type"") + +let serverKey = ""firebase server key"" // *** SERVER KEY USED HERE *** +request.setValue(""key=\(serverKey)"", forHTTPHeaderField: ""Authorization"") + +let task = URLSession.shared.dataTask(with: request) { (data, response, error) in + + do { + if let jsonData = data { + + if let jsonDataDict = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] { + print(""jsonData Successfully Sent data: \n\(jsonDataDict))"") + } + } + } catch let err as NSError { + print(""jsonData Error: \(err.debugDescription)"") + } +} +task.resume() + +```" +37384772,"I am getting this error as JSON result.error. While my JSON is an valid one, check it on JSON vaildator online. + +This is my code for JSON request. + +``` +Alamofire.request(.POST, url, parameters: parameters, encoding:.JSON) + .responseJSON { (request, response, result) in + hud.hide(true) + // Set flag to disale poor internet connection alert + weakInternet = false + print(result.error) + if (result.value != nil) { + print(""API Response: \(result.value!)"") + // Pass the response JSON to the completion block + completion(json: result.value!) + } else { + // Response JSON is NULL + } + } + +``` + +When i hit the same service with particular request parameters i am getting this response. + +``` +{""error"":""success"",""post_data"":{""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""password"":""himanshu"",""confirm_password"":""himanshu"",""companies"":[""Big Rattle Technologies_Fg_yes""],""institutes"":[""""]},""msg"":""success"",""data"":{""_id"":""5742ae1564b35e37369f0838"",""first_name"":""hd"",""last_name"":""df"",""email"":""hiiaaaaaaa@dnsa.coma"",""profile_pic"":"""",""loc"":[0,0],""locs"":{""type"":""Point"",""coordinates"":[0,0]},""institutes"":[],""companies"":[{""comapny_id"":""555b2d0a678e79ed510041ce"",""group_id"":""556c2434678e79a1820041dd"",""name"":""Big Rattle Technologies"",""designation"":""Fg"",""is_current"":""yes""}],""device_token"":"""",""user_group"":""site_user"",""is_verified"":0,""is_disclose"":1,""is_discover"":1,""wallNotification"":1,""messageNotification"":1,""matchNotification"":1,""verificationSent"":0,""status"":1,""mobile"":"""",""linkedin_id"":"""",""facebook_id"":"""",""os"":"""",""qblox_id"":12957726,""updated_at"":""2016-05-23 07:15:33"",""created_at"":""2016-05-23 07:15:33"",""current_company"":""Big Rattle Technologies""}} + +``` + +Anybody knows what is the problem in my case?",2016/05/23,"['https://Stackoverflow.com/questions/37384772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6064629/']","Swift 5, Swift 4 + +``` +var headers = HTTPHeaders() + headers = [ + ""Content-Type"" :""text/html; charset=UTF-8"", + //""Content-Type"": ""application/json"", + //""Content-Type"": ""application/x-www-form-urlencoded"", + //""Accept"": ""application/json"", + ""Accept"": ""multipart/form-data"" + ] + +```",Make Sure The firewall Off from Server +48243,"This is probably something I don't understand since I am used to Windows +and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software. + +I mean, every application is run by a specific user, and that user will +only be able to run that applciation with his privilages, so if he has +no admin privileges, the application also won't be able to access unauthorized +directories etc. + +I want most of the time to work on my PC with a non-admin user since it seems +more safe to me, most of the time I have no need for admin privileges. +and even though I know viruses in linux are uncommon I still think the best +practice is to work on the computer in a state that you yourself can't +make any changes to important files, that way viruses also can't harm any important +files, but I need to install software for programming and web-design etc. +and first of all I don't want to switch users all the time. +But also it sounds safer to me that everything being done on the PC +will be done through the non-admin user. + +I'll be glad to know what misunderstanding I have here, cause +something here doesn't sound right.",2011/06/11,"['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']","Why you're asked for a password +------------------------------- + +Most software is designed to touch sensitive files, i.e. sensitive to the security of your private data or the systems integrity. This is why software installation is a potential risk and should be validated by a user who knows what he is doing. Even for open source Software you can not be sure that no bad code bits arrive with your percious new audio player until someone checked. And even then something could have been overlooked or packages could be manipulated on the way. Who knows what's hidden in the depth of the program? One user should. + +Ubuntu provides a comfortable way of installing software. Software developers can rely on that comfort and make the assumption that synaptic/software center/apt enables them to access these sensitive files. Canonical checks the software repository for bugs and malicious code. But the ultimate responsibility is yours. + +If the software in question does not need access to sensitive files, it can (in principle) be installed in the home folder though not in the Ubuntu way. You will for instance have to compile the source code yourself or run a custom install script. Beside the greater efforts of that it has the disadvantage of not allowing other users access to your just installed program (as they have no right to access your home-folder). They will need to installed it a second time. So this way of installation makes no sense in a large scale and in a small scale it's usually easier to type a password than to install software manually. + +So that's why Synaptic aaks for a password and why it's good that it does. + +--- + +Sudoers +------- + +**If you are really in dire need of having other users install software without password**, you can add them to the sudoers list. This however will result in **a great security risk**. If that doesn't concern you, consider that there a bot networks out there with great resources to break into your computer via Internet. They do this just to add your computer to the net and use it's connection and computing power without your knowledge to do all sorts of illegal stuff. They are not even after your personal data your you for that matter. They just want to hijack your PC. Still not concerned? Really? Then look at the following answer which is a small how-to on the workings of sudoers list: + +[How to make Ubuntu remember forever the password after the first time](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978) + +Read that carefully. You could lock yourself out of the system. + +### The scare is over + +So now you have the scare behind you are and taking the matter seriously, I can tell you it's really not that bad. If you trust the people working on your computer, and you don't have programs installed that allow remote access to your system (e.g. an ssh- or ftp-server), then it's really not that dangerous to disable the password stuff. Just don't do it without considering the worst case and think of your private data. + +--- + +Overlook on the proceedings (**don't do this lightly** - see text and [link above](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)): + +``` +# in shell type these commands +sudo su # in case you do something stupid, you'll have a root shell open +select-editor # (optional) will allow you to select text editor +visudo # secure way to open sudoers list + +``` + +An editor will open ADD a line like this: + +``` +confus confusion=(root) NOPASSWD:/usr/sbin/synaptic,/usr/bin/software-center + +``` + +Syntax explanation: `username machine=(usernameToRunCommandAs) command1,command2,...`. So the above line allows confus to run synaptic and softwarecenter as root without password query. You will still need to start it with `sudo synaptic` or `gksudo synaptic` or put an alias `alias synaptic='sudo synaptic' in your shell profile.","You touched upon a BIG difference between windows and ubuntu. In Windows when you are logged in as an admin programms will be installed without asking for a password. This enables also malware to run their programs. In Ubuntu (Linux) even being logged in as an admin the system will always ask for your password when you change the system. Therefore, malware cant intrude your system easily. To sum up run Ubuntu as an admin. If you open another user account for your kids than give them only normal user rights so they cant screw up the system." +48243,"This is probably something I don't understand since I am used to Windows +and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software. + +I mean, every application is run by a specific user, and that user will +only be able to run that applciation with his privilages, so if he has +no admin privileges, the application also won't be able to access unauthorized +directories etc. + +I want most of the time to work on my PC with a non-admin user since it seems +more safe to me, most of the time I have no need for admin privileges. +and even though I know viruses in linux are uncommon I still think the best +practice is to work on the computer in a state that you yourself can't +make any changes to important files, that way viruses also can't harm any important +files, but I need to install software for programming and web-design etc. +and first of all I don't want to switch users all the time. +But also it sounds safer to me that everything being done on the PC +will be done through the non-admin user. + +I'll be glad to know what misunderstanding I have here, cause +something here doesn't sound right.",2011/06/11,"['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']","Why you're asked for a password +------------------------------- + +Most software is designed to touch sensitive files, i.e. sensitive to the security of your private data or the systems integrity. This is why software installation is a potential risk and should be validated by a user who knows what he is doing. Even for open source Software you can not be sure that no bad code bits arrive with your percious new audio player until someone checked. And even then something could have been overlooked or packages could be manipulated on the way. Who knows what's hidden in the depth of the program? One user should. + +Ubuntu provides a comfortable way of installing software. Software developers can rely on that comfort and make the assumption that synaptic/software center/apt enables them to access these sensitive files. Canonical checks the software repository for bugs and malicious code. But the ultimate responsibility is yours. + +If the software in question does not need access to sensitive files, it can (in principle) be installed in the home folder though not in the Ubuntu way. You will for instance have to compile the source code yourself or run a custom install script. Beside the greater efforts of that it has the disadvantage of not allowing other users access to your just installed program (as they have no right to access your home-folder). They will need to installed it a second time. So this way of installation makes no sense in a large scale and in a small scale it's usually easier to type a password than to install software manually. + +So that's why Synaptic aaks for a password and why it's good that it does. + +--- + +Sudoers +------- + +**If you are really in dire need of having other users install software without password**, you can add them to the sudoers list. This however will result in **a great security risk**. If that doesn't concern you, consider that there a bot networks out there with great resources to break into your computer via Internet. They do this just to add your computer to the net and use it's connection and computing power without your knowledge to do all sorts of illegal stuff. They are not even after your personal data your you for that matter. They just want to hijack your PC. Still not concerned? Really? Then look at the following answer which is a small how-to on the workings of sudoers list: + +[How to make Ubuntu remember forever the password after the first time](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978) + +Read that carefully. You could lock yourself out of the system. + +### The scare is over + +So now you have the scare behind you are and taking the matter seriously, I can tell you it's really not that bad. If you trust the people working on your computer, and you don't have programs installed that allow remote access to your system (e.g. an ssh- or ftp-server), then it's really not that dangerous to disable the password stuff. Just don't do it without considering the worst case and think of your private data. + +--- + +Overlook on the proceedings (**don't do this lightly** - see text and [link above](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)): + +``` +# in shell type these commands +sudo su # in case you do something stupid, you'll have a root shell open +select-editor # (optional) will allow you to select text editor +visudo # secure way to open sudoers list + +``` + +An editor will open ADD a line like this: + +``` +confus confusion=(root) NOPASSWD:/usr/sbin/synaptic,/usr/bin/software-center + +``` + +Syntax explanation: `username machine=(usernameToRunCommandAs) command1,command2,...`. So the above line allows confus to run synaptic and softwarecenter as root without password query. You will still need to start it with `sudo synaptic` or `gksudo synaptic` or put an alias `alias synaptic='sudo synaptic' in your shell profile.","In Ubuntu, the administrator has root privileges (often referred as just ""root"", as in ""you need to be root""). + +Access to files can be split in three types: + +* read (numeric value 4) +* write (numeric value 2) +* execute (numeric value 1) + +These attributes can be set on every file or directory. Furthermore, these restrictions can be set on: + +* the owner of the file +* the group of the file (users can be a member of this group) +* all other users which are not the owner nor in the group + +These principles forms the basics of Linux file permissions. In windows, everything can be executed. Give it an `.cmd` or `.exe` extension for example. In Ubuntu, you need to add the execute bit explicitly, otherwise a permission error will be raised. + +When an user executes a program, the program accesses files as that user and these file permissions kicks in. By default, locations where programs are installed are privileged, only the owner can write. This owner is root. All other users can only read and execute the program, not write to it. That's why you need root privileges to install programs. + +Ubuntu has a special program called `sudo` (SuperUser DO ...) to run programs with root privileges. This can be used for installing software. When run, the `sudo` program asks you for your user password. Note that only members of the `admin` group can run programs as root using `sudo`. + +In Windows, you would go to a website and download an installer. Ubuntu works with a software repository in which you can search for programs and install those. These programs are reviewed before added to the official repositories, so you can be sure that no harmful intentions exist in the programs." +48243,"This is probably something I don't understand since I am used to Windows +and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software. + +I mean, every application is run by a specific user, and that user will +only be able to run that applciation with his privilages, so if he has +no admin privileges, the application also won't be able to access unauthorized +directories etc. + +I want most of the time to work on my PC with a non-admin user since it seems +more safe to me, most of the time I have no need for admin privileges. +and even though I know viruses in linux are uncommon I still think the best +practice is to work on the computer in a state that you yourself can't +make any changes to important files, that way viruses also can't harm any important +files, but I need to install software for programming and web-design etc. +and first of all I don't want to switch users all the time. +But also it sounds safer to me that everything being done on the PC +will be done through the non-admin user. + +I'll be glad to know what misunderstanding I have here, cause +something here doesn't sound right.",2011/06/11,"['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']","Non-admin users cannot install software because the packages run as root when they're installing as they install to privileged parts of the system, run maintainer scripts, etc. + +There is currently no way to tell the system ""Install firefox from this .deb but in a user's home directory so that it's isolated from the rest of the system""; which is why currently it's mostly an all or nothing affair. (This is also why running third party .debs is bad, the package and it's included scripts have root access to your system)","You can install software as a regular, non-admin, user. Software installed by a regular user will be ""owned"" by that user, which means that, in effect, it is an extension of the user -- it has no more permissions than the owning user does, though it may have fewer permissions, at the user's option. + +A common practice is for a user to create a 'bin' directory within their home directory. If /home/[user]/bin exists, it is added to the beginning of that user's path. You can place executable files in /home/[user]/bin, or in any other folder to which you have write and execute access, and execute the program from there. + +What a regular user can't do is install a package system-wide. A regular user can't put executable files in /usr/bin, for instance, nor grant them permissions that exceed the user's own permissions. This is, obviously, for basic security reasons -- you need admin permissions to reformat a hard drive, for instance, and you don't want someone unauthorized doing that. + +As far as I know, you cannot use package management software to install a software package unless you have admin permissions, as package management is done system-wide. + +However, without admin permissions, you can create shell scripts, write and compile source code, download and compile ""tarballs"", which are packages of source code for complex applications, or download executable files, so long as these can be used with only the permissions of a regular user. Some indie games, such as World of Goo or X-Plane 9, can be installed and used in this way." +48243,"This is probably something I don't understand since I am used to Windows +and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software. + +I mean, every application is run by a specific user, and that user will +only be able to run that applciation with his privilages, so if he has +no admin privileges, the application also won't be able to access unauthorized +directories etc. + +I want most of the time to work on my PC with a non-admin user since it seems +more safe to me, most of the time I have no need for admin privileges. +and even though I know viruses in linux are uncommon I still think the best +practice is to work on the computer in a state that you yourself can't +make any changes to important files, that way viruses also can't harm any important +files, but I need to install software for programming and web-design etc. +and first of all I don't want to switch users all the time. +But also it sounds safer to me that everything being done on the PC +will be done through the non-admin user. + +I'll be glad to know what misunderstanding I have here, cause +something here doesn't sound right.",2011/06/11,"['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']","In Ubuntu, the administrator has root privileges (often referred as just ""root"", as in ""you need to be root""). + +Access to files can be split in three types: + +* read (numeric value 4) +* write (numeric value 2) +* execute (numeric value 1) + +These attributes can be set on every file or directory. Furthermore, these restrictions can be set on: + +* the owner of the file +* the group of the file (users can be a member of this group) +* all other users which are not the owner nor in the group + +These principles forms the basics of Linux file permissions. In windows, everything can be executed. Give it an `.cmd` or `.exe` extension for example. In Ubuntu, you need to add the execute bit explicitly, otherwise a permission error will be raised. + +When an user executes a program, the program accesses files as that user and these file permissions kicks in. By default, locations where programs are installed are privileged, only the owner can write. This owner is root. All other users can only read and execute the program, not write to it. That's why you need root privileges to install programs. + +Ubuntu has a special program called `sudo` (SuperUser DO ...) to run programs with root privileges. This can be used for installing software. When run, the `sudo` program asks you for your user password. Note that only members of the `admin` group can run programs as root using `sudo`. + +In Windows, you would go to a website and download an installer. Ubuntu works with a software repository in which you can search for programs and install those. These programs are reviewed before added to the official repositories, so you can be sure that no harmful intentions exist in the programs.","You can install software as a regular, non-admin, user. Software installed by a regular user will be ""owned"" by that user, which means that, in effect, it is an extension of the user -- it has no more permissions than the owning user does, though it may have fewer permissions, at the user's option. + +A common practice is for a user to create a 'bin' directory within their home directory. If /home/[user]/bin exists, it is added to the beginning of that user's path. You can place executable files in /home/[user]/bin, or in any other folder to which you have write and execute access, and execute the program from there. + +What a regular user can't do is install a package system-wide. A regular user can't put executable files in /usr/bin, for instance, nor grant them permissions that exceed the user's own permissions. This is, obviously, for basic security reasons -- you need admin permissions to reformat a hard drive, for instance, and you don't want someone unauthorized doing that. + +As far as I know, you cannot use package management software to install a software package unless you have admin permissions, as package management is done system-wide. + +However, without admin permissions, you can create shell scripts, write and compile source code, download and compile ""tarballs"", which are packages of source code for complex applications, or download executable files, so long as these can be used with only the permissions of a regular user. Some indie games, such as World of Goo or X-Plane 9, can be installed and used in this way." +48243,"This is probably something I don't understand since I am used to Windows +and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software. + +I mean, every application is run by a specific user, and that user will +only be able to run that applciation with his privilages, so if he has +no admin privileges, the application also won't be able to access unauthorized +directories etc. + +I want most of the time to work on my PC with a non-admin user since it seems +more safe to me, most of the time I have no need for admin privileges. +and even though I know viruses in linux are uncommon I still think the best +practice is to work on the computer in a state that you yourself can't +make any changes to important files, that way viruses also can't harm any important +files, but I need to install software for programming and web-design etc. +and first of all I don't want to switch users all the time. +But also it sounds safer to me that everything being done on the PC +will be done through the non-admin user. + +I'll be glad to know what misunderstanding I have here, cause +something here doesn't sound right.",2011/06/11,"['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']","Why you're asked for a password +------------------------------- + +Most software is designed to touch sensitive files, i.e. sensitive to the security of your private data or the systems integrity. This is why software installation is a potential risk and should be validated by a user who knows what he is doing. Even for open source Software you can not be sure that no bad code bits arrive with your percious new audio player until someone checked. And even then something could have been overlooked or packages could be manipulated on the way. Who knows what's hidden in the depth of the program? One user should. + +Ubuntu provides a comfortable way of installing software. Software developers can rely on that comfort and make the assumption that synaptic/software center/apt enables them to access these sensitive files. Canonical checks the software repository for bugs and malicious code. But the ultimate responsibility is yours. + +If the software in question does not need access to sensitive files, it can (in principle) be installed in the home folder though not in the Ubuntu way. You will for instance have to compile the source code yourself or run a custom install script. Beside the greater efforts of that it has the disadvantage of not allowing other users access to your just installed program (as they have no right to access your home-folder). They will need to installed it a second time. So this way of installation makes no sense in a large scale and in a small scale it's usually easier to type a password than to install software manually. + +So that's why Synaptic aaks for a password and why it's good that it does. + +--- + +Sudoers +------- + +**If you are really in dire need of having other users install software without password**, you can add them to the sudoers list. This however will result in **a great security risk**. If that doesn't concern you, consider that there a bot networks out there with great resources to break into your computer via Internet. They do this just to add your computer to the net and use it's connection and computing power without your knowledge to do all sorts of illegal stuff. They are not even after your personal data your you for that matter. They just want to hijack your PC. Still not concerned? Really? Then look at the following answer which is a small how-to on the workings of sudoers list: + +[How to make Ubuntu remember forever the password after the first time](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978) + +Read that carefully. You could lock yourself out of the system. + +### The scare is over + +So now you have the scare behind you are and taking the matter seriously, I can tell you it's really not that bad. If you trust the people working on your computer, and you don't have programs installed that allow remote access to your system (e.g. an ssh- or ftp-server), then it's really not that dangerous to disable the password stuff. Just don't do it without considering the worst case and think of your private data. + +--- + +Overlook on the proceedings (**don't do this lightly** - see text and [link above](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)): + +``` +# in shell type these commands +sudo su # in case you do something stupid, you'll have a root shell open +select-editor # (optional) will allow you to select text editor +visudo # secure way to open sudoers list + +``` + +An editor will open ADD a line like this: + +``` +confus confusion=(root) NOPASSWD:/usr/sbin/synaptic,/usr/bin/software-center + +``` + +Syntax explanation: `username machine=(usernameToRunCommandAs) command1,command2,...`. So the above line allows confus to run synaptic and softwarecenter as root without password query. You will still need to start it with `sudo synaptic` or `gksudo synaptic` or put an alias `alias synaptic='sudo synaptic' in your shell profile.","They can not. Here is the deal. + +1. The 1st user created in Ubuntu is considered a special user: this is a user with administration permissions. This means when ever this user wants to do admin tasks he will be prompted for his admin password. Those tasks are issued by putting `sudo` in front of a command. +2. All other users (unless you change it yourself) are normal users and can not install sofware system wide unless the admin (1st user) lets them do so. +Normal user can only put things in their own home and if they want to they can mess up their home directory. + +This way 1 person is responsible for the system. + +You could make more than 1 user an admin (so able to install software) by adding those users to the sudoers file. + +Besides that they can install software in their home but this does depend on the software: sometimes the installer wants to add it to the system and that is not allowed. +These installs tend to be from source so it is not the easiest method ;)" +48243,"This is probably something I don't understand since I am used to Windows +and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software. + +I mean, every application is run by a specific user, and that user will +only be able to run that applciation with his privilages, so if he has +no admin privileges, the application also won't be able to access unauthorized +directories etc. + +I want most of the time to work on my PC with a non-admin user since it seems +more safe to me, most of the time I have no need for admin privileges. +and even though I know viruses in linux are uncommon I still think the best +practice is to work on the computer in a state that you yourself can't +make any changes to important files, that way viruses also can't harm any important +files, but I need to install software for programming and web-design etc. +and first of all I don't want to switch users all the time. +But also it sounds safer to me that everything being done on the PC +will be done through the non-admin user. + +I'll be glad to know what misunderstanding I have here, cause +something here doesn't sound right.",2011/06/11,"['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']","Why you're asked for a password +------------------------------- + +Most software is designed to touch sensitive files, i.e. sensitive to the security of your private data or the systems integrity. This is why software installation is a potential risk and should be validated by a user who knows what he is doing. Even for open source Software you can not be sure that no bad code bits arrive with your percious new audio player until someone checked. And even then something could have been overlooked or packages could be manipulated on the way. Who knows what's hidden in the depth of the program? One user should. + +Ubuntu provides a comfortable way of installing software. Software developers can rely on that comfort and make the assumption that synaptic/software center/apt enables them to access these sensitive files. Canonical checks the software repository for bugs and malicious code. But the ultimate responsibility is yours. + +If the software in question does not need access to sensitive files, it can (in principle) be installed in the home folder though not in the Ubuntu way. You will for instance have to compile the source code yourself or run a custom install script. Beside the greater efforts of that it has the disadvantage of not allowing other users access to your just installed program (as they have no right to access your home-folder). They will need to installed it a second time. So this way of installation makes no sense in a large scale and in a small scale it's usually easier to type a password than to install software manually. + +So that's why Synaptic aaks for a password and why it's good that it does. + +--- + +Sudoers +------- + +**If you are really in dire need of having other users install software without password**, you can add them to the sudoers list. This however will result in **a great security risk**. If that doesn't concern you, consider that there a bot networks out there with great resources to break into your computer via Internet. They do this just to add your computer to the net and use it's connection and computing power without your knowledge to do all sorts of illegal stuff. They are not even after your personal data your you for that matter. They just want to hijack your PC. Still not concerned? Really? Then look at the following answer which is a small how-to on the workings of sudoers list: + +[How to make Ubuntu remember forever the password after the first time](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978) + +Read that carefully. You could lock yourself out of the system. + +### The scare is over + +So now you have the scare behind you are and taking the matter seriously, I can tell you it's really not that bad. If you trust the people working on your computer, and you don't have programs installed that allow remote access to your system (e.g. an ssh- or ftp-server), then it's really not that dangerous to disable the password stuff. Just don't do it without considering the worst case and think of your private data. + +--- + +Overlook on the proceedings (**don't do this lightly** - see text and [link above](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)): + +``` +# in shell type these commands +sudo su # in case you do something stupid, you'll have a root shell open +select-editor # (optional) will allow you to select text editor +visudo # secure way to open sudoers list + +``` + +An editor will open ADD a line like this: + +``` +confus confusion=(root) NOPASSWD:/usr/sbin/synaptic,/usr/bin/software-center + +``` + +Syntax explanation: `username machine=(usernameToRunCommandAs) command1,command2,...`. So the above line allows confus to run synaptic and softwarecenter as root without password query. You will still need to start it with `sudo synaptic` or `gksudo synaptic` or put an alias `alias synaptic='sudo synaptic' in your shell profile.","You can install software as a regular, non-admin, user. Software installed by a regular user will be ""owned"" by that user, which means that, in effect, it is an extension of the user -- it has no more permissions than the owning user does, though it may have fewer permissions, at the user's option. + +A common practice is for a user to create a 'bin' directory within their home directory. If /home/[user]/bin exists, it is added to the beginning of that user's path. You can place executable files in /home/[user]/bin, or in any other folder to which you have write and execute access, and execute the program from there. + +What a regular user can't do is install a package system-wide. A regular user can't put executable files in /usr/bin, for instance, nor grant them permissions that exceed the user's own permissions. This is, obviously, for basic security reasons -- you need admin permissions to reformat a hard drive, for instance, and you don't want someone unauthorized doing that. + +As far as I know, you cannot use package management software to install a software package unless you have admin permissions, as package management is done system-wide. + +However, without admin permissions, you can create shell scripts, write and compile source code, download and compile ""tarballs"", which are packages of source code for complex applications, or download executable files, so long as these can be used with only the permissions of a regular user. Some indie games, such as World of Goo or X-Plane 9, can be installed and used in this way." +48243,"This is probably something I don't understand since I am used to Windows +and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software. + +I mean, every application is run by a specific user, and that user will +only be able to run that applciation with his privilages, so if he has +no admin privileges, the application also won't be able to access unauthorized +directories etc. + +I want most of the time to work on my PC with a non-admin user since it seems +more safe to me, most of the time I have no need for admin privileges. +and even though I know viruses in linux are uncommon I still think the best +practice is to work on the computer in a state that you yourself can't +make any changes to important files, that way viruses also can't harm any important +files, but I need to install software for programming and web-design etc. +and first of all I don't want to switch users all the time. +But also it sounds safer to me that everything being done on the PC +will be done through the non-admin user. + +I'll be glad to know what misunderstanding I have here, cause +something here doesn't sound right.",2011/06/11,"['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']","They can not. Here is the deal. + +1. The 1st user created in Ubuntu is considered a special user: this is a user with administration permissions. This means when ever this user wants to do admin tasks he will be prompted for his admin password. Those tasks are issued by putting `sudo` in front of a command. +2. All other users (unless you change it yourself) are normal users and can not install sofware system wide unless the admin (1st user) lets them do so. +Normal user can only put things in their own home and if they want to they can mess up their home directory. + +This way 1 person is responsible for the system. + +You could make more than 1 user an admin (so able to install software) by adding those users to the sudoers file. + +Besides that they can install software in their home but this does depend on the software: sometimes the installer wants to add it to the system and that is not allowed. +These installs tend to be from source so it is not the easiest method ;)","You can install software as a regular, non-admin, user. Software installed by a regular user will be ""owned"" by that user, which means that, in effect, it is an extension of the user -- it has no more permissions than the owning user does, though it may have fewer permissions, at the user's option. + +A common practice is for a user to create a 'bin' directory within their home directory. If /home/[user]/bin exists, it is added to the beginning of that user's path. You can place executable files in /home/[user]/bin, or in any other folder to which you have write and execute access, and execute the program from there. + +What a regular user can't do is install a package system-wide. A regular user can't put executable files in /usr/bin, for instance, nor grant them permissions that exceed the user's own permissions. This is, obviously, for basic security reasons -- you need admin permissions to reformat a hard drive, for instance, and you don't want someone unauthorized doing that. + +As far as I know, you cannot use package management software to install a software package unless you have admin permissions, as package management is done system-wide. + +However, without admin permissions, you can create shell scripts, write and compile source code, download and compile ""tarballs"", which are packages of source code for complex applications, or download executable files, so long as these can be used with only the permissions of a regular user. Some indie games, such as World of Goo or X-Plane 9, can be installed and used in this way." +48243,"This is probably something I don't understand since I am used to Windows +and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software. + +I mean, every application is run by a specific user, and that user will +only be able to run that applciation with his privilages, so if he has +no admin privileges, the application also won't be able to access unauthorized +directories etc. + +I want most of the time to work on my PC with a non-admin user since it seems +more safe to me, most of the time I have no need for admin privileges. +and even though I know viruses in linux are uncommon I still think the best +practice is to work on the computer in a state that you yourself can't +make any changes to important files, that way viruses also can't harm any important +files, but I need to install software for programming and web-design etc. +and first of all I don't want to switch users all the time. +But also it sounds safer to me that everything being done on the PC +will be done through the non-admin user. + +I'll be glad to know what misunderstanding I have here, cause +something here doesn't sound right.",2011/06/11,"['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']","Why you're asked for a password +------------------------------- + +Most software is designed to touch sensitive files, i.e. sensitive to the security of your private data or the systems integrity. This is why software installation is a potential risk and should be validated by a user who knows what he is doing. Even for open source Software you can not be sure that no bad code bits arrive with your percious new audio player until someone checked. And even then something could have been overlooked or packages could be manipulated on the way. Who knows what's hidden in the depth of the program? One user should. + +Ubuntu provides a comfortable way of installing software. Software developers can rely on that comfort and make the assumption that synaptic/software center/apt enables them to access these sensitive files. Canonical checks the software repository for bugs and malicious code. But the ultimate responsibility is yours. + +If the software in question does not need access to sensitive files, it can (in principle) be installed in the home folder though not in the Ubuntu way. You will for instance have to compile the source code yourself or run a custom install script. Beside the greater efforts of that it has the disadvantage of not allowing other users access to your just installed program (as they have no right to access your home-folder). They will need to installed it a second time. So this way of installation makes no sense in a large scale and in a small scale it's usually easier to type a password than to install software manually. + +So that's why Synaptic aaks for a password and why it's good that it does. + +--- + +Sudoers +------- + +**If you are really in dire need of having other users install software without password**, you can add them to the sudoers list. This however will result in **a great security risk**. If that doesn't concern you, consider that there a bot networks out there with great resources to break into your computer via Internet. They do this just to add your computer to the net and use it's connection and computing power without your knowledge to do all sorts of illegal stuff. They are not even after your personal data your you for that matter. They just want to hijack your PC. Still not concerned? Really? Then look at the following answer which is a small how-to on the workings of sudoers list: + +[How to make Ubuntu remember forever the password after the first time](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978) + +Read that carefully. You could lock yourself out of the system. + +### The scare is over + +So now you have the scare behind you are and taking the matter seriously, I can tell you it's really not that bad. If you trust the people working on your computer, and you don't have programs installed that allow remote access to your system (e.g. an ssh- or ftp-server), then it's really not that dangerous to disable the password stuff. Just don't do it without considering the worst case and think of your private data. + +--- + +Overlook on the proceedings (**don't do this lightly** - see text and [link above](https://askubuntu.com/questions/43969/how-to-make-ubuntu-remember-forever-the-password-after-the-first-time/43978#43978)): + +``` +# in shell type these commands +sudo su # in case you do something stupid, you'll have a root shell open +select-editor # (optional) will allow you to select text editor +visudo # secure way to open sudoers list + +``` + +An editor will open ADD a line like this: + +``` +confus confusion=(root) NOPASSWD:/usr/sbin/synaptic,/usr/bin/software-center + +``` + +Syntax explanation: `username machine=(usernameToRunCommandAs) command1,command2,...`. So the above line allows confus to run synaptic and softwarecenter as root without password query. You will still need to start it with `sudo synaptic` or `gksudo synaptic` or put an alias `alias synaptic='sudo synaptic' in your shell profile.","Non-admin users cannot install software because the packages run as root when they're installing as they install to privileged parts of the system, run maintainer scripts, etc. + +There is currently no way to tell the system ""Install firefox from this .deb but in a user's home directory so that it's isolated from the rest of the system""; which is why currently it's mostly an all or nothing affair. (This is also why running third party .debs is bad, the package and it's included scripts have root access to your system)" +48243,"This is probably something I don't understand since I am used to Windows +and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software. + +I mean, every application is run by a specific user, and that user will +only be able to run that applciation with his privilages, so if he has +no admin privileges, the application also won't be able to access unauthorized +directories etc. + +I want most of the time to work on my PC with a non-admin user since it seems +more safe to me, most of the time I have no need for admin privileges. +and even though I know viruses in linux are uncommon I still think the best +practice is to work on the computer in a state that you yourself can't +make any changes to important files, that way viruses also can't harm any important +files, but I need to install software for programming and web-design etc. +and first of all I don't want to switch users all the time. +But also it sounds safer to me that everything being done on the PC +will be done through the non-admin user. + +I'll be glad to know what misunderstanding I have here, cause +something here doesn't sound right.",2011/06/11,"['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']","Non-admin users cannot install software because the packages run as root when they're installing as they install to privileged parts of the system, run maintainer scripts, etc. + +There is currently no way to tell the system ""Install firefox from this .deb but in a user's home directory so that it's isolated from the rest of the system""; which is why currently it's mostly an all or nothing affair. (This is also why running third party .debs is bad, the package and it's included scripts have root access to your system)","You touched upon a BIG difference between windows and ubuntu. In Windows when you are logged in as an admin programms will be installed without asking for a password. This enables also malware to run their programs. In Ubuntu (Linux) even being logged in as an admin the system will always ask for your password when you change the system. Therefore, malware cant intrude your system easily. To sum up run Ubuntu as an admin. If you open another user account for your kids than give them only normal user rights so they cant screw up the system." +48243,"This is probably something I don't understand since I am used to Windows +and am only starting out with Ubuntu. I know that software in linux comes in packages what I don't understand is why can't non-admin users install software. + +I mean, every application is run by a specific user, and that user will +only be able to run that applciation with his privilages, so if he has +no admin privileges, the application also won't be able to access unauthorized +directories etc. + +I want most of the time to work on my PC with a non-admin user since it seems +more safe to me, most of the time I have no need for admin privileges. +and even though I know viruses in linux are uncommon I still think the best +practice is to work on the computer in a state that you yourself can't +make any changes to important files, that way viruses also can't harm any important +files, but I need to install software for programming and web-design etc. +and first of all I don't want to switch users all the time. +But also it sounds safer to me that everything being done on the PC +will be done through the non-admin user. + +I'll be glad to know what misunderstanding I have here, cause +something here doesn't sound right.",2011/06/11,"['https://askubuntu.com/questions/48243', 'https://askubuntu.com', 'https://askubuntu.com/users/19733/']","In Ubuntu, the administrator has root privileges (often referred as just ""root"", as in ""you need to be root""). + +Access to files can be split in three types: + +* read (numeric value 4) +* write (numeric value 2) +* execute (numeric value 1) + +These attributes can be set on every file or directory. Furthermore, these restrictions can be set on: + +* the owner of the file +* the group of the file (users can be a member of this group) +* all other users which are not the owner nor in the group + +These principles forms the basics of Linux file permissions. In windows, everything can be executed. Give it an `.cmd` or `.exe` extension for example. In Ubuntu, you need to add the execute bit explicitly, otherwise a permission error will be raised. + +When an user executes a program, the program accesses files as that user and these file permissions kicks in. By default, locations where programs are installed are privileged, only the owner can write. This owner is root. All other users can only read and execute the program, not write to it. That's why you need root privileges to install programs. + +Ubuntu has a special program called `sudo` (SuperUser DO ...) to run programs with root privileges. This can be used for installing software. When run, the `sudo` program asks you for your user password. Note that only members of the `admin` group can run programs as root using `sudo`. + +In Windows, you would go to a website and download an installer. Ubuntu works with a software repository in which you can search for programs and install those. These programs are reviewed before added to the official repositories, so you can be sure that no harmful intentions exist in the programs.","You touched upon a BIG difference between windows and ubuntu. In Windows when you are logged in as an admin programms will be installed without asking for a password. This enables also malware to run their programs. In Ubuntu (Linux) even being logged in as an admin the system will always ask for your password when you change the system. Therefore, malware cant intrude your system easily. To sum up run Ubuntu as an admin. If you open another user account for your kids than give them only normal user rights so they cant screw up the system." +22202342,"I have a calendar function, where I would like to call a column from my MySQL database. Before I am making the call for the column, I would just like to check if there is connection at all. My call goes through the servlet dataExchange.java. This servlet works fine, and I can put in information from my JSP page. In my database the format for the date is yyy-dd-mm. Therefore I have changed my JQuery calendar to have that format. That works fine and I get the alert box with the correct format, so it is the same as MySQL database. But I don't get the alert box, that the load was performed. Can anybody see why I don't get this call? + +Best Regards +Mads + +``` +
+ +
+ + + +```",2014/03/05,"['https://Stackoverflow.com/questions/22202342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1883095/']","You are trying to call your java class directcly `$.get(""dataExchange.java"" ...` You must use your URL mapping for the servlet. You can map the servlet in the `web.xml` file or with annotations. + +If you put your servlet an web.xml we can provide more help.","Answer: + +``` +$(function(){ + $(""#start"").datepicker({ + dateFormat: 'yy-mm-dd', + onSelect: function(dateText,inst){ + alert(dateText); + //Her skal du så lave din ajax kald: + $.ajax({ + url: ""../dataExchange"", + type: ""post"", + data: Date, + success: function(){ + alert(""success""); + $(""#result"").html('submitted successfully'); + }, + error:function(){ + alert(""failure""); + $(""#result"").html('there is error while submit'); + } + }); + } + }); +}); + +```" +34315485,"How do I manage to link from a given shiny part to parts that are located on other tabs/panels? + +Update +------ + +The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for). + +**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.** + +Example +------- + +I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked. + +The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app. + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + observeEvent(input$link_to_tabpanel_b, { + tags$a(href = ""#tab-4527-2"") + }) +} + +shinyApp(ui, server) + +```",2015/12/16,"['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']","The following solution is based on the inputs I got from the comments. + +Note that `updateTabsetPanel()` belongs to `shiny` while `updateTabItems()` is a function of the `shinydashboard` package. They seem to work interchangeably. + +``` +library(shiny) +library(shinydashboard) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + id = ""panels"", + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2""), + actionLink(""link_to_tabpanel_a"", ""Link to panel A"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { +# observeEvent(input$link_to_tabpanel_b, { +# tags$a(href = ""#tab-4527-2"") +# }) + observeEvent(input$link_to_tabpanel_b, { + newvalue <- ""B"" + updateTabItems(session, ""panels"", newvalue) + }) + observeEvent(input$link_to_tabpanel_a, { + newvalue <- ""A"" + updateTabsetPanel(session, ""panels"", newvalue) + }) +} + +shinyApp(ui, server) + +```","According to the code and logic from Rappster. It is possible to set any kind of links. Link to `TabsetPanel` can be used by `updataTabsetPanel`. Link to `Navbar` can use `updateNavbarPage(session, inputId, selected = NULL)`. These can be found by `?updateTabsetPanel` as following. + +``` +updateTabsetPanel(session, inputId, selected = NULL) + +updateNavbarPage(session, inputId, selected = NULL) + +updateNavlistPanel(session, inputId, selected = NULL) + +``` + +Please notice `selected` is the new id that you can define for `tabsetPanel`, `Navbar`, or `NavlistPanel`." +34315485,"How do I manage to link from a given shiny part to parts that are located on other tabs/panels? + +Update +------ + +The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for). + +**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.** + +Example +------- + +I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked. + +The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app. + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + observeEvent(input$link_to_tabpanel_b, { + tags$a(href = ""#tab-4527-2"") + }) +} + +shinyApp(ui, server) + +```",2015/12/16,"['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']","The following solution is based on the inputs I got from the comments. + +Note that `updateTabsetPanel()` belongs to `shiny` while `updateTabItems()` is a function of the `shinydashboard` package. They seem to work interchangeably. + +``` +library(shiny) +library(shinydashboard) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + id = ""panels"", + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2""), + actionLink(""link_to_tabpanel_a"", ""Link to panel A"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { +# observeEvent(input$link_to_tabpanel_b, { +# tags$a(href = ""#tab-4527-2"") +# }) + observeEvent(input$link_to_tabpanel_b, { + newvalue <- ""B"" + updateTabItems(session, ""panels"", newvalue) + }) + observeEvent(input$link_to_tabpanel_a, { + newvalue <- ""A"" + updateTabsetPanel(session, ""panels"", newvalue) + }) +} + +shinyApp(ui, server) + +```","We have just released a [routing library](https://github.com/Appsilon/shiny.router), which makes linking in Shiny easy. Here's how it looks like in a nutshell. + +``` +make_router( + route(""/main"", main_page_shiny_ui), + route(""/other"", other_page_shiny_ui) +) + +``` + +More information can be found in this [blog post](http://blog.appsilondatascience.com/rstats/2016/12/08/shiny.router.html)." +34315485,"How do I manage to link from a given shiny part to parts that are located on other tabs/panels? + +Update +------ + +The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for). + +**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.** + +Example +------- + +I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked. + +The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app. + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + observeEvent(input$link_to_tabpanel_b, { + tags$a(href = ""#tab-4527-2"") + }) +} + +shinyApp(ui, server) + +```",2015/12/16,"['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']","The following solution is based on the inputs I got from the comments. + +Note that `updateTabsetPanel()` belongs to `shiny` while `updateTabItems()` is a function of the `shinydashboard` package. They seem to work interchangeably. + +``` +library(shiny) +library(shinydashboard) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + id = ""panels"", + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2""), + actionLink(""link_to_tabpanel_a"", ""Link to panel A"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { +# observeEvent(input$link_to_tabpanel_b, { +# tags$a(href = ""#tab-4527-2"") +# }) + observeEvent(input$link_to_tabpanel_b, { + newvalue <- ""B"" + updateTabItems(session, ""panels"", newvalue) + }) + observeEvent(input$link_to_tabpanel_a, { + newvalue <- ""A"" + updateTabsetPanel(session, ""panels"", newvalue) + }) +} + +shinyApp(ui, server) + +```","You can give your `tabsetPanel` an id and use `updateTabsetPanel` with your `observeEvent` + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel(id = ""demo"", + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + observeEvent(input$link_to_tabpanel_b, { + updateTabsetPanel(session, ""demo"", ""B"") + }) +} + +shinyApp(ui, server) + +```" +34315485,"How do I manage to link from a given shiny part to parts that are located on other tabs/panels? + +Update +------ + +The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for). + +**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.** + +Example +------- + +I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked. + +The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app. + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + observeEvent(input$link_to_tabpanel_b, { + tags$a(href = ""#tab-4527-2"") + }) +} + +shinyApp(ui, server) + +```",2015/12/16,"['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']","The following solution is based on the inputs I got from the comments. + +Note that `updateTabsetPanel()` belongs to `shiny` while `updateTabItems()` is a function of the `shinydashboard` package. They seem to work interchangeably. + +``` +library(shiny) +library(shinydashboard) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + id = ""panels"", + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2""), + actionLink(""link_to_tabpanel_a"", ""Link to panel A"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { +# observeEvent(input$link_to_tabpanel_b, { +# tags$a(href = ""#tab-4527-2"") +# }) + observeEvent(input$link_to_tabpanel_b, { + newvalue <- ""B"" + updateTabItems(session, ""panels"", newvalue) + }) + observeEvent(input$link_to_tabpanel_a, { + newvalue <- ""A"" + updateTabsetPanel(session, ""panels"", newvalue) + }) +} + +shinyApp(ui, server) + +```","I was struggling with the same issue and really wanted to link to a different tab **via the URL**. Thanks to the [simple example of thesadie](https://stackoverflow.com/a/43125357/7061057) and by using an *observe* to parse inputs from the url, for me the following worked (and made it possible to switch the tab by adding */?tab=B* to the URL, e.g. http://localhost:1234/?tab=B): + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel(id = ""demo"", + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + # Allow url parsing + observe({ + query <- parseQueryString(session$clientData$url_search) + if (!is.null(query)) { + for (name in names(query)) { + if (name == ""tab"") { + # Change tab + try(updateTabsetPanel(session, ""demo"", selected = query[[name]])) + } else { + # Update inputs - this part is not really necessary if you just want to change the tabs, + # but I also needed to update other inputs from the url + try(updateTextInput(session, name, value = query[[name]]), silent = TRUE) + } + } + } + }) + + observeEvent(input$link_to_tabpanel_b, { + updateTabsetPanel(session, ""demo"", ""B"") + }) +} + +shinyApp(ui, server) + +```" +34315485,"How do I manage to link from a given shiny part to parts that are located on other tabs/panels? + +Update +------ + +The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for). + +**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.** + +Example +------- + +I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked. + +The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app. + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + observeEvent(input$link_to_tabpanel_b, { + tags$a(href = ""#tab-4527-2"") + }) +} + +shinyApp(ui, server) + +```",2015/12/16,"['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']","We have just released a [routing library](https://github.com/Appsilon/shiny.router), which makes linking in Shiny easy. Here's how it looks like in a nutshell. + +``` +make_router( + route(""/main"", main_page_shiny_ui), + route(""/other"", other_page_shiny_ui) +) + +``` + +More information can be found in this [blog post](http://blog.appsilondatascience.com/rstats/2016/12/08/shiny.router.html).","According to the code and logic from Rappster. It is possible to set any kind of links. Link to `TabsetPanel` can be used by `updataTabsetPanel`. Link to `Navbar` can use `updateNavbarPage(session, inputId, selected = NULL)`. These can be found by `?updateTabsetPanel` as following. + +``` +updateTabsetPanel(session, inputId, selected = NULL) + +updateNavbarPage(session, inputId, selected = NULL) + +updateNavlistPanel(session, inputId, selected = NULL) + +``` + +Please notice `selected` is the new id that you can define for `tabsetPanel`, `Navbar`, or `NavlistPanel`." +34315485,"How do I manage to link from a given shiny part to parts that are located on other tabs/panels? + +Update +------ + +The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for). + +**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.** + +Example +------- + +I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked. + +The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app. + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + observeEvent(input$link_to_tabpanel_b, { + tags$a(href = ""#tab-4527-2"") + }) +} + +shinyApp(ui, server) + +```",2015/12/16,"['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']","You can give your `tabsetPanel` an id and use `updateTabsetPanel` with your `observeEvent` + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel(id = ""demo"", + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + observeEvent(input$link_to_tabpanel_b, { + updateTabsetPanel(session, ""demo"", ""B"") + }) +} + +shinyApp(ui, server) + +```","According to the code and logic from Rappster. It is possible to set any kind of links. Link to `TabsetPanel` can be used by `updataTabsetPanel`. Link to `Navbar` can use `updateNavbarPage(session, inputId, selected = NULL)`. These can be found by `?updateTabsetPanel` as following. + +``` +updateTabsetPanel(session, inputId, selected = NULL) + +updateNavbarPage(session, inputId, selected = NULL) + +updateNavlistPanel(session, inputId, selected = NULL) + +``` + +Please notice `selected` is the new id that you can define for `tabsetPanel`, `Navbar`, or `NavlistPanel`." +34315485,"How do I manage to link from a given shiny part to parts that are located on other tabs/panels? + +Update +------ + +The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for). + +**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.** + +Example +------- + +I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked. + +The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app. + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + observeEvent(input$link_to_tabpanel_b, { + tags$a(href = ""#tab-4527-2"") + }) +} + +shinyApp(ui, server) + +```",2015/12/16,"['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']","I was struggling with the same issue and really wanted to link to a different tab **via the URL**. Thanks to the [simple example of thesadie](https://stackoverflow.com/a/43125357/7061057) and by using an *observe* to parse inputs from the url, for me the following worked (and made it possible to switch the tab by adding */?tab=B* to the URL, e.g. http://localhost:1234/?tab=B): + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel(id = ""demo"", + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + # Allow url parsing + observe({ + query <- parseQueryString(session$clientData$url_search) + if (!is.null(query)) { + for (name in names(query)) { + if (name == ""tab"") { + # Change tab + try(updateTabsetPanel(session, ""demo"", selected = query[[name]])) + } else { + # Update inputs - this part is not really necessary if you just want to change the tabs, + # but I also needed to update other inputs from the url + try(updateTextInput(session, name, value = query[[name]]), silent = TRUE) + } + } + } + }) + + observeEvent(input$link_to_tabpanel_b, { + updateTabsetPanel(session, ""demo"", ""B"") + }) +} + +shinyApp(ui, server) + +```","According to the code and logic from Rappster. It is possible to set any kind of links. Link to `TabsetPanel` can be used by `updataTabsetPanel`. Link to `Navbar` can use `updateNavbarPage(session, inputId, selected = NULL)`. These can be found by `?updateTabsetPanel` as following. + +``` +updateTabsetPanel(session, inputId, selected = NULL) + +updateNavbarPage(session, inputId, selected = NULL) + +updateNavlistPanel(session, inputId, selected = NULL) + +``` + +Please notice `selected` is the new id that you can define for `tabsetPanel`, `Navbar`, or `NavlistPanel`." +34315485,"How do I manage to link from a given shiny part to parts that are located on other tabs/panels? + +Update +------ + +The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for). + +**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.** + +Example +------- + +I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked. + +The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app. + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + observeEvent(input$link_to_tabpanel_b, { + tags$a(href = ""#tab-4527-2"") + }) +} + +shinyApp(ui, server) + +```",2015/12/16,"['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']","We have just released a [routing library](https://github.com/Appsilon/shiny.router), which makes linking in Shiny easy. Here's how it looks like in a nutshell. + +``` +make_router( + route(""/main"", main_page_shiny_ui), + route(""/other"", other_page_shiny_ui) +) + +``` + +More information can be found in this [blog post](http://blog.appsilondatascience.com/rstats/2016/12/08/shiny.router.html).","I was struggling with the same issue and really wanted to link to a different tab **via the URL**. Thanks to the [simple example of thesadie](https://stackoverflow.com/a/43125357/7061057) and by using an *observe* to parse inputs from the url, for me the following worked (and made it possible to switch the tab by adding */?tab=B* to the URL, e.g. http://localhost:1234/?tab=B): + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel(id = ""demo"", + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + # Allow url parsing + observe({ + query <- parseQueryString(session$clientData$url_search) + if (!is.null(query)) { + for (name in names(query)) { + if (name == ""tab"") { + # Change tab + try(updateTabsetPanel(session, ""demo"", selected = query[[name]])) + } else { + # Update inputs - this part is not really necessary if you just want to change the tabs, + # but I also needed to update other inputs from the url + try(updateTextInput(session, name, value = query[[name]]), silent = TRUE) + } + } + } + }) + + observeEvent(input$link_to_tabpanel_b, { + updateTabsetPanel(session, ""demo"", ""B"") + }) +} + +shinyApp(ui, server) + +```" +34315485,"How do I manage to link from a given shiny part to parts that are located on other tabs/panels? + +Update +------ + +The solution I drafted below works for the explicit case of linking to tabs/panels (and that's what I asked for). + +**However, I'd be interested to also know about more generic ways of linking parts of a shiny app.** + +Example +------- + +I'd like to link from panel A to panel B, but I'm not quite sure what I need to specify as an action when the action link in panel A is clicked. + +The value `#tab-4527-2` came from investigating the HTML output of `ui`, but I just saw that those values change each time I restart the app. + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel( + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + observeEvent(input$link_to_tabpanel_b, { + tags$a(href = ""#tab-4527-2"") + }) +} + +shinyApp(ui, server) + +```",2015/12/16,"['https://Stackoverflow.com/questions/34315485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989691/']","You can give your `tabsetPanel` an id and use `updateTabsetPanel` with your `observeEvent` + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel(id = ""demo"", + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + observeEvent(input$link_to_tabpanel_b, { + updateTabsetPanel(session, ""demo"", ""B"") + }) +} + +shinyApp(ui, server) + +```","I was struggling with the same issue and really wanted to link to a different tab **via the URL**. Thanks to the [simple example of thesadie](https://stackoverflow.com/a/43125357/7061057) and by using an *observe* to parse inputs from the url, for me the following worked (and made it possible to switch the tab by adding */?tab=B* to the URL, e.g. http://localhost:1234/?tab=B): + +``` +library(shiny) + +# UI --------------------------------------------------------------------- + +ui <- fluidPage( + tabsetPanel(id = ""demo"", + tabPanel( + ""A"", + p(), + actionLink(""link_to_tabpanel_b"", ""Link to panel B"") + ), + tabPanel( + ""B"", + h3(""Some information""), + tags$li(""Item 1""), + tags$li(""Item 2"") + ) + ) +) + +# Server ------------------------------------------------------------------ + +server <- function(input, output, session) { + # Allow url parsing + observe({ + query <- parseQueryString(session$clientData$url_search) + if (!is.null(query)) { + for (name in names(query)) { + if (name == ""tab"") { + # Change tab + try(updateTabsetPanel(session, ""demo"", selected = query[[name]])) + } else { + # Update inputs - this part is not really necessary if you just want to change the tabs, + # but I also needed to update other inputs from the url + try(updateTextInput(session, name, value = query[[name]]), silent = TRUE) + } + } + } + }) + + observeEvent(input$link_to_tabpanel_b, { + updateTabsetPanel(session, ""demo"", ""B"") + }) +} + +shinyApp(ui, server) + +```" +454341,"I built a computer for a friend with an OCZ petrol SSD. It seems to be having some problems now. Once or twice a day, it gets an error that looks like it's pointing to a disk sector and then blue screens. I booted off System Rescue CD to try and take a backup image of the disk, but it failed with an error along the lines of being unable to read a segment. The errors come totally at random, they don't seem to be associated with trying to read a certain file. The variance in uptime between faults is pretty large. + +I'd like to update the drive firmware at some stage, but first I want to have a full disk backup just in case anything goes wrong (took me a long time to get the computer correctly configured in the first place!). What sort of tool will work to back up the disk, and is the problem likely to be solved by a firmware update or am I going to have to RMA the drive?",2012/07/27,"['https://superuser.com/questions/454341', 'https://superuser.com', 'https://superuser.com/users/148667/']","According to [this article](http://alloytm.com/2010/01/05/virtualbox-regdb_e_classnotreg-error/), this can be fixed like so: + +> +> 1. Open a standard command line ( Run > cmd ) +> 2. Run: `cd C:\Program Files\Oracle\VirtualBox` +> 3. Run: `VBoxSVC /ReRegServer` +> 4. Run: `regsvr32 VBoxC.dll` +> +> +> + +Make sure to run the Command Prompt as an Administrator. + +But I find it confusing that this happens directly after installation. You may want to report this issue on the [VirtualBox Bugtracker](https://www.virtualbox.org/wiki/Bugtracker).","This error occurred with my win 7 64 bit too. + +I came to a conclusion that this problem occurred due to installation of youwave for android on my pc. + +They both have some conflicts so only any one can be installed at a time." +454341,"I built a computer for a friend with an OCZ petrol SSD. It seems to be having some problems now. Once or twice a day, it gets an error that looks like it's pointing to a disk sector and then blue screens. I booted off System Rescue CD to try and take a backup image of the disk, but it failed with an error along the lines of being unable to read a segment. The errors come totally at random, they don't seem to be associated with trying to read a certain file. The variance in uptime between faults is pretty large. + +I'd like to update the drive firmware at some stage, but first I want to have a full disk backup just in case anything goes wrong (took me a long time to get the computer correctly configured in the first place!). What sort of tool will work to back up the disk, and is the problem likely to be solved by a firmware update or am I going to have to RMA the drive?",2012/07/27,"['https://superuser.com/questions/454341', 'https://superuser.com', 'https://superuser.com/users/148667/']","According to [this article](http://alloytm.com/2010/01/05/virtualbox-regdb_e_classnotreg-error/), this can be fixed like so: + +> +> 1. Open a standard command line ( Run > cmd ) +> 2. Run: `cd C:\Program Files\Oracle\VirtualBox` +> 3. Run: `VBoxSVC /ReRegServer` +> 4. Run: `regsvr32 VBoxC.dll` +> +> +> + +Make sure to run the Command Prompt as an Administrator. + +But I find it confusing that this happens directly after installation. You may want to report this issue on the [VirtualBox Bugtracker](https://www.virtualbox.org/wiki/Bugtracker).","I have the same problem after de+reinstall VirtualBox. + +Good hint, Oliver Salzburg! It didn't work for me under Win10, but brought me closer to the solution: + +* Open start menu, right click on the `VirtualBox link` +* Click on `open file path` - explorer opens +* Right click on `VirtualBox link`, then `settings` +* Under `compatibility` click `settings for all users` button +* Check `execute program as administrator` +* ok-click all windows + +'Strings' may vary due to translation. + +Surprisingly (for me), `execute program as administrator` even makes a difference when using an admin account. This is also important for Oliver's solution (as I learned today after >15 years Windows experience." +454341,"I built a computer for a friend with an OCZ petrol SSD. It seems to be having some problems now. Once or twice a day, it gets an error that looks like it's pointing to a disk sector and then blue screens. I booted off System Rescue CD to try and take a backup image of the disk, but it failed with an error along the lines of being unable to read a segment. The errors come totally at random, they don't seem to be associated with trying to read a certain file. The variance in uptime between faults is pretty large. + +I'd like to update the drive firmware at some stage, but first I want to have a full disk backup just in case anything goes wrong (took me a long time to get the computer correctly configured in the first place!). What sort of tool will work to back up the disk, and is the problem likely to be solved by a firmware update or am I going to have to RMA the drive?",2012/07/27,"['https://superuser.com/questions/454341', 'https://superuser.com', 'https://superuser.com/users/148667/']","I have the same problem after de+reinstall VirtualBox. + +Good hint, Oliver Salzburg! It didn't work for me under Win10, but brought me closer to the solution: + +* Open start menu, right click on the `VirtualBox link` +* Click on `open file path` - explorer opens +* Right click on `VirtualBox link`, then `settings` +* Under `compatibility` click `settings for all users` button +* Check `execute program as administrator` +* ok-click all windows + +'Strings' may vary due to translation. + +Surprisingly (for me), `execute program as administrator` even makes a difference when using an admin account. This is also important for Oliver's solution (as I learned today after >15 years Windows experience.","This error occurred with my win 7 64 bit too. + +I came to a conclusion that this problem occurred due to installation of youwave for android on my pc. + +They both have some conflicts so only any one can be installed at a time." +14160928,"I am trying to draw some Kaplan-Meier curves using **ggplot2** and code found at: + +I had good results with this great code in a different database. However, in this case it gives me the following error... as if I had empty rows in my dataframe: + +`Error en if (nrow(layer_data) == 0) return() : argument is of length zero.` + +Previous questions about this type of error don't seem to be useful for me, as types of data and functions are not the same in my case. + +I am rather new to the statistical analysis using R and I don't have programming background, so I think this must be a 'dumb bug' in my data, but I can't found where it is… It definitely seems that ggplot2 can't find rows to plot. Please, could you help me in any way, with clues, suggestions.. etc? + +Here are my data and the code used, sequentially, ready for the console -I tried it in a knitr script-. At the end, I've posted my sessionInfo: + +``` +library(splines) +library(survival) +library(abind) +library(ggplot2) +library(grid) + +``` + +I create a data frame called **acbi30** (real data): + +``` +mort28day <- c(1,0,1,0,0,0,0,1,0,0,0,1,1,0,1,0,0,1,0,1,1,1,1,0,1,1,1,0,0,1) +daysurv <- c(4,29,24,29,29,29,29,19,29,29,29,3,9,29,15,29,29,11,29,5,13,20,22,29,16,21,9,29,29,15) +levo <- c(0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0) +acbi30 <- data.frame(mort28day, daysurv, levo) +save(acbi30, file=""acbi30.rda"") +acbi30 + +``` + +Then, I paste the following commands to create a function using ggplot2: + +``` +t.Surv <- Surv(acbi30$daysurv, acbi30$mort28day) +t.survfit <- survfit(t.Surv~1, data=acbi30) + +#define custom function to create a survival data.frame# +createSurvivalFrame <- function(f.survfit){ + +#initialise frame variable# +f.frame <- NULL + +#check if more then one strata# +if(length(names(f.survfit$strata)) == 0){ + +#create data.frame with data from survfit# +f.frame <- data.frame(time=f.survfit$time, n.risk=f.survfit$n.risk, n.event=f.survfit$n.event, n.censor = f.survfit +$n.censor, surv=f.survfit$surv, upper=f.survfit$upper, lower=f.survfit$lower) +#create first two rows (start at 1)# +f.start <- data.frame(time=c(0, f.frame$time[1]), n.risk=c(f.survfit$n, f.survfit$n), n.event=c(0,0), +n.censor=c(0,0), surv=c(1,1), upper=c(1,1), lower=c(1,1)) +#add first row to dataset# +f.frame <- rbind(f.start, f.frame) +#remove temporary data# +rm(f.start) +} +else { +#create vector for strata identification# +f.strata <- NULL +for(f.i in 1:length(f.survfit$strata)){ +#add vector for one strata according to number of rows of strata# +f.strata <- c(f.strata, rep(names(f.survfit$strata)[f.i], f.survfit$strata[f.i])) +} +#create data.frame with data from survfit (create column for strata)# +f.frame <- data.frame(time=f.survfit$time, n.risk=f.survfit$n.risk, n.event=f.survfit$n.event, n.censor = f.survfit +$n.censor, surv=f.survfit$surv, upper=f.survfit$upper, lower=f.survfit$lower, strata=factor(f.strata)) +#remove temporary data# +rm(f.strata) +#create first two rows (start at 1) for each strata# +for(f.i in 1:length(f.survfit$strata)){ +#take only subset for this strata from data# +f.subset <- subset(f.frame, strata==names(f.survfit$strata)[f.i]) +#create first two rows (time: 0, time of first event)# +f.start <- data.frame(time=c(0, f.subset$time[1]), n.risk=rep(f.survfit[f.i]$n, 2), n.event=c(0,0), +n.censor=c(0,0), surv=c(1,1), upper=c(1,1), lower=c(1,1), strata=rep(names(f.survfit$strata)[f.i], +2)) +#add first two rows to dataset# +f.frame <- rbind(f.start, f.frame) +#remove temporary data# +rm(f.start, f.subset) +} +#reorder data# +f.frame <- f.frame[order(f.frame$strata, f.frame$time), ] +#rename row.names# +rownames(f.frame) <- NULL +} +#return frame# +return(f.frame) +} + +#define custom function to draw kaplan-meier curve with ggplot# +qplot_survival <- function(f.frame, f.CI=""default"", f.shape=3){ +#use different plotting commands dependig whether or not strata's are given# +if(""strata"" %in% names(f.frame) == FALSE){ +#confidence intervals are drawn if not specified otherwise# +if(f.CI==""default"" | f.CI==TRUE ){ +#create plot with 4 layers (first 3 layers only events, last layer only censored)# +#hint: censoring data for multiple censoring events at timepoint are overplotted# +#(unlike in plot.survfit in survival package)# +ggplot(data=f.frame) + geom_step(aes(x=time, y=surv), direction=""hv"") + geom_step(aes(x=time, +y=upper), directions=""hv"", linetype=2) + geom_step(aes(x=time,y=lower), direction=""hv"", linetype=2) + +geom_point(data=subset(f.frame, n.censor==1), aes(x=time, y=surv), shape=f.shape) +} +else { +#create plot without confidence intervals# +ggplot(data=f.frame) + geom_step(aes(x=time, y=surv), direction=""hv"") + +geom_point(data=subset(f.frame, n.censor==1), aes(x=time, y=surv), shape=f.shape) +} +} +else { +if(f.CI==""default"" | f.CI==FALSE){ +#without CI# +ggplot(data=f.frame, aes(group=strata, colour=strata)) + geom_step(aes(x=time, y=surv), +direction=""hv"") + geom_point(data=subset(f.frame, n.censor==1), aes(x=time, y=surv), shape=f.shape) +} +else { +#with CI (hint: use alpha for CI)# +ggplot(data=f.frame, aes(colour=strata, group=strata)) + geom_step(aes(x=time, y=surv), +direction=""hv"") + geom_step(aes(x=time, y=upper), directions=""hv"", linetype=2, alpha=0.5) + +geom_step(aes(x=time,y=lower), direction=""hv"", linetype=2, alpha=0.5) + +geom_point(data=subset(f.frame, n.censor==1), aes(x=time, y=surv), shape=f.shape) +} +} +} + +``` + +**Plotting global survival curve (with 95% CI):** + +It doesn't give any errors: + +``` +# Kaplan-Meier plot, global survival (with CI) +t.survfit <- survfit(t.Surv~1, data=acbi30) +t.survframe <- createSurvivalFrame(t.survfit) +t.survfit +qplot_survival(t.survframe, TRUE, 20) + +``` + +**Plotting stratified survival curves:** + +Gives the error above mentioned: + +``` +# Kaplan-Meier plot, stratified survival +t.survfit2 <- survfit(t.Surv~levo, data=acbi30) +t.survframe2 <- createSurvivalFrame(t.survfit2) +t.survfit2 +qplot_survival(t.survframe2, TRUE, 20) + +``` + +**Plotting the results without ggplot2:** + +The structure of t.survframe2 seems OK to me, without any empty rows, so it must be a problem of qplot\_survival reading my data in *t.survframe2*. Making a simple plot doesn't return any error: + +``` +t.survframe2 +plot(t.survfit2) + +``` + +Where is the problem with my dataframe? The functions created work well with other datasets, but not with this one... + +Thank you in advance, + +Mareviv + +**Session info:** + +``` +sessionInfo() + +``` + +R version 2.15.2 (2012-10-26) +Platform: i386-w64-mingw32/i386 (32-bit) + +``` +locale: + +[1] LC_COLLATE=Spanish_Spain.1252 LC_CTYPE=Spanish_Spain.1252 +[3] LC_MONETARY=Spanish_Spain.1252 LC_NUMERIC=C +[5] LC_TIME=Spanish_Spain.1252 + +attached base packages: +[1] grid splines stats graphics grDevices utils datasets +[8] methods base + +other attached packages: +[1] ggplot2_0.9.3 abind_1.4-0 survival_2.36-14 knitr_0.8 + +loaded via a namespace (and not attached): + [1] colorspace_1.1-1 dichromat_1.2-4 digest_0.5.2 + [4] evaluate_0.4.2 formatR_0.7 gtable_0.1.2 + [7] labeling_0.1 MASS_7.3-22 munsell_0.4 +[10] plyr_1.8 proto_0.3-9.2 RColorBrewer_1.0-5 +[13] reshape2_1.2.1 scales_0.2.3 stringr_0.6.1 +[16] tools_2.15.2 + +```",2013/01/04,"['https://Stackoverflow.com/questions/14160928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1948108/']","I did a little cosmetic surgery on your `qplot_survival()` function. The main problem seemed to be your subset condition in the `data =` argument of `geom_point`; in both `t.survframe` and `t.survframe2`, a table of `n.censor` yielded values 0, 3 and 12. By changing the subset condition to `n.censor > 0`, I managed to get a plot in all cases. I also didn't see the point of `f.CI = ""default""`, so I set the default to TRUE and modified the if conditions accordingly. + +``` +qplot_survival <- function(f.frame, f.CI= TRUE, f.shape=3) +{ + # use different plotting commands depending whether + # or not strata are given# +if(!(""strata"" %in% names(f.frame))) +{ + #confidence intervals are drawn if not specified otherwise# + if( isTRUE(f.CI) ) + { + # create plot with 4 layers (first 3 layers only events, + # last layer only censored)# + # hint: censoring data for multiple censoring events at + # timepoint are overplotted# + # (unlike in plot.survfit in survival package)# + ggplot(data=f.frame) + + geom_step(aes(x=time, y=surv), direction=""hv"") + + geom_step(aes(x=time, y=upper), direction =""hv"", linetype=2) + + geom_step(aes(x=time,y=lower), direction=""hv"", linetype=2) + + geom_point(data=subset(f.frame, n.censor > 0), + aes(x=time, y=surv), shape=f.shape) + } else { + #create plot without confidence intervals# + ggplot(data=f.frame) + + geom_step(aes(x=time, y=surv), direction=""hv"") + + geom_point(data=subset(f.frame, n.censor > 0), + aes(x=time, y=surv), shape=f.shape) + } +} else { + if( !(isTRUE(f.CI)) ){ +#without CI# + ggplot(data=f.frame, aes(group=strata, colour=strata)) + + geom_step(aes(x=time, y=surv), direction=""hv"") + + geom_point(data=subset(f.frame, n.censor > 0), + aes(x=time, y=surv), shape=f.shape) +} else { + +#with CI (hint: use alpha for CI)# + ggplot(data=f.frame, aes(x = time, colour=strata, group=strata)) + + geom_step(aes(y=surv), direction=""hv"") + + geom_step(aes(y=upper), direction=""hv"", + linetype=2, alpha=0.5) + + geom_step(aes(y=lower), direction=""hv"", + linetype=2, alpha=0.5) + + geom_point(data=subset(f.frame, n.censor > 0), + aes(y=surv), shape=f.shape) + } + } +} + +``` + +The following plots all worked for me after making these changes: + +``` +qplot_survival(t.survframe2, TRUE, 20) +qplot_survival(t.survframe2, FALSE, 20) +qplot_survival(t.survframe, TRUE, 20) +qplot_survival(t.survframe, FALSE, 20) + +``` + +A couple of comments: + +1. Subsetting inside a function can be dangerous because sometimes, as in this case, satisfying the condition returns a zero-row data frame. I'd consider whether or not the `geom_point()` layer is really necessary. +2. In a couple of places, you had `directions = ""hv""` inside a `geom_step()` call. The argument is not pluralized and has been changed above. +3. This could be done a little more efficiently I think, but one way to extract the columns of interest from a `survfit` object, say `t.survfit`, is something like this: + +(Expand comps when strata are present) + +``` +comps <- c(2:6, 8, 10); +t.fit <- as.data.frame(do.call(cbind, lapply(comps, function(j) t.survfit[[j]]))) +names(t.fit) <- names(t.survfit)[comps] + +```","Here is another version that also accounts for the case when there are no censoring points in your data (@Dennis's version still fails in that case). This could be made more efficient, probably by creating a variable that stores how many censoring points there are in the entire dataframe upfront, and re-use that, rather than testing like I do again in each case. + +``` +# define custom function to draw kaplan-meier curve with ggplot +qplot_survival <- function(f.frame, f.CI=""default"", f.shape=3){ + # use different plotting commands dependig whether or not strata's are given + if(""strata"" %in% colnames(f.frame) == FALSE){ + # confidence intervals are drawn if not specified otherwise + if(f.CI==""default"" | f.CI==TRUE ){ + # create plot with 4 layers (first 3 layers only events, last layer only censored) + # hint: censoring data for multiple censoring events at timepoint are overplotted + + # (unlike in plot.survfit in survival package) + p <- ggplot(data=f.frame) + geom_step(aes(x=time, y=surv), direction=""hv"") + geom_step(aes(x=time, + y=upper), directions=""hv"", linetype=2) + geom_step(aes(x=time,y=lower), direction=""hv"", linetype=2) + if(nrow(subset(f.frame, n.censor > 0)) > 0){ + p+geom_point(data=subset(f.frame, n.censor > 0), aes(x=time, y=surv), shape=f.shape) + }else{ + p + } + } + else { + # create plot without confidence intervalls + p <- ggplot(data=f.frame) + geom_step(aes(x=time, y=surv), direction=""hv"") + if(nrow(subset(f.frame, n.censor > 0)) > 0){ + p + geom_point(data=subset(f.frame, n.censor > 0), aes(x=time, y=surv), shape=f.shape) + }else{ + p + } + } + } + else { + if(f.CI==""default"" | f.CI==FALSE){ + # without CI + p <- ggplot(data=f.frame, aes(group=strata, colour=strata)) + geom_step(aes(x=time, y=surv), + direction=""hv"") + if(nrow(subset(f.frame, n.censor > 0)) > 0){ + p +geom_point(data=subset(f.frame, n.censor > 0), aes(x=time, y=surv), shape=f.shape) + }else{ + p + } + } + else { + # with CI (hint: use alpha for CI) + p <- ggplot(data=f.frame, aes(colour=strata, group=strata)) + geom_step(aes(x=time, y=surv), + direction=""hv"") + geom_step(aes(x=time, y=upper), directions=""hv"", linetype=2, alpha=0.5) + + geom_step(aes(x=time,y=lower), direction=""hv"", linetype=2, alpha=0.5) + if(nrow(subset(f.frame, n.censor > 0)) > 0){ + p + geom_point(data=subset(f.frame, n.censor > 0), aes(x=time, y=surv), shape=f.shape) + }else{ + p + } + } + } +} + +```" +63196690,"A Worker Service is the new way to write a Windows service in .NET Core 3.x. The worker class extends [`Microsoft.Extensions.Hosting.BackgroundService`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.backgroundservice?view=dotnet-plat-ext-3.1) and implements `ExecuteAsync`. The documentation for that method says: + +> +> This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed. +> +> +> + +What should this method return when the work being done by the service is not a long-running operation in the usual sense, but event-driven? For example, I'm writing a service that sets up a [`FileSystemWatcher`](https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netcore-3.1). How would I encapsulate that in a `Task`? There's no `Task.Never()`, so should I just return something based on a very long `Task.Delay()` to prevent the service from shutting down? + +``` +private async Task DoStuffAsync(CancellationToken cancel) +{ + // register events + while(!cancel.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromDays(1000000), cancel); + } + // unregister events +} + +```",2020/07/31,"['https://Stackoverflow.com/questions/63196690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8773089/']","You could also use an actual infinite delay: + +``` +await Task.Delay(Timeout.Infinite, cancellationToken); + +```","I incorporated the delay into a method called `Eternity`: + +``` +private async Task Eternity(CancellationToken cancel) +{ + while (!cancel.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromDays(1), cancel); + } +} + +``` + +So my `ExecuteAsync` looks like: + +``` +protected override async Task ExecuteAsync(CancellationToken cancel) +{ + using (var watcher = new FileSystemWatcher()) + { + ConfigureWatcher(watcher); + await Eternity(cancel); + } +} + +``` + +This seems to work as expected." +63196690,"A Worker Service is the new way to write a Windows service in .NET Core 3.x. The worker class extends [`Microsoft.Extensions.Hosting.BackgroundService`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.backgroundservice?view=dotnet-plat-ext-3.1) and implements `ExecuteAsync`. The documentation for that method says: + +> +> This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed. +> +> +> + +What should this method return when the work being done by the service is not a long-running operation in the usual sense, but event-driven? For example, I'm writing a service that sets up a [`FileSystemWatcher`](https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netcore-3.1). How would I encapsulate that in a `Task`? There's no `Task.Never()`, so should I just return something based on a very long `Task.Delay()` to prevent the service from shutting down? + +``` +private async Task DoStuffAsync(CancellationToken cancel) +{ + // register events + while(!cancel.IsCancellationRequested) + { + await Task.Delay(TimeSpan.FromDays(1000000), cancel); + } + // unregister events +} + +```",2020/07/31,"['https://Stackoverflow.com/questions/63196690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8773089/']","You could also use an actual infinite delay: + +``` +await Task.Delay(Timeout.Infinite, cancellationToken); + +```","If you want to call it like `await ""Eternity""` or `await (""Eternity"", token)` if you want cancellation support. We can use them with cancellation support thanks to value tuples. + +Basically *you can await anything* with some extension methods. + +Here is the code: + +``` +protected override async Task ExecuteAsync(CancellationToken token) + { + using (var watcher = new FileSystemWatcher()) + { + ConfigureWatcher(watcher); + + // Use any of these methods you'd like + await ""Eternity""; + await (""Eternity"", token); + await TimeSpan.FromDays(1); + await (TimeSpan.FromDays(1), token); + } + } + +public static class GetAwaiterExtensions + { + public static TaskAwaiter GetAwaiter(this (TimeSpan, CancellationToken) valueTuple) + { + return Task.Delay((int) valueTuple.Item1.TotalMilliseconds, valueTuple.Item2) + .GetAwaiter(); + } + + public static TaskAwaiter GetAwaiter(this TimeSpan timeSpan) + { + return Task.Delay((int) timeSpan.TotalMilliseconds) + .GetAwaiter(); + } + + public static TaskAwaiter GetAwaiter(this string value) + { + if (value == ""Eternity"") + { + return Task.Delay(Timeout.Infinite) + .GetAwaiter(); + } + + throw new ArgumentException(); + } + + public static TaskAwaiter GetAwaiter(this (string, CancellationToken) valueTuple) + { + if (valueTuple.Item1 == ""Eternity"") + { + return Task + .Delay(Timeout.Infinite, cancellationToken: valueTuple.Item2) + .GetAwaiter(); + } + + throw new ArgumentException(); + } + } + +```" +23298393,"I tried many various methods, but didn't work.. What's wrong with my code? Please explain... help. My both images is transparent, with my idea on mouseover shoud fade new image. Current my code: + +[DEMO](http://jsbin.com/nipocete/1) +[DEMO2](http://jsbin.com/nipocete/1/edit) + +``` + + + + +
+ + +
+ +```",2014/04/25,"['https://Stackoverflow.com/questions/23298393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3573697/']","I believe to achieve your desired effect as I understand it you simply need to add a background to `img.a`. [Fiddle](http://jsfiddle.net/G8TB5/2/ ""Fiddle"") + +``` + img.a{ + position: absolute; + left: 0; + top: 0; + z-index: 10; + background:#fff; + } + +```","It seems to me you are doing the wrong thing. The img.b should have opacity 0 at :not(:hover) and opacity 1 at :hover, but all you are doing is setting the opacity of $(this) which is img.a + +Here is my re-work... I didn't use hover because I get confused with the syntax + +Here is my [fiddle/jsbin](http://jsbin.com/nipocete/14/edit) + +**HTML** + +``` + + +``` + +**CSS** + +``` +div.fadehover +{ + position: relative; +} + +img.a +{ + position: absolute; + left: 0; + top: 0; + z-index: 10; +} + +img.b +{ + position: absolute; + left: 0; + top: 0; + opacity: 0; +} + +``` + +**JS - using jQuery** + +``` +$(document).on('mouseenter', 'img.a', function() { + console.log('mouseenter'); + $(this).parent().next().find('.b').animate({""opacity"": ""1""}, ""slow""); +}); + +$(document).on('mouseleave', 'img.a', function() { + console.log('mouseleave'); + $(this).parent().next().find('.b').animate({""opacity"": ""0""}, ""slow""); +}); + +``` + +PS **ExceptionLimeCat** has found a very nice solution +1" +23298393,"I tried many various methods, but didn't work.. What's wrong with my code? Please explain... help. My both images is transparent, with my idea on mouseover shoud fade new image. Current my code: + +[DEMO](http://jsbin.com/nipocete/1) +[DEMO2](http://jsbin.com/nipocete/1/edit) + +``` + + + + +
+ + +
+ +```",2014/04/25,"['https://Stackoverflow.com/questions/23298393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3573697/']","I believe to achieve your desired effect as I understand it you simply need to add a background to `img.a`. [Fiddle](http://jsfiddle.net/G8TB5/2/ ""Fiddle"") + +``` + img.a{ + position: absolute; + left: 0; + top: 0; + z-index: 10; + background:#fff; + } + +```","ExceptionLimeCat solutions good but only for in bright/shiny/white backgrounds. +Jaka Dirnbek way is better, because is more optimal. + +Anyway.. Solved with this thing. But how this [Jaka Dirnbek](http://jsbin.com/nipocete/14/edit) jquery use on link? Example: + +``` +
+
    +
  • +
  • +
  • +
  • +
+
+ +``` + +CSS: + +``` +#nav_virsus { + position:absolute; + top:71px; + right:50px; +} + +#nav_virsus li +{ + font-family: 'Anaheim', sans-serif; + font-size:14px; + text-transform:uppercase; + float:left; + padding:20px; +} + +#nav_virsus li a +{ + color:#b8d9ff; + text-decoration:none; + padding:20px 5px 20px 5px; +} + +#nav_virsus li a:hover +{ + background:url(../images/hover.png) repeat-x; + color:#000; + text-decoration:none; + padding:21px 5px 20px 5px; +} + +```" +9533392,"Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this: + +``` +const char* give() +{ + return ""Hello, World!""; +} + +``` + +Would it be save to call the function and dereference the pointer simultaneously? + +Edit: Many answers. Will accept the first one who can show me the section out of the standard.",2012/03/02,"['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']","According to the standard: + +> +> C++11 1.10/3: The value of an object visible to a thread T at a particular point is the initial value of the object, a value assigned to the object by T, or a value assigned to the object by another thread, according to the rules below. +> +> +> + +A string literal, like any other constant object, cannot legally be assigned to; it has static storage duration, and so is initialised before the program starts; therefore, all threads will see its initial value at all times. + +Older standards had nothing to say about threads; so if your compiler doesn't support the C++11 threading model then you'll have to consult its documentation for any thread-safety guarantees. However, it's hard to imagine any implementation under which access to immutable objects were not thread-safe.","It is always safe to access immutable data from multiple threads. String literals are an example of immutable data (since it's illegal to modify them at run-time), so it is safe to access them from multiple threads." +9533392,"Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this: + +``` +const char* give() +{ + return ""Hello, World!""; +} + +``` + +Would it be save to call the function and dereference the pointer simultaneously? + +Edit: Many answers. Will accept the first one who can show me the section out of the standard.",2012/03/02,"['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']","Yes, it's safe. Why wouldn't it be? It would be unsafe if you'd try to modify the string, but that's illegal anyway.","As long as you only read data, you can access it from as many threads as you want. When data needs to be changed, that's when it gets complicated." +9533392,"Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this: + +``` +const char* give() +{ + return ""Hello, World!""; +} + +``` + +Would it be save to call the function and dereference the pointer simultaneously? + +Edit: Many answers. Will accept the first one who can show me the section out of the standard.",2012/03/02,"['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']","According to the standard: + +> +> C++11 1.10/3: The value of an object visible to a thread T at a particular point is the initial value of the object, a value assigned to the object by T, or a value assigned to the object by another thread, according to the rules below. +> +> +> + +A string literal, like any other constant object, cannot legally be assigned to; it has static storage duration, and so is initialised before the program starts; therefore, all threads will see its initial value at all times. + +Older standards had nothing to say about threads; so if your compiler doesn't support the C++11 threading model then you'll have to consult its documentation for any thread-safety guarantees. However, it's hard to imagine any implementation under which access to immutable objects were not thread-safe.","Yes, it's safe. Why wouldn't it be? It would be unsafe if you'd try to modify the string, but that's illegal anyway." +9533392,"Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this: + +``` +const char* give() +{ + return ""Hello, World!""; +} + +``` + +Would it be save to call the function and dereference the pointer simultaneously? + +Edit: Many answers. Will accept the first one who can show me the section out of the standard.",2012/03/02,"['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']","As long as you only read data, you can access it from as many threads as you want. When data needs to be changed, that's when it gets complicated.","String literals are (conceptually) stored in read only memory and initialised on loading (rather than at runtime). It's therefore safe to access them from multiple threads at any time. + +Note that more complex structures might not be initialised at load time, and so multiple thread access might have the possibility of issues immediately after the creation of the object. + +But string literals are completely safe." +9533392,"Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this: + +``` +const char* give() +{ + return ""Hello, World!""; +} + +``` + +Would it be save to call the function and dereference the pointer simultaneously? + +Edit: Many answers. Will accept the first one who can show me the section out of the standard.",2012/03/02,"['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']","It is always safe to access immutable data from multiple threads. String literals are an example of immutable data (since it's illegal to modify them at run-time), so it is safe to access them from multiple threads.","This depends on the implementation of the C Compiler. But I do not know of an implementation where concurrent read accesses might be unsafe, so in practice this is safe." +9533392,"Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this: + +``` +const char* give() +{ + return ""Hello, World!""; +} + +``` + +Would it be save to call the function and dereference the pointer simultaneously? + +Edit: Many answers. Will accept the first one who can show me the section out of the standard.",2012/03/02,"['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']","According to the standard: + +> +> C++11 1.10/3: The value of an object visible to a thread T at a particular point is the initial value of the object, a value assigned to the object by T, or a value assigned to the object by another thread, according to the rules below. +> +> +> + +A string literal, like any other constant object, cannot legally be assigned to; it has static storage duration, and so is initialised before the program starts; therefore, all threads will see its initial value at all times. + +Older standards had nothing to say about threads; so if your compiler doesn't support the C++11 threading model then you'll have to consult its documentation for any thread-safety guarantees. However, it's hard to imagine any implementation under which access to immutable objects were not thread-safe.","This depends on the implementation of the C Compiler. But I do not know of an implementation where concurrent read accesses might be unsafe, so in practice this is safe." +9533392,"Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this: + +``` +const char* give() +{ + return ""Hello, World!""; +} + +``` + +Would it be save to call the function and dereference the pointer simultaneously? + +Edit: Many answers. Will accept the first one who can show me the section out of the standard.",2012/03/02,"['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']","It is always safe to access immutable data from multiple threads. String literals are an example of immutable data (since it's illegal to modify them at run-time), so it is safe to access them from multiple threads.","As long as you only read data, you can access it from as many threads as you want. When data needs to be changed, that's when it gets complicated." +9533392,"Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this: + +``` +const char* give() +{ + return ""Hello, World!""; +} + +``` + +Would it be save to call the function and dereference the pointer simultaneously? + +Edit: Many answers. Will accept the first one who can show me the section out of the standard.",2012/03/02,"['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']","Yes, it's safe. Why wouldn't it be? It would be unsafe if you'd try to modify the string, but that's illegal anyway.","String literals are (conceptually) stored in read only memory and initialised on loading (rather than at runtime). It's therefore safe to access them from multiple threads at any time. + +Note that more complex structures might not be initialised at load time, and so multiple thread access might have the possibility of issues immediately after the creation of the object. + +But string literals are completely safe." +9533392,"Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this: + +``` +const char* give() +{ + return ""Hello, World!""; +} + +``` + +Would it be save to call the function and dereference the pointer simultaneously? + +Edit: Many answers. Will accept the first one who can show me the section out of the standard.",2012/03/02,"['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']","Yes, it's safe. Why wouldn't it be? It would be unsafe if you'd try to modify the string, but that's illegal anyway.","This depends on the implementation of the C Compiler. But I do not know of an implementation where concurrent read accesses might be unsafe, so in practice this is safe." +9533392,"Is it valid (defined behavior) to access a string literal simultaneously with multiple threads? Given a function like this: + +``` +const char* give() +{ + return ""Hello, World!""; +} + +``` + +Would it be save to call the function and dereference the pointer simultaneously? + +Edit: Many answers. Will accept the first one who can show me the section out of the standard.",2012/03/02,"['https://Stackoverflow.com/questions/9533392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/941699/']","According to the standard: + +> +> C++11 1.10/3: The value of an object visible to a thread T at a particular point is the initial value of the object, a value assigned to the object by T, or a value assigned to the object by another thread, according to the rules below. +> +> +> + +A string literal, like any other constant object, cannot legally be assigned to; it has static storage duration, and so is initialised before the program starts; therefore, all threads will see its initial value at all times. + +Older standards had nothing to say about threads; so if your compiler doesn't support the C++11 threading model then you'll have to consult its documentation for any thread-safety guarantees. However, it's hard to imagine any implementation under which access to immutable objects were not thread-safe.","String literals are (conceptually) stored in read only memory and initialised on loading (rather than at runtime). It's therefore safe to access them from multiple threads at any time. + +Note that more complex structures might not be initialised at load time, and so multiple thread access might have the possibility of issues immediately after the creation of the object. + +But string literals are completely safe." +52426582,"I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user. + +Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record? + +Below is the Code: + +``` +select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + + /* In case of queue is not there generate the new queue */ + if ($ads_queue === false) { + $output = $this->generateAdQueue(); + //In case of something went wrong while generating the queue + if ($output == false) { + return array(); + } + + //Now fetch the record again + $ads_queue = (new \yii\db\Query()) + ->select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + } + + /* Now, marked that one as is_sent */ + Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute(); + return $ads_queue; +} + +/** + * Below will Generate the Queue if not exist + */ +public function generateAdQueue() { + /* First check thatt there is existing queue, if so don't generate it */ + $data_exist = (new \yii\db\Query()) + ->select('ad_quque_id') + ->from('ad_banner_queue') + ->where('is_sent=0') + ->scalar(); + if ($data_exist === false) { + /* Delete all other entries */ + (new \yii\db\Query()) + ->createCommand() + ->delete('ad_banner_queue') + ->execute(); + + /* Fetch all banner */ + $ads = (new \yii\db\Query()) + ->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage') + ->from('advertisement') + ->where('status_id in (8)') //Means only fetch Approved ads + ->all(); + if (!empty($ads)) { + foreach ($ads as $ad) { + /* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */ + $ins_fields = array(); + for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) { + $ins_fields[] = array($ad['ad_id']); + } + Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute(); + } + return true; + } else { + return false; + } + } else { + return false; + } +} + +```",2018/09/20,"['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']","I'm taking it that you mean that different ""people"" that are conducting simultaneous requests should not get the same random row? The most robust way, without testing it, in order to avoid the minute chance of the same record being selected twice in two running requests will probably be to lock the table and perform the read and update in a transaction. You would have to use a storage engine that supports this, such as InnoDB. + +The way to accomplish `LOCK TABLES` and `UNLOCK TABLES` with transactional tables, such as InnoDB tables, is to begin a transaction with `SET autocommit = 0`, **not** `START TRANSACTION`, followed by `LOCK TABLES`. Then you should not call `UNLOCK TABLES` until you commit the transaction explicitly. + +For example, if you need to read and write to your table in one go, you can do this: + +``` +SET autocommit = 0; +LOCK TABLES ad_banner_queue AS ad_banner_queue_w WRITE, ad_banner_queue AS ad_banner_queue_r READ; +... perform your select query on ad_banner_queue_r, then update that row in ad_banner_queue_w with is_sent = 1... +COMMIT; +UNLOCK TABLES; + +``` + +The reason we lock with an alias is that you [cannot refer to a locked table multiple times in a single query using the same name](https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html). So we use aliases instead and obtain a separate lock for the table and each alias.",You should create a separate db table and mark ads that user received with its help. Before sending ads to user check if he has already received it. +52426582,"I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user. + +Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record? + +Below is the Code: + +``` +select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + + /* In case of queue is not there generate the new queue */ + if ($ads_queue === false) { + $output = $this->generateAdQueue(); + //In case of something went wrong while generating the queue + if ($output == false) { + return array(); + } + + //Now fetch the record again + $ads_queue = (new \yii\db\Query()) + ->select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + } + + /* Now, marked that one as is_sent */ + Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute(); + return $ads_queue; +} + +/** + * Below will Generate the Queue if not exist + */ +public function generateAdQueue() { + /* First check thatt there is existing queue, if so don't generate it */ + $data_exist = (new \yii\db\Query()) + ->select('ad_quque_id') + ->from('ad_banner_queue') + ->where('is_sent=0') + ->scalar(); + if ($data_exist === false) { + /* Delete all other entries */ + (new \yii\db\Query()) + ->createCommand() + ->delete('ad_banner_queue') + ->execute(); + + /* Fetch all banner */ + $ads = (new \yii\db\Query()) + ->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage') + ->from('advertisement') + ->where('status_id in (8)') //Means only fetch Approved ads + ->all(); + if (!empty($ads)) { + foreach ($ads as $ad) { + /* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */ + $ins_fields = array(); + for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) { + $ins_fields[] = array($ad['ad_id']); + } + Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute(); + } + return true; + } else { + return false; + } + } else { + return false; + } +} + +```",2018/09/20,"['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']","You may use [mutex](https://www.yiiframework.com/doc/api/2.0/yii-mutex-mutex) component to ensure that there is only one process trying to pop ad from queue. + +``` +$banner = []; +$key = __CLASS__ . '::generateAdQueue()' . serialize($params); +if (Yii::$app->mutex->acquire($key, 1)) { + $banner = $this->getBanner($params); + Yii::$app->mutex->release($key); +} + +``` + +However be aware that this may greatly reduce performance, especially if you want to process multiple request at the same time. You may consider different technology for such queue, relational databases does not really fit well for such task. Using Redis-based queue and [`SPOP`](https://redis.io/commands/spop) may be much better choice.","You can use transactions and SELECT FOR UPDATE construction for lock data and consistent executing of queries. For instance: + +``` +public function getAds() +{ + $db = Yii::$app->db; + $transaction = $db->beginTransaction(Transaction::REPEATABLE_READ); + try { + $ads_queue = (new \yii\db\Query()) + ->select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where(new Expression('is_sent=0 FOR UPDATE')) + ->orderBy('RAND()') + ->one(); + if ($ads_queue === false) { + $transaction->commit(); + return null; + } + $db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute(); + $transaction->commit(); + return $ads_queue; + } catch(Exception $e) { + $transaction->rollBack(); + throw $e; + } +} + +public function getBanner($params) +{ + $ads_queue = $this->getAds(); + if (is_null($ads_queue)) { + $output = $this->generateAdQueue(); + if ($output == false) { + return array(); + } + $ads_queue = $this->getAds(); + } + return $ads_queue; +} + +```" +52426582,"I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user. + +Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record? + +Below is the Code: + +``` +select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + + /* In case of queue is not there generate the new queue */ + if ($ads_queue === false) { + $output = $this->generateAdQueue(); + //In case of something went wrong while generating the queue + if ($output == false) { + return array(); + } + + //Now fetch the record again + $ads_queue = (new \yii\db\Query()) + ->select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + } + + /* Now, marked that one as is_sent */ + Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute(); + return $ads_queue; +} + +/** + * Below will Generate the Queue if not exist + */ +public function generateAdQueue() { + /* First check thatt there is existing queue, if so don't generate it */ + $data_exist = (new \yii\db\Query()) + ->select('ad_quque_id') + ->from('ad_banner_queue') + ->where('is_sent=0') + ->scalar(); + if ($data_exist === false) { + /* Delete all other entries */ + (new \yii\db\Query()) + ->createCommand() + ->delete('ad_banner_queue') + ->execute(); + + /* Fetch all banner */ + $ads = (new \yii\db\Query()) + ->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage') + ->from('advertisement') + ->where('status_id in (8)') //Means only fetch Approved ads + ->all(); + if (!empty($ads)) { + foreach ($ads as $ad) { + /* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */ + $ins_fields = array(); + for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) { + $ins_fields[] = array($ad['ad_id']); + } + Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute(); + } + return true; + } else { + return false; + } + } else { + return false; + } +} + +```",2018/09/20,"['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']","I'm taking it that you mean that different ""people"" that are conducting simultaneous requests should not get the same random row? The most robust way, without testing it, in order to avoid the minute chance of the same record being selected twice in two running requests will probably be to lock the table and perform the read and update in a transaction. You would have to use a storage engine that supports this, such as InnoDB. + +The way to accomplish `LOCK TABLES` and `UNLOCK TABLES` with transactional tables, such as InnoDB tables, is to begin a transaction with `SET autocommit = 0`, **not** `START TRANSACTION`, followed by `LOCK TABLES`. Then you should not call `UNLOCK TABLES` until you commit the transaction explicitly. + +For example, if you need to read and write to your table in one go, you can do this: + +``` +SET autocommit = 0; +LOCK TABLES ad_banner_queue AS ad_banner_queue_w WRITE, ad_banner_queue AS ad_banner_queue_r READ; +... perform your select query on ad_banner_queue_r, then update that row in ad_banner_queue_w with is_sent = 1... +COMMIT; +UNLOCK TABLES; + +``` + +The reason we lock with an alias is that you [cannot refer to a locked table multiple times in a single query using the same name](https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html). So we use aliases instead and obtain a separate lock for the table and each alias.","Make your index unique or make a check that checks the data and see's if it is a duplicate. + +Hope this helps. Good luck" +52426582,"I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user. + +Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record? + +Below is the Code: + +``` +select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + + /* In case of queue is not there generate the new queue */ + if ($ads_queue === false) { + $output = $this->generateAdQueue(); + //In case of something went wrong while generating the queue + if ($output == false) { + return array(); + } + + //Now fetch the record again + $ads_queue = (new \yii\db\Query()) + ->select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + } + + /* Now, marked that one as is_sent */ + Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute(); + return $ads_queue; +} + +/** + * Below will Generate the Queue if not exist + */ +public function generateAdQueue() { + /* First check thatt there is existing queue, if so don't generate it */ + $data_exist = (new \yii\db\Query()) + ->select('ad_quque_id') + ->from('ad_banner_queue') + ->where('is_sent=0') + ->scalar(); + if ($data_exist === false) { + /* Delete all other entries */ + (new \yii\db\Query()) + ->createCommand() + ->delete('ad_banner_queue') + ->execute(); + + /* Fetch all banner */ + $ads = (new \yii\db\Query()) + ->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage') + ->from('advertisement') + ->where('status_id in (8)') //Means only fetch Approved ads + ->all(); + if (!empty($ads)) { + foreach ($ads as $ad) { + /* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */ + $ins_fields = array(); + for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) { + $ins_fields[] = array($ad['ad_id']); + } + Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute(); + } + return true; + } else { + return false; + } + } else { + return false; + } +} + +```",2018/09/20,"['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']","Although it might seem to be a trivial question it is not at all, there are several ways to handle it and each of them has its own downsides, mainly you can face this issue from three different points: + +Live with it +============ + +Chances you can get a repeated pull are low in real life and you need to really think if you are willing to face the extra work just to make sure an ad is not shown twice in a row, you also need to think caches exist and you might break your brain making ads atomic just to find out browser/proxy/cache are serving a repeated ad :( + +Handle it on database +===================== + +You can handle this issue leaving the database the responsability to keep data safe and coherent(indeed it is the main task of database), there are several ways of doing it: + +* **Locks and table** (as previously suggested), I personally disklike the approach of using locks with PHP and MySQL, you will suffer performance penalities and risk deadlocking but anyway it's still a solution, you just make a select for update on your queue table to be sure no-one reads again until you update. The problem in here is you will lock the whole table while this is done and you need to be careful with your DB Driver and autocommits. +* **Cursors** Cursors are database structures created basically for the duty you are willing to do, you create a cursor and safely traverse it with [its functions](https://dev.mysql.com/doc/refman/5.7/en/cursors.html). Using cursors into PHP might be very tricky due to transactions too and you need to know very well what are you doing to avoid errors. +* **Cursors and stored procedures** the best way to handle this into database is managing cursors inside the database itself, that's why stored procedures are there, just create procedures to pull a new item from your cursor and to fill it again once it's all consumed. + +Handle it on PHP side +===================== + +In this case you need to implement your own queue on PHP and there might be several ways to do so but the main problem might be implementing multiprocess-safe atomic operations on your app, I personally dislike using any kind of locks if you are not 100% sure of the execution flow of your app or you might end up locking it all. Anyway there are three chances in here: + +* **Use sems or mutex** both included on php or third party, timeouts and locks can become a hell and they are not easy to detect so as stated above I'd avoid it. +* **[Use PHP MSG Queue](https://secure.php.net/manual/en/function.msg-get-queue.php)** I think this is the safest way as long as you run your app on a \*nix system, just send all the available ads to the message queue instead of creating a table on database, once all ads are consumed you can regenerate the queue once again, the drawback of this system is your server can not be distributed and you might lose the current queue status if you don't save it before a restart. +* **Third party queue system** depending on your app workload or interactions you might need to use a queue management system, this is a must if you want a distributed system, it might sound too serious using a msg queue system to handle this issue but this kind of approaches may be life-savers. + +Summary +======= + +If you can't live with it and are proficient enough with databases i'd go for stored procedures and cursors, you don't need to break your mind with concurrency, database will handle it as long as you are using an ACID compliant database (not MyISAM i.e.) + +If you want to avoid conding into the database and your system is \*nix and not going to be distributed you can give a try to msg\_queues + +If you think your system may be sometime distributed or do not rely on old SysV mechanisms you can give a try to a message broker like RabbitMQ, this nice things are addictive and once you start using them you start seeing new uses for them daily.","You may use [mutex](https://www.yiiframework.com/doc/api/2.0/yii-mutex-mutex) component to ensure that there is only one process trying to pop ad from queue. + +``` +$banner = []; +$key = __CLASS__ . '::generateAdQueue()' . serialize($params); +if (Yii::$app->mutex->acquire($key, 1)) { + $banner = $this->getBanner($params); + Yii::$app->mutex->release($key); +} + +``` + +However be aware that this may greatly reduce performance, especially if you want to process multiple request at the same time. You may consider different technology for such queue, relational databases does not really fit well for such task. Using Redis-based queue and [`SPOP`](https://redis.io/commands/spop) may be much better choice." +52426582,"I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user. + +Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record? + +Below is the Code: + +``` +select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + + /* In case of queue is not there generate the new queue */ + if ($ads_queue === false) { + $output = $this->generateAdQueue(); + //In case of something went wrong while generating the queue + if ($output == false) { + return array(); + } + + //Now fetch the record again + $ads_queue = (new \yii\db\Query()) + ->select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + } + + /* Now, marked that one as is_sent */ + Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute(); + return $ads_queue; +} + +/** + * Below will Generate the Queue if not exist + */ +public function generateAdQueue() { + /* First check thatt there is existing queue, if so don't generate it */ + $data_exist = (new \yii\db\Query()) + ->select('ad_quque_id') + ->from('ad_banner_queue') + ->where('is_sent=0') + ->scalar(); + if ($data_exist === false) { + /* Delete all other entries */ + (new \yii\db\Query()) + ->createCommand() + ->delete('ad_banner_queue') + ->execute(); + + /* Fetch all banner */ + $ads = (new \yii\db\Query()) + ->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage') + ->from('advertisement') + ->where('status_id in (8)') //Means only fetch Approved ads + ->all(); + if (!empty($ads)) { + foreach ($ads as $ad) { + /* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */ + $ins_fields = array(); + for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) { + $ins_fields[] = array($ad['ad_id']); + } + Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute(); + } + return true; + } else { + return false; + } + } else { + return false; + } +} + +```",2018/09/20,"['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']","Presumably, the ads are presented from separate pages. HTML is ""stateless"", so you cannot expect one page to know what ads have previously been displayed. So, you have to either pass this info from page to page, or store it somewhere in the database associated with the individual user. + +You also want some randomizing? Let's do both things at the same time. + +What is the ""state""? There is an ""initial state"", at which time you randomly pick the first ad to display. And you pass that info on to the next page (in the url or in a cookie or in the database). + +The other ""state"" looks at the previous state and computes which ad to display next. (Eventually, you need to worry about running out of ads -- will you start over? Will you re-randomize? Etc.) + +But how to avoid showing the same ""random"" ad twice in a row? + +* You have N ads -- `SELECT COUNT(*) ...` +* You picked add number J as the first ad to display -- simple application of `RAND()`, either in SQL or in the app. +* Pick a number, M, such that M and N are ""relatively prime"". +* The ""next"" ad is number (J := (J + M) mod N). This will cycle through all the ads without duplicating until all have been shown. -- Again, this can be done in SQL or in the ap. +* Pass J and M from one page to the next. + +To get the J'th row: Either have the rows uniquely *and* consecutively numbered; or use `ORDER BY ... LIMIT 1 OFFSET J`. (Caveat: it may be tricky to fill J into the SQL.) + +No table locks, no mutexes, just passing info from one page to the next.","Make your index unique or make a check that checks the data and see's if it is a duplicate. + +Hope this helps. Good luck" +52426582,"I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user. + +Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record? + +Below is the Code: + +``` +select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + + /* In case of queue is not there generate the new queue */ + if ($ads_queue === false) { + $output = $this->generateAdQueue(); + //In case of something went wrong while generating the queue + if ($output == false) { + return array(); + } + + //Now fetch the record again + $ads_queue = (new \yii\db\Query()) + ->select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + } + + /* Now, marked that one as is_sent */ + Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute(); + return $ads_queue; +} + +/** + * Below will Generate the Queue if not exist + */ +public function generateAdQueue() { + /* First check thatt there is existing queue, if so don't generate it */ + $data_exist = (new \yii\db\Query()) + ->select('ad_quque_id') + ->from('ad_banner_queue') + ->where('is_sent=0') + ->scalar(); + if ($data_exist === false) { + /* Delete all other entries */ + (new \yii\db\Query()) + ->createCommand() + ->delete('ad_banner_queue') + ->execute(); + + /* Fetch all banner */ + $ads = (new \yii\db\Query()) + ->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage') + ->from('advertisement') + ->where('status_id in (8)') //Means only fetch Approved ads + ->all(); + if (!empty($ads)) { + foreach ($ads as $ad) { + /* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */ + $ins_fields = array(); + for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) { + $ins_fields[] = array($ad['ad_id']); + } + Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute(); + } + return true; + } else { + return false; + } + } else { + return false; + } +} + +```",2018/09/20,"['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']","I'm taking it that you mean that different ""people"" that are conducting simultaneous requests should not get the same random row? The most robust way, without testing it, in order to avoid the minute chance of the same record being selected twice in two running requests will probably be to lock the table and perform the read and update in a transaction. You would have to use a storage engine that supports this, such as InnoDB. + +The way to accomplish `LOCK TABLES` and `UNLOCK TABLES` with transactional tables, such as InnoDB tables, is to begin a transaction with `SET autocommit = 0`, **not** `START TRANSACTION`, followed by `LOCK TABLES`. Then you should not call `UNLOCK TABLES` until you commit the transaction explicitly. + +For example, if you need to read and write to your table in one go, you can do this: + +``` +SET autocommit = 0; +LOCK TABLES ad_banner_queue AS ad_banner_queue_w WRITE, ad_banner_queue AS ad_banner_queue_r READ; +... perform your select query on ad_banner_queue_r, then update that row in ad_banner_queue_w with is_sent = 1... +COMMIT; +UNLOCK TABLES; + +``` + +The reason we lock with an alias is that you [cannot refer to a locked table multiple times in a single query using the same name](https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html). So we use aliases instead and obtain a separate lock for the table and each alias.","Presumably, the ads are presented from separate pages. HTML is ""stateless"", so you cannot expect one page to know what ads have previously been displayed. So, you have to either pass this info from page to page, or store it somewhere in the database associated with the individual user. + +You also want some randomizing? Let's do both things at the same time. + +What is the ""state""? There is an ""initial state"", at which time you randomly pick the first ad to display. And you pass that info on to the next page (in the url or in a cookie or in the database). + +The other ""state"" looks at the previous state and computes which ad to display next. (Eventually, you need to worry about running out of ads -- will you start over? Will you re-randomize? Etc.) + +But how to avoid showing the same ""random"" ad twice in a row? + +* You have N ads -- `SELECT COUNT(*) ...` +* You picked add number J as the first ad to display -- simple application of `RAND()`, either in SQL or in the app. +* Pick a number, M, such that M and N are ""relatively prime"". +* The ""next"" ad is number (J := (J + M) mod N). This will cycle through all the ads without duplicating until all have been shown. -- Again, this can be done in SQL or in the ap. +* Pass J and M from one page to the next. + +To get the J'th row: Either have the rows uniquely *and* consecutively numbered; or use `ORDER BY ... LIMIT 1 OFFSET J`. (Caveat: it may be tricky to fill J into the SQL.) + +No table locks, no mutexes, just passing info from one page to the next." +52426582,"I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user. + +Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record? + +Below is the Code: + +``` +select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + + /* In case of queue is not there generate the new queue */ + if ($ads_queue === false) { + $output = $this->generateAdQueue(); + //In case of something went wrong while generating the queue + if ($output == false) { + return array(); + } + + //Now fetch the record again + $ads_queue = (new \yii\db\Query()) + ->select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + } + + /* Now, marked that one as is_sent */ + Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute(); + return $ads_queue; +} + +/** + * Below will Generate the Queue if not exist + */ +public function generateAdQueue() { + /* First check thatt there is existing queue, if so don't generate it */ + $data_exist = (new \yii\db\Query()) + ->select('ad_quque_id') + ->from('ad_banner_queue') + ->where('is_sent=0') + ->scalar(); + if ($data_exist === false) { + /* Delete all other entries */ + (new \yii\db\Query()) + ->createCommand() + ->delete('ad_banner_queue') + ->execute(); + + /* Fetch all banner */ + $ads = (new \yii\db\Query()) + ->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage') + ->from('advertisement') + ->where('status_id in (8)') //Means only fetch Approved ads + ->all(); + if (!empty($ads)) { + foreach ($ads as $ad) { + /* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */ + $ins_fields = array(); + for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) { + $ins_fields[] = array($ad['ad_id']); + } + Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute(); + } + return true; + } else { + return false; + } + } else { + return false; + } +} + +```",2018/09/20,"['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']",You should create a separate db table and mark ads that user received with its help. Before sending ads to user check if he has already received it.,"Make your index unique or make a check that checks the data and see's if it is a duplicate. + +Hope this helps. Good luck" +52426582,"I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user. + +Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record? + +Below is the Code: + +``` +select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + + /* In case of queue is not there generate the new queue */ + if ($ads_queue === false) { + $output = $this->generateAdQueue(); + //In case of something went wrong while generating the queue + if ($output == false) { + return array(); + } + + //Now fetch the record again + $ads_queue = (new \yii\db\Query()) + ->select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + } + + /* Now, marked that one as is_sent */ + Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute(); + return $ads_queue; +} + +/** + * Below will Generate the Queue if not exist + */ +public function generateAdQueue() { + /* First check thatt there is existing queue, if so don't generate it */ + $data_exist = (new \yii\db\Query()) + ->select('ad_quque_id') + ->from('ad_banner_queue') + ->where('is_sent=0') + ->scalar(); + if ($data_exist === false) { + /* Delete all other entries */ + (new \yii\db\Query()) + ->createCommand() + ->delete('ad_banner_queue') + ->execute(); + + /* Fetch all banner */ + $ads = (new \yii\db\Query()) + ->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage') + ->from('advertisement') + ->where('status_id in (8)') //Means only fetch Approved ads + ->all(); + if (!empty($ads)) { + foreach ($ads as $ad) { + /* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */ + $ins_fields = array(); + for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) { + $ins_fields[] = array($ad['ad_id']); + } + Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute(); + } + return true; + } else { + return false; + } + } else { + return false; + } +} + +```",2018/09/20,"['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']","I'm taking it that you mean that different ""people"" that are conducting simultaneous requests should not get the same random row? The most robust way, without testing it, in order to avoid the minute chance of the same record being selected twice in two running requests will probably be to lock the table and perform the read and update in a transaction. You would have to use a storage engine that supports this, such as InnoDB. + +The way to accomplish `LOCK TABLES` and `UNLOCK TABLES` with transactional tables, such as InnoDB tables, is to begin a transaction with `SET autocommit = 0`, **not** `START TRANSACTION`, followed by `LOCK TABLES`. Then you should not call `UNLOCK TABLES` until you commit the transaction explicitly. + +For example, if you need to read and write to your table in one go, you can do this: + +``` +SET autocommit = 0; +LOCK TABLES ad_banner_queue AS ad_banner_queue_w WRITE, ad_banner_queue AS ad_banner_queue_r READ; +... perform your select query on ad_banner_queue_r, then update that row in ad_banner_queue_w with is_sent = 1... +COMMIT; +UNLOCK TABLES; + +``` + +The reason we lock with an alias is that you [cannot refer to a locked table multiple times in a single query using the same name](https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html). So we use aliases instead and obtain a separate lock for the table and each alias.","You may use [mutex](https://www.yiiframework.com/doc/api/2.0/yii-mutex-mutex) component to ensure that there is only one process trying to pop ad from queue. + +``` +$banner = []; +$key = __CLASS__ . '::generateAdQueue()' . serialize($params); +if (Yii::$app->mutex->acquire($key, 1)) { + $banner = $this->getBanner($params); + Yii::$app->mutex->release($key); +} + +``` + +However be aware that this may greatly reduce performance, especially if you want to process multiple request at the same time. You may consider different technology for such queue, relational databases does not really fit well for such task. Using Redis-based queue and [`SPOP`](https://redis.io/commands/spop) may be much better choice." +52426582,"I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user. + +Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record? + +Below is the Code: + +``` +select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + + /* In case of queue is not there generate the new queue */ + if ($ads_queue === false) { + $output = $this->generateAdQueue(); + //In case of something went wrong while generating the queue + if ($output == false) { + return array(); + } + + //Now fetch the record again + $ads_queue = (new \yii\db\Query()) + ->select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + } + + /* Now, marked that one as is_sent */ + Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute(); + return $ads_queue; +} + +/** + * Below will Generate the Queue if not exist + */ +public function generateAdQueue() { + /* First check thatt there is existing queue, if so don't generate it */ + $data_exist = (new \yii\db\Query()) + ->select('ad_quque_id') + ->from('ad_banner_queue') + ->where('is_sent=0') + ->scalar(); + if ($data_exist === false) { + /* Delete all other entries */ + (new \yii\db\Query()) + ->createCommand() + ->delete('ad_banner_queue') + ->execute(); + + /* Fetch all banner */ + $ads = (new \yii\db\Query()) + ->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage') + ->from('advertisement') + ->where('status_id in (8)') //Means only fetch Approved ads + ->all(); + if (!empty($ads)) { + foreach ($ads as $ad) { + /* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */ + $ins_fields = array(); + for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) { + $ins_fields[] = array($ad['ad_id']); + } + Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute(); + } + return true; + } else { + return false; + } + } else { + return false; + } +} + +```",2018/09/20,"['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']","Although it might seem to be a trivial question it is not at all, there are several ways to handle it and each of them has its own downsides, mainly you can face this issue from three different points: + +Live with it +============ + +Chances you can get a repeated pull are low in real life and you need to really think if you are willing to face the extra work just to make sure an ad is not shown twice in a row, you also need to think caches exist and you might break your brain making ads atomic just to find out browser/proxy/cache are serving a repeated ad :( + +Handle it on database +===================== + +You can handle this issue leaving the database the responsability to keep data safe and coherent(indeed it is the main task of database), there are several ways of doing it: + +* **Locks and table** (as previously suggested), I personally disklike the approach of using locks with PHP and MySQL, you will suffer performance penalities and risk deadlocking but anyway it's still a solution, you just make a select for update on your queue table to be sure no-one reads again until you update. The problem in here is you will lock the whole table while this is done and you need to be careful with your DB Driver and autocommits. +* **Cursors** Cursors are database structures created basically for the duty you are willing to do, you create a cursor and safely traverse it with [its functions](https://dev.mysql.com/doc/refman/5.7/en/cursors.html). Using cursors into PHP might be very tricky due to transactions too and you need to know very well what are you doing to avoid errors. +* **Cursors and stored procedures** the best way to handle this into database is managing cursors inside the database itself, that's why stored procedures are there, just create procedures to pull a new item from your cursor and to fill it again once it's all consumed. + +Handle it on PHP side +===================== + +In this case you need to implement your own queue on PHP and there might be several ways to do so but the main problem might be implementing multiprocess-safe atomic operations on your app, I personally dislike using any kind of locks if you are not 100% sure of the execution flow of your app or you might end up locking it all. Anyway there are three chances in here: + +* **Use sems or mutex** both included on php or third party, timeouts and locks can become a hell and they are not easy to detect so as stated above I'd avoid it. +* **[Use PHP MSG Queue](https://secure.php.net/manual/en/function.msg-get-queue.php)** I think this is the safest way as long as you run your app on a \*nix system, just send all the available ads to the message queue instead of creating a table on database, once all ads are consumed you can regenerate the queue once again, the drawback of this system is your server can not be distributed and you might lose the current queue status if you don't save it before a restart. +* **Third party queue system** depending on your app workload or interactions you might need to use a queue management system, this is a must if you want a distributed system, it might sound too serious using a msg queue system to handle this issue but this kind of approaches may be life-savers. + +Summary +======= + +If you can't live with it and are proficient enough with databases i'd go for stored procedures and cursors, you don't need to break your mind with concurrency, database will handle it as long as you are using an ACID compliant database (not MyISAM i.e.) + +If you want to avoid conding into the database and your system is \*nix and not going to be distributed you can give a try to msg\_queues + +If you think your system may be sometime distributed or do not rely on old SysV mechanisms you can give a try to a message broker like RabbitMQ, this nice things are addictive and once you start using them you start seeing new uses for them daily.","Make your index unique or make a check that checks the data and see's if it is a duplicate. + +Hope this helps. Good luck" +52426582,"I have one table as ad\_banner\_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user. + +Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record? + +Below is the Code: + +``` +select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + + /* In case of queue is not there generate the new queue */ + if ($ads_queue === false) { + $output = $this->generateAdQueue(); + //In case of something went wrong while generating the queue + if ($output == false) { + return array(); + } + + //Now fetch the record again + $ads_queue = (new \yii\db\Query()) + ->select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where('is_sent=0') + ->orderBy('RAND()') + ->one(); + } + + /* Now, marked that one as is_sent */ + Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute(); + return $ads_queue; +} + +/** + * Below will Generate the Queue if not exist + */ +public function generateAdQueue() { + /* First check thatt there is existing queue, if so don't generate it */ + $data_exist = (new \yii\db\Query()) + ->select('ad_quque_id') + ->from('ad_banner_queue') + ->where('is_sent=0') + ->scalar(); + if ($data_exist === false) { + /* Delete all other entries */ + (new \yii\db\Query()) + ->createCommand() + ->delete('ad_banner_queue') + ->execute(); + + /* Fetch all banner */ + $ads = (new \yii\db\Query()) + ->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage') + ->from('advertisement') + ->where('status_id in (8)') //Means only fetch Approved ads + ->all(); + if (!empty($ads)) { + foreach ($ads as $ad) { + /* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */ + $ins_fields = array(); + for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) { + $ins_fields[] = array($ad['ad_id']); + } + Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute(); + } + return true; + } else { + return false; + } + } else { + return false; + } +} + +```",2018/09/20,"['https://Stackoverflow.com/questions/52426582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1773177/']","Presumably, the ads are presented from separate pages. HTML is ""stateless"", so you cannot expect one page to know what ads have previously been displayed. So, you have to either pass this info from page to page, or store it somewhere in the database associated with the individual user. + +You also want some randomizing? Let's do both things at the same time. + +What is the ""state""? There is an ""initial state"", at which time you randomly pick the first ad to display. And you pass that info on to the next page (in the url or in a cookie or in the database). + +The other ""state"" looks at the previous state and computes which ad to display next. (Eventually, you need to worry about running out of ads -- will you start over? Will you re-randomize? Etc.) + +But how to avoid showing the same ""random"" ad twice in a row? + +* You have N ads -- `SELECT COUNT(*) ...` +* You picked add number J as the first ad to display -- simple application of `RAND()`, either in SQL or in the app. +* Pick a number, M, such that M and N are ""relatively prime"". +* The ""next"" ad is number (J := (J + M) mod N). This will cycle through all the ads without duplicating until all have been shown. -- Again, this can be done in SQL or in the ap. +* Pass J and M from one page to the next. + +To get the J'th row: Either have the rows uniquely *and* consecutively numbered; or use `ORDER BY ... LIMIT 1 OFFSET J`. (Caveat: it may be tricky to fill J into the SQL.) + +No table locks, no mutexes, just passing info from one page to the next.","You can use transactions and SELECT FOR UPDATE construction for lock data and consistent executing of queries. For instance: + +``` +public function getAds() +{ + $db = Yii::$app->db; + $transaction = $db->beginTransaction(Transaction::REPEATABLE_READ); + try { + $ads_queue = (new \yii\db\Query()) + ->select('ad_quque_id, banner_image, unique_code') + ->from('ad_banner_queue') + ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id') + ->where(new Expression('is_sent=0 FOR UPDATE')) + ->orderBy('RAND()') + ->one(); + if ($ads_queue === false) { + $transaction->commit(); + return null; + } + $db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute(); + $transaction->commit(); + return $ads_queue; + } catch(Exception $e) { + $transaction->rollBack(); + throw $e; + } +} + +public function getBanner($params) +{ + $ads_queue = $this->getAds(); + if (is_null($ads_queue)) { + $output = $this->generateAdQueue(); + if ($output == false) { + return array(); + } + $ads_queue = $this->getAds(); + } + return $ads_queue; +} + +```" +30707256,I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?,2015/06/08,"['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']","I'm from Instamojo. + +You can't use a local URL. This is because a webhook request is a POST request that is made from our server. Therefore, the only URLs that we can make these requests to would be URLs that are publicly available. + +For testing purposes, I would recommend using [RequestBin](https://requestbin.com/). You can create a new bin and paste the URL for that bin in the webhook URL field of your Instamojo link. This will give you a link that is accessible by our server and you can inspect the POST requests to this link by appending `?inspect` at the end of the URL.","I doubt if you can use local host URL +but instead you can create new links, as below +" +30707256,I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?,2015/06/08,"['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']","It is possible to forward Instamojo's webhooks to your local machine using tools like `localtunnel`. + +* `npm` is required to install localtunnel. [[How to install node and npm]](https://docs.npmjs.com/getting-started/installing-node) +* Install +[localtunnel](https://localtunnel.me/) + +Suppose you are running your local server at port 8000, in a new terminal window, execute this: + +* `lt --port 8000` + +It will show you output like: + +* `your url is: https://whawgpctcs.localtunnel.me` + +This is a *temporary* webhook URL that will forward every HTTPS request sent to `https://whawgpctcs.localtunnel.me` to your local server running on port `8000`. + +* Paste this temporary url into Instamojo's webhook field and continue testing. +* **Remember to remove the temporary webhook URL from Instamojo once you are done testing** + +The temporary webhook URL is valid as long as the `lt --port 8000` command (and your Internet connection) is active.","I doubt if you can use local host URL +but instead you can create new links, as below +" +30707256,I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?,2015/06/08,"['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']","I doubt if you can use local host URL +but instead you can create new links, as below +","You cannot use the localhost URL as a webhook URL in order to test the process. But you can simply bypass it, open hosts file from `C:\Windows\System32\Drivers\etc\hosts` +At the end of the line write + +``` +127.0.0.1 yourname.com + +``` + +And access localhost using yourname.com. +Just change localhost/your-location url with yourname.com/your-location in the PHP file." +30707256,I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?,2015/06/08,"['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']","I'm from Instamojo. + +You can't use a local URL. This is because a webhook request is a POST request that is made from our server. Therefore, the only URLs that we can make these requests to would be URLs that are publicly available. + +For testing purposes, I would recommend using [RequestBin](https://requestbin.com/). You can create a new bin and paste the URL for that bin in the webhook URL field of your Instamojo link. This will give you a link that is accessible by our server and you can inspect the POST requests to this link by appending `?inspect` at the end of the URL.","We can't use localhost or as Webhook URL.If it is used the following error will show ""Domain name should not be ""localhost"" or ""127.0.0.1"" "". So it must be a live URL." +30707256,I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?,2015/06/08,"['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']","It is possible to forward Instamojo's webhooks to your local machine using tools like `localtunnel`. + +* `npm` is required to install localtunnel. [[How to install node and npm]](https://docs.npmjs.com/getting-started/installing-node) +* Install +[localtunnel](https://localtunnel.me/) + +Suppose you are running your local server at port 8000, in a new terminal window, execute this: + +* `lt --port 8000` + +It will show you output like: + +* `your url is: https://whawgpctcs.localtunnel.me` + +This is a *temporary* webhook URL that will forward every HTTPS request sent to `https://whawgpctcs.localtunnel.me` to your local server running on port `8000`. + +* Paste this temporary url into Instamojo's webhook field and continue testing. +* **Remember to remove the temporary webhook URL from Instamojo once you are done testing** + +The temporary webhook URL is valid as long as the `lt --port 8000` command (and your Internet connection) is active.","We can't use localhost or as Webhook URL.If it is used the following error will show ""Domain name should not be ""localhost"" or ""127.0.0.1"" "". So it must be a live URL." +30707256,I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?,2015/06/08,"['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']","We can't use localhost or as Webhook URL.If it is used the following error will show ""Domain name should not be ""localhost"" or ""127.0.0.1"" "". So it must be a live URL.","You cannot use the localhost URL as a webhook URL in order to test the process. But you can simply bypass it, open hosts file from `C:\Windows\System32\Drivers\etc\hosts` +At the end of the line write + +``` +127.0.0.1 yourname.com + +``` + +And access localhost using yourname.com. +Just change localhost/your-location url with yourname.com/your-location in the PHP file." +30707256,I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?,2015/06/08,"['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']","I'm from Instamojo. + +You can't use a local URL. This is because a webhook request is a POST request that is made from our server. Therefore, the only URLs that we can make these requests to would be URLs that are publicly available. + +For testing purposes, I would recommend using [RequestBin](https://requestbin.com/). You can create a new bin and paste the URL for that bin in the webhook URL field of your Instamojo link. This will give you a link that is accessible by our server and you can inspect the POST requests to this link by appending `?inspect` at the end of the URL.","It is possible to forward Instamojo's webhooks to your local machine using tools like `localtunnel`. + +* `npm` is required to install localtunnel. [[How to install node and npm]](https://docs.npmjs.com/getting-started/installing-node) +* Install +[localtunnel](https://localtunnel.me/) + +Suppose you are running your local server at port 8000, in a new terminal window, execute this: + +* `lt --port 8000` + +It will show you output like: + +* `your url is: https://whawgpctcs.localtunnel.me` + +This is a *temporary* webhook URL that will forward every HTTPS request sent to `https://whawgpctcs.localtunnel.me` to your local server running on port `8000`. + +* Paste this temporary url into Instamojo's webhook field and continue testing. +* **Remember to remove the temporary webhook URL from Instamojo once you are done testing** + +The temporary webhook URL is valid as long as the `lt --port 8000` command (and your Internet connection) is active." +30707256,I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?,2015/06/08,"['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']","I'm from Instamojo. + +You can't use a local URL. This is because a webhook request is a POST request that is made from our server. Therefore, the only URLs that we can make these requests to would be URLs that are publicly available. + +For testing purposes, I would recommend using [RequestBin](https://requestbin.com/). You can create a new bin and paste the URL for that bin in the webhook URL field of your Instamojo link. This will give you a link that is accessible by our server and you can inspect the POST requests to this link by appending `?inspect` at the end of the URL.","You cannot use the localhost URL as a webhook URL in order to test the process. But you can simply bypass it, open hosts file from `C:\Windows\System32\Drivers\etc\hosts` +At the end of the line write + +``` +127.0.0.1 yourname.com + +``` + +And access localhost using yourname.com. +Just change localhost/your-location url with yourname.com/your-location in the PHP file." +30707256,I am implementing instamojo payment method into my website. Can I use a localhost URL as Webhook URL in order to test the process?,2015/06/08,"['https://Stackoverflow.com/questions/30707256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4290253/']","It is possible to forward Instamojo's webhooks to your local machine using tools like `localtunnel`. + +* `npm` is required to install localtunnel. [[How to install node and npm]](https://docs.npmjs.com/getting-started/installing-node) +* Install +[localtunnel](https://localtunnel.me/) + +Suppose you are running your local server at port 8000, in a new terminal window, execute this: + +* `lt --port 8000` + +It will show you output like: + +* `your url is: https://whawgpctcs.localtunnel.me` + +This is a *temporary* webhook URL that will forward every HTTPS request sent to `https://whawgpctcs.localtunnel.me` to your local server running on port `8000`. + +* Paste this temporary url into Instamojo's webhook field and continue testing. +* **Remember to remove the temporary webhook URL from Instamojo once you are done testing** + +The temporary webhook URL is valid as long as the `lt --port 8000` command (and your Internet connection) is active.","You cannot use the localhost URL as a webhook URL in order to test the process. But you can simply bypass it, open hosts file from `C:\Windows\System32\Drivers\etc\hosts` +At the end of the line write + +``` +127.0.0.1 yourname.com + +``` + +And access localhost using yourname.com. +Just change localhost/your-location url with yourname.com/your-location in the PHP file." +6624921,"Hi i have a question a tryaing to create Amount calculator in jQuery, AJAX and jQuery UI. But i have a problem, i get all importat values from slider, select box. Bud i really don't know how can a get this value to global. I get value only in each function but when i want get this value out of function this value in variable does not exist. + +``` +$(function() { + //1st slider for get amount + $(""#amount"").slider({ + range: ""min"", + value: 0, + min: 0, + max: 10000, + slide: function (e, ui) { + $(""#amount_show"").val(ui.value); + amount = ui.value; + } + }); + $(""#amount_show"").val($(""#amount"").slider(""value"")); + + //2nd slider for get values years + $(""#years"").slider({ + range: ""min"", + value:1, + min:1, + max:20, + step:1, + slide: function (e, ui) { + $(""#years_show"").val(ui.value); + years = ui.value; + } + }); + $(""#years_show"").val($(""#years"").slider(""value"")); + + //AJAX for loading values from xml + $.get(""irate.xml"", function(xml) { + $(xml).find('country').each(function() { + + var select = $('#country'), + id = $(this).attr('id'), + name = $(this).find('name').text(), + irate = $(this).find('irate').text(), + currency = $(this).find('currency').text(); + + select.append(""""); + }); + }); + + //get irate value from dropbox + $(""#country"").change(function() { + var irate_select = """"; + $(""#country option:selected"").each(function () { + irate_select += $(this).val() + "" ""; + }); + irate = irate_select; + }); +}); + +``` + +I need calculate with amount, years and irate. + +Thank for your advice.",2011/07/08,"['https://Stackoverflow.com/questions/6624921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896953/']","declare the variable outside of your function. + +ex. + +``` +var amount; + +$(function... + +```","AndyL's answer should be correct. + +If you declare the variables you need available in another function outside of your function, and then set their values in one function, they should be available with those values to another function. + +``` +// outside your function!! +var amount, + years, + irate; + +// in your function somewhere!! +amount = someCalculation(); +years = someOtherCalculation(); + +``` + +These values will be available in every other function because they are declared as members of the global namespace." +6624921,"Hi i have a question a tryaing to create Amount calculator in jQuery, AJAX and jQuery UI. But i have a problem, i get all importat values from slider, select box. Bud i really don't know how can a get this value to global. I get value only in each function but when i want get this value out of function this value in variable does not exist. + +``` +$(function() { + //1st slider for get amount + $(""#amount"").slider({ + range: ""min"", + value: 0, + min: 0, + max: 10000, + slide: function (e, ui) { + $(""#amount_show"").val(ui.value); + amount = ui.value; + } + }); + $(""#amount_show"").val($(""#amount"").slider(""value"")); + + //2nd slider for get values years + $(""#years"").slider({ + range: ""min"", + value:1, + min:1, + max:20, + step:1, + slide: function (e, ui) { + $(""#years_show"").val(ui.value); + years = ui.value; + } + }); + $(""#years_show"").val($(""#years"").slider(""value"")); + + //AJAX for loading values from xml + $.get(""irate.xml"", function(xml) { + $(xml).find('country').each(function() { + + var select = $('#country'), + id = $(this).attr('id'), + name = $(this).find('name').text(), + irate = $(this).find('irate').text(), + currency = $(this).find('currency').text(); + + select.append(""""); + }); + }); + + //get irate value from dropbox + $(""#country"").change(function() { + var irate_select = """"; + $(""#country option:selected"").each(function () { + irate_select += $(this).val() + "" ""; + }); + irate = irate_select; + }); +}); + +``` + +I need calculate with amount, years and irate. + +Thank for your advice.",2011/07/08,"['https://Stackoverflow.com/questions/6624921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896953/']","declare the variable outside of your function. + +ex. + +``` +var amount; + +$(function... + +```","Try using jquery's data() object; + +``` +$(function(){ +... + +slide: function (e, ui) { + $(""#amount_show"").val(ui.value); + amount = ui.value; + + // Add to data() object here + $('#amount').data('amount',amount); +} + +// reference it elsewhere in your script like such: +console.log($('#amount').data('amount')); + +```" +6624921,"Hi i have a question a tryaing to create Amount calculator in jQuery, AJAX and jQuery UI. But i have a problem, i get all importat values from slider, select box. Bud i really don't know how can a get this value to global. I get value only in each function but when i want get this value out of function this value in variable does not exist. + +``` +$(function() { + //1st slider for get amount + $(""#amount"").slider({ + range: ""min"", + value: 0, + min: 0, + max: 10000, + slide: function (e, ui) { + $(""#amount_show"").val(ui.value); + amount = ui.value; + } + }); + $(""#amount_show"").val($(""#amount"").slider(""value"")); + + //2nd slider for get values years + $(""#years"").slider({ + range: ""min"", + value:1, + min:1, + max:20, + step:1, + slide: function (e, ui) { + $(""#years_show"").val(ui.value); + years = ui.value; + } + }); + $(""#years_show"").val($(""#years"").slider(""value"")); + + //AJAX for loading values from xml + $.get(""irate.xml"", function(xml) { + $(xml).find('country').each(function() { + + var select = $('#country'), + id = $(this).attr('id'), + name = $(this).find('name').text(), + irate = $(this).find('irate').text(), + currency = $(this).find('currency').text(); + + select.append(""""); + }); + }); + + //get irate value from dropbox + $(""#country"").change(function() { + var irate_select = """"; + $(""#country option:selected"").each(function () { + irate_select += $(this).val() + "" ""; + }); + irate = irate_select; + }); +}); + +``` + +I need calculate with amount, years and irate. + +Thank for your advice.",2011/07/08,"['https://Stackoverflow.com/questions/6624921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896953/']","declare the variable outside of your function. + +ex. + +``` +var amount; + +$(function... + +```","a global variable should work, however, Shouldn't you want to change your 'calculator' if they change the values of something? + +pretend this is the html for the calculated amount: + +``` + + +``` + +then you will need something like this code in document.ready(): + +``` +//if the slider changes, then update the calculated value +$( ""#years,#amount"" ).bind( ""slidechange"", function(event, ui) { + myCalculator(); +}); +// if the ?country? drop down changes, update the calculated value +$().change(function(event){ + myCalculator(); +}); + +function myCalculator(){ + var years = $('#years').slider(""value""); + var amount = $('#amount').slider(""value""); + var country = $('#country').val(); + $('#amount').val(""something"") +}; + +```" +6624921,"Hi i have a question a tryaing to create Amount calculator in jQuery, AJAX and jQuery UI. But i have a problem, i get all importat values from slider, select box. Bud i really don't know how can a get this value to global. I get value only in each function but when i want get this value out of function this value in variable does not exist. + +``` +$(function() { + //1st slider for get amount + $(""#amount"").slider({ + range: ""min"", + value: 0, + min: 0, + max: 10000, + slide: function (e, ui) { + $(""#amount_show"").val(ui.value); + amount = ui.value; + } + }); + $(""#amount_show"").val($(""#amount"").slider(""value"")); + + //2nd slider for get values years + $(""#years"").slider({ + range: ""min"", + value:1, + min:1, + max:20, + step:1, + slide: function (e, ui) { + $(""#years_show"").val(ui.value); + years = ui.value; + } + }); + $(""#years_show"").val($(""#years"").slider(""value"")); + + //AJAX for loading values from xml + $.get(""irate.xml"", function(xml) { + $(xml).find('country').each(function() { + + var select = $('#country'), + id = $(this).attr('id'), + name = $(this).find('name').text(), + irate = $(this).find('irate').text(), + currency = $(this).find('currency').text(); + + select.append(""""); + }); + }); + + //get irate value from dropbox + $(""#country"").change(function() { + var irate_select = """"; + $(""#country option:selected"").each(function () { + irate_select += $(this).val() + "" ""; + }); + irate = irate_select; + }); +}); + +``` + +I need calculate with amount, years and irate. + +Thank for your advice.",2011/07/08,"['https://Stackoverflow.com/questions/6624921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896953/']","AndyL's answer should be correct. + +If you declare the variables you need available in another function outside of your function, and then set their values in one function, they should be available with those values to another function. + +``` +// outside your function!! +var amount, + years, + irate; + +// in your function somewhere!! +amount = someCalculation(); +years = someOtherCalculation(); + +``` + +These values will be available in every other function because they are declared as members of the global namespace.","Try using jquery's data() object; + +``` +$(function(){ +... + +slide: function (e, ui) { + $(""#amount_show"").val(ui.value); + amount = ui.value; + + // Add to data() object here + $('#amount').data('amount',amount); +} + +// reference it elsewhere in your script like such: +console.log($('#amount').data('amount')); + +```" +6624921,"Hi i have a question a tryaing to create Amount calculator in jQuery, AJAX and jQuery UI. But i have a problem, i get all importat values from slider, select box. Bud i really don't know how can a get this value to global. I get value only in each function but when i want get this value out of function this value in variable does not exist. + +``` +$(function() { + //1st slider for get amount + $(""#amount"").slider({ + range: ""min"", + value: 0, + min: 0, + max: 10000, + slide: function (e, ui) { + $(""#amount_show"").val(ui.value); + amount = ui.value; + } + }); + $(""#amount_show"").val($(""#amount"").slider(""value"")); + + //2nd slider for get values years + $(""#years"").slider({ + range: ""min"", + value:1, + min:1, + max:20, + step:1, + slide: function (e, ui) { + $(""#years_show"").val(ui.value); + years = ui.value; + } + }); + $(""#years_show"").val($(""#years"").slider(""value"")); + + //AJAX for loading values from xml + $.get(""irate.xml"", function(xml) { + $(xml).find('country').each(function() { + + var select = $('#country'), + id = $(this).attr('id'), + name = $(this).find('name').text(), + irate = $(this).find('irate').text(), + currency = $(this).find('currency').text(); + + select.append(""""); + }); + }); + + //get irate value from dropbox + $(""#country"").change(function() { + var irate_select = """"; + $(""#country option:selected"").each(function () { + irate_select += $(this).val() + "" ""; + }); + irate = irate_select; + }); +}); + +``` + +I need calculate with amount, years and irate. + +Thank for your advice.",2011/07/08,"['https://Stackoverflow.com/questions/6624921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896953/']","AndyL's answer should be correct. + +If you declare the variables you need available in another function outside of your function, and then set their values in one function, they should be available with those values to another function. + +``` +// outside your function!! +var amount, + years, + irate; + +// in your function somewhere!! +amount = someCalculation(); +years = someOtherCalculation(); + +``` + +These values will be available in every other function because they are declared as members of the global namespace.","a global variable should work, however, Shouldn't you want to change your 'calculator' if they change the values of something? + +pretend this is the html for the calculated amount: + +``` + + +``` + +then you will need something like this code in document.ready(): + +``` +//if the slider changes, then update the calculated value +$( ""#years,#amount"" ).bind( ""slidechange"", function(event, ui) { + myCalculator(); +}); +// if the ?country? drop down changes, update the calculated value +$().change(function(event){ + myCalculator(); +}); + +function myCalculator(){ + var years = $('#years').slider(""value""); + var amount = $('#amount').slider(""value""); + var country = $('#country').val(); + $('#amount').val(""something"") +}; + +```" +69712966,"I have been struggling with creating a legend in my ggplot for some time now, and I cannot find any answer that works. + +This is the stripped down version of my ggplot: + +``` +ggplot() + + geom_smooth(data = mydf1, aes(x, predicted, linetype = 1), method = ""lm"", linetype = 1, colour = ""black"") + + geom_smooth(data = mydf2, aes(x, predicted, linetype = 2), method = ""lm"", linetype = 2, colour = ""black"") + + geom_smooth(data = mydf3, aes(x, predicted, linetype = 3), method = ""lm"", linetype = 3, colour = ""black"") + + theme_classic() + +``` + +[![enter image description here](https://i.stack.imgur.com/u84MR.png)](https://i.stack.imgur.com/u84MR.png) + +As you can notice, I am taking data from different dataframes (mydf1, mydf2, mydf3). Now I want to manually add a legend that specifies that the solid line is ""Group 1"", the longdashed line is ""Group 2"", and the dotted linetype is ""Group 3"". However, whatever I try, no legend appears in my ggplot. I included linetype within the aes(), tried everything I could think of regarding scale\_linetype\_manual(), and I've been looking around to find solutions, but no legend pops up. + +Am I missing something obvious? I just need a small legend to the side stating what the different linetypes mean. + +My data is the following: + +``` +mydf1 <- data.frame(x = c(seq(-1,1, 0.2)), + predicted = c(-0.27066438, -0.23568714, -0.20070991, -0.16573267, -0.13075543, -0.09577819, -0.06080095, -0.02582371, 0.00915353, 0.04413077, 0.07910801)) + +mydf2 <- data.frame(x = c(seq(-1,1, 0.2)), + predicted = c(-0.39806988, -0.34348641, -0.28890295, -0.23431948, -0.17973602, -0.12515255, -0.07056909, -0.01598562, 0.03859784, 0.09318131, 0.14776477)) + +mydf3 <- data.frame(x = c(seq(-1,1, 0.2)), + predicted = c(-0.25520076, -0.22917917, -0.20315758, -0.17713600, -0.15111441, -0.12509282, -0.09907123, -0.07304964, -0.04702806, -0.02100647, 0.00501512)) + +``` + +Although any practical solution would be helpful, I am not neccesarily looking to combine the dataframes into a single one and redo the ggplot. Thanks!",2021/10/25,"['https://Stackoverflow.com/questions/69712966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13339640/']","Bring the line linetype inside aes() and use lab() to give title for the legend. + +``` +ggplot() + + geom_smooth(data = mydf1, aes(x, predicted, linetype = ""Group 1""), method = ""lm"", colour = ""black"") + + geom_smooth(data = mydf2, aes(x, predicted, linetype = ""Group 2""), method = ""lm"", colour = ""black"") + + geom_smooth(data = mydf3, aes(x, predicted, linetype = ""Group 3""), method = ""lm"", colour = ""black"") + + labs(linetype=""Group"") + + theme_classic() + +``` + +[![enter image description here](https://i.stack.imgur.com/vg054.png)](https://i.stack.imgur.com/vg054.png)","Here is an alternative way using `bind_rows`: + +``` +library(dplyr) +library(ggplot2) +bind_rows(mydf1, mydf2, mydf3) %>% + mutate(group = as.integer(gl(n(), 11, n()))) %>% + ggplot(aes(x, predicted, linetype=factor(group)))+ + geom_smooth(color=""black"", method = ""lm"", se=F) + + scale_linetype_discrete(name=""group"", + breaks=c(1, 2, 3), + labels = c(""group1"", ""group2"", ""group3""))+ + theme_classic() + +``` + +[![enter image description here](https://i.stack.imgur.com/qSVzf.png)](https://i.stack.imgur.com/qSVzf.png)" +15501034,"I try to load a codeigniter view in iframe as, +`` +But the page could not load. +With out i frame its working. +How do i load this view in iframe ?",2013/03/19,"['https://Stackoverflow.com/questions/15501034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939388/']","You can't assign plain html to iframe elements src attribute. You should have a controller that render your html and then set src attribute to that controller. + +``` + + +```","This is because the iframe is on another page? +you haven't specified the controller function on that page so it doesn't recognize the view. i think you have to put the controller date from your view into the function for the view you have your iframe in, so lik this. + +``` +function list_view() +{ +//functions for your listview +} + +function viewforiframe() +{ +//function for you view where the iframe is located ++ +//functions for your listview +} + +``` + +NOTE: the answer Deon gave is also a thing to look at. without a good link you could never see the view." +15501034,"I try to load a codeigniter view in iframe as, +`` +But the page could not load. +With out i frame its working. +How do i load this view in iframe ?",2013/03/19,"['https://Stackoverflow.com/questions/15501034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939388/']","create a function in your controller + +``` +//project.php + +function view_list() +{ +$this->load->view('lists'); +} + +``` + +and call in the view page like this + +``` + + +```","This is because the iframe is on another page? +you haven't specified the controller function on that page so it doesn't recognize the view. i think you have to put the controller date from your view into the function for the view you have your iframe in, so lik this. + +``` +function list_view() +{ +//functions for your listview +} + +function viewforiframe() +{ +//function for you view where the iframe is located ++ +//functions for your listview +} + +``` + +NOTE: the answer Deon gave is also a thing to look at. without a good link you could never see the view." +15501034,"I try to load a codeigniter view in iframe as, +`` +But the page could not load. +With out i frame its working. +How do i load this view in iframe ?",2013/03/19,"['https://Stackoverflow.com/questions/15501034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939388/']","I wanted to tile a site with several views, each in their own iframe, this is what I did: + +The controller, **book.php** + +``` +shell(); + } + + public function shell(){ + + $data['title'] = ""Home""; + $data['frames'] = array( + ""book/events"" + ,""book/sales"" + ,""book/purchases"" + ,""book/cashflows"" + ); + + $this->load->view(""shell"", $data); + + } + + public function events(){ + $this->load->view(""events""); + } + + public function sales(){ + $this->load->view(""sales""); + } + + public function purchases(){ + $this->load->view(""purchases""); + } + + public function cashflows(){ + $this->load->view(""cashflows""); + } + +} + +``` + +The view **shell.php** contains a foreach statement letting me pass in tiles dynamically. Note how the url's to each site are written in the controller above ^^ (eg. ""book/events""). + +``` + + + + + <?php echo $title ?> + + + + + + + +
+ Page rendered in {elapsed_time} seconds

+
+ + + +``` + +Then each tile is simply it's own site, like so: + +``` + + + + + Events + + +
Events
+
Bla bla bla you have no money
+
+ Page rendered in {elapsed_time} seconds

+
+ + + +```","This is because the iframe is on another page? +you haven't specified the controller function on that page so it doesn't recognize the view. i think you have to put the controller date from your view into the function for the view you have your iframe in, so lik this. + +``` +function list_view() +{ +//functions for your listview +} + +function viewforiframe() +{ +//function for you view where the iframe is located ++ +//functions for your listview +} + +``` + +NOTE: the answer Deon gave is also a thing to look at. without a good link you could never see the view." +15501034,"I try to load a codeigniter view in iframe as, +`` +But the page could not load. +With out i frame its working. +How do i load this view in iframe ?",2013/03/19,"['https://Stackoverflow.com/questions/15501034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939388/']","create a function in your controller + +``` +//project.php + +function view_list() +{ +$this->load->view('lists'); +} + +``` + +and call in the view page like this + +``` + + +```","You can't assign plain html to iframe elements src attribute. You should have a controller that render your html and then set src attribute to that controller. + +``` + + +```" +15501034,"I try to load a codeigniter view in iframe as, +`` +But the page could not load. +With out i frame its working. +How do i load this view in iframe ?",2013/03/19,"['https://Stackoverflow.com/questions/15501034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1939388/']","create a function in your controller + +``` +//project.php + +function view_list() +{ +$this->load->view('lists'); +} + +``` + +and call in the view page like this + +``` + + +```","I wanted to tile a site with several views, each in their own iframe, this is what I did: + +The controller, **book.php** + +``` +shell(); + } + + public function shell(){ + + $data['title'] = ""Home""; + $data['frames'] = array( + ""book/events"" + ,""book/sales"" + ,""book/purchases"" + ,""book/cashflows"" + ); + + $this->load->view(""shell"", $data); + + } + + public function events(){ + $this->load->view(""events""); + } + + public function sales(){ + $this->load->view(""sales""); + } + + public function purchases(){ + $this->load->view(""purchases""); + } + + public function cashflows(){ + $this->load->view(""cashflows""); + } + +} + +``` + +The view **shell.php** contains a foreach statement letting me pass in tiles dynamically. Note how the url's to each site are written in the controller above ^^ (eg. ""book/events""). + +``` + + + + + <?php echo $title ?> + + + + + + + +
+ Page rendered in {elapsed_time} seconds

+
+ + + +``` + +Then each tile is simply it's own site, like so: + +``` + + + + + Events + + +
Events
+
Bla bla bla you have no money
+
+ Page rendered in {elapsed_time} seconds

+
+ + + +```" +4381225,"I have a database called RankHistory that is populated daily with each user's username and rank for the day (rank as in 1,2,3,...). I keep logs going back 90 days for every user, but my user base has grown to the point that the MySQL database holding these logs is now in excess of 20 million rows. + +This data is recorded solely for the use of generating a graph showing how a user's rank has changed for the past 90 days. Is there a better way of doing this than having this massive database that will keep growing forever?",2010/12/07,"['https://Stackoverflow.com/questions/4381225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115182/']","How great is the need for historic data in this case? My first thought would be to truncate data older than a certain threshold, or move it to an archive table that doesn't require as frequent or fast access as your current data. + +You also mention keeping 90 days of data per user, but the data is only used to show a graph of changes to rank over the past 30 days. Is the extra 60 days' data used to look at changes over previous periods? If it isn't strictly necessary to keep that data (or at least not keep it in your primary data store, as per my first suggestion), you'd neatly cut the quantity of your data by two-thirds. + +Do we have the full picture, though? If you have a daily record per user, and keep 90 days on hand, you must have on the order of a quarter-million users if you've generated over twenty million records. Is that so? + +**Update:** + +Based on the comments below, here are my thoughts: If you have hundreds of thousands of users, and must keep a piece of data for each of them, every day for 90 days, then you will eventually have millions of pieces of data - there's no simple way around that. What you can look into is *minimizing* that data. If all you need to present is a calculated rank per user per day, and assuming that rank is simply a numeric position for the given user among all users (an integer between 1 - 200000, for example), storing twenty million such records should not put unreasonable strain on your database resources. + +So, what precisely is your concern? Sheer data size (i.e. hard-disk space consumed) should be relatively manageable under the scenario above. You should be able to handle performance via indexes, to a certain point, beyond which the data truncation and partitioning concepts mentioned can come into play (keep blocks of users in different tables or databases, for example, though that's not an ideal design...) + +Another possibility is, though the specifics are somewhat beyond my realm of expertise, you seem to have an ideal candidate for an [OLAP cube](http://training.inet.com/OLAP/Cubes.htm), here: you have a fact (rank) that you want to view in the context of two dimensions (user and date). There are tools out there for managing this sort of scenario efficiently, even on very large datasets.",Could you run an automated task like a cron job that checks the database every day or week and deletes entries that are more than 90 days old? +4381225,"I have a database called RankHistory that is populated daily with each user's username and rank for the day (rank as in 1,2,3,...). I keep logs going back 90 days for every user, but my user base has grown to the point that the MySQL database holding these logs is now in excess of 20 million rows. + +This data is recorded solely for the use of generating a graph showing how a user's rank has changed for the past 90 days. Is there a better way of doing this than having this massive database that will keep growing forever?",2010/12/07,"['https://Stackoverflow.com/questions/4381225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115182/']","How great is the need for historic data in this case? My first thought would be to truncate data older than a certain threshold, or move it to an archive table that doesn't require as frequent or fast access as your current data. + +You also mention keeping 90 days of data per user, but the data is only used to show a graph of changes to rank over the past 30 days. Is the extra 60 days' data used to look at changes over previous periods? If it isn't strictly necessary to keep that data (or at least not keep it in your primary data store, as per my first suggestion), you'd neatly cut the quantity of your data by two-thirds. + +Do we have the full picture, though? If you have a daily record per user, and keep 90 days on hand, you must have on the order of a quarter-million users if you've generated over twenty million records. Is that so? + +**Update:** + +Based on the comments below, here are my thoughts: If you have hundreds of thousands of users, and must keep a piece of data for each of them, every day for 90 days, then you will eventually have millions of pieces of data - there's no simple way around that. What you can look into is *minimizing* that data. If all you need to present is a calculated rank per user per day, and assuming that rank is simply a numeric position for the given user among all users (an integer between 1 - 200000, for example), storing twenty million such records should not put unreasonable strain on your database resources. + +So, what precisely is your concern? Sheer data size (i.e. hard-disk space consumed) should be relatively manageable under the scenario above. You should be able to handle performance via indexes, to a certain point, beyond which the data truncation and partitioning concepts mentioned can come into play (keep blocks of users in different tables or databases, for example, though that's not an ideal design...) + +Another possibility is, though the specifics are somewhat beyond my realm of expertise, you seem to have an ideal candidate for an [OLAP cube](http://training.inet.com/OLAP/Cubes.htm), here: you have a fact (rank) that you want to view in the context of two dimensions (user and date). There are tools out there for managing this sort of scenario efficiently, even on very large datasets.","Another option, do can you create some ""roll-up"" aggregate per user based on whatever the criteria is... counts, sales, whatever and it is all stored based on employee + date of activity. Then you could have your pre-aggregated rollups in a much smaller table for however long in history you need. Triggers, or nightly procedures can run a query for the day and append the results to the daily summary. Then your queries and graphs can go against that without dealing with performance issues. This would also help ease moving such records to a historical database archive. + +-- uh... oops... that's what it sounded like you WERE doing and STILL had 20 million+ records... is that correct? That would mean you're dealing with about 220,000+ users??? +20,000,000 records / 90 days = about 222,222 users + +EDIT -- from feedback. + +Having 222k+ users, I would seriously consider that importance it is for ""Ranking"" when you have someone in the 222,222nd place. I would pair the daily ranking down to say the top 1,000. Again, I don't know the importance, but if someone doesn't make the top 1,000 does it really matter???" +127322,"In the context of testing using hardhat... + +**The scenario:** My `token` is transfering from `owner` to `receiverContract`. I want to check that receiverContract emitted a `Received` event. + +The transaction looks like this and is initiated by the owner. + +```js +const tx = await token.transferFrom( + owner.address, // <- From this wallet + receiverContract.address, // <- To this contract + tokenId, + { + from: owner.address, + } +); + +``` + +How can I check if receiverContract emitted a ""Received"" event? +Alternatively, if someone can solve this problem with `@openzeppelin/test-helpers` `expectEvent.inTransaction()` that works too. + +Edit: The receiver contract code emits an event when it receives something. So we can assume it emits. I just need to write a test for it. I'm not interested in testing for the `Transfer` event on the token itself.",2022/05/02,"['https://ethereum.stackexchange.com/questions/127322', 'https://ethereum.stackexchange.com', 'https://ethereum.stackexchange.com/users/68369/']","I figured out how to do it. + +Each contract can be viewed via `console.log(receiverContract)`... so I eventually navigated to the event object inside the contract. Here is a snippet of the contract when logged... + +```js +{ + interface: Interface { + fragments: [ [ConstructorFragment], [EventFragment], [FunctionFragment] ], + _abiCoder: AbiCoder { coerceFunc: null }, + functions: { + 'onERC721Received(address,address,uint256,bytes)': [FunctionFragment] + }, + errors: {}, + events: { // <- This is what we're looking for + 'Received(address,address,uint256,bytes,uint256)': [EventFragment { + name: 'Received', + anonymous: false, + inputs: [ [ParamType], [ParamType], [ParamType], [ParamType], [ParamType] ], + type: 'event', + _isFragment: true + }], + // ... +} + +``` + +Running `console.log(receiverContract.interface.events)` gives you this nested object + +```js + 'Received(address,address,uint256,bytes,uint256)', + EventFragment { + name: 'Received', // <- This is the event name + anonymous: false, + inputs: [ [ParamType], [ParamType], [ParamType], [ParamType], [ParamType] ], + type: 'event', + _isFragment: true + } + +``` + +So in order to look for and test that the event emitted, this works + +```js +expect( + Object.entries(receiverContract.interface.events).some( + ([k, v]: any) => v.name === ""Received"" + ) +).to.be.equal(true); + +```","Since there's no interaction with the receiving contract, it will not emit anything. + +Transaction is sent to the token, which emits `Transfer` event once it changes records of its ledger. + +You can watch the token for `Transfer` event, or read the transaction receipt, decode the log and check for that event." +127322,"In the context of testing using hardhat... + +**The scenario:** My `token` is transfering from `owner` to `receiverContract`. I want to check that receiverContract emitted a `Received` event. + +The transaction looks like this and is initiated by the owner. + +```js +const tx = await token.transferFrom( + owner.address, // <- From this wallet + receiverContract.address, // <- To this contract + tokenId, + { + from: owner.address, + } +); + +``` + +How can I check if receiverContract emitted a ""Received"" event? +Alternatively, if someone can solve this problem with `@openzeppelin/test-helpers` `expectEvent.inTransaction()` that works too. + +Edit: The receiver contract code emits an event when it receives something. So we can assume it emits. I just need to write a test for it. I'm not interested in testing for the `Transfer` event on the token itself.",2022/05/02,"['https://ethereum.stackexchange.com/questions/127322', 'https://ethereum.stackexchange.com', 'https://ethereum.stackexchange.com/users/68369/']","I figured out how to do it. + +Each contract can be viewed via `console.log(receiverContract)`... so I eventually navigated to the event object inside the contract. Here is a snippet of the contract when logged... + +```js +{ + interface: Interface { + fragments: [ [ConstructorFragment], [EventFragment], [FunctionFragment] ], + _abiCoder: AbiCoder { coerceFunc: null }, + functions: { + 'onERC721Received(address,address,uint256,bytes)': [FunctionFragment] + }, + errors: {}, + events: { // <- This is what we're looking for + 'Received(address,address,uint256,bytes,uint256)': [EventFragment { + name: 'Received', + anonymous: false, + inputs: [ [ParamType], [ParamType], [ParamType], [ParamType], [ParamType] ], + type: 'event', + _isFragment: true + }], + // ... +} + +``` + +Running `console.log(receiverContract.interface.events)` gives you this nested object + +```js + 'Received(address,address,uint256,bytes,uint256)', + EventFragment { + name: 'Received', // <- This is the event name + anonymous: false, + inputs: [ [ParamType], [ParamType], [ParamType], [ParamType], [ParamType] ], + type: 'event', + _isFragment: true + } + +``` + +So in order to look for and test that the event emitted, this works + +```js +expect( + Object.entries(receiverContract.interface.events).some( + ([k, v]: any) => v.name === ""Received"" + ) +).to.be.equal(true); + +```","The ERC20 contract transaction is sent to the token contract itself, and not to the receiving contract, hence there cannot be any event emitted from the receiving contract. + +A receiving contract can emit any event only if it has been configured in either the `receive()` or `fallback()` method. That too, while sending `msg.value` to it i.e. ETH, BNB, etc. (the receiving contract's chain's native crypto). + +If you just want to make sure that the receiving contract has received the tokens, you can check the `Transfer` event emitted by the ERC20 token contract. + +You want suggestions on `@openzeppelin/test-helpers`, I've not used it but you can use the `expectEvent()` function to check it. + +Something like (NOT TESTED): + +``` +const tx = await token.transferFrom( + owner.address, // <- From this wallet + receiverContract.address, // <- To this contract + tokenId, + { + from: owner.address, + } +); + +expectEvent(tx, 'Transfer', { + from: owner.address, // <- From this wallet + to: receiverContract.address, // <- To this contract + value: tokenId, +}); + +```" +23404,"When widening a road, why does construction seem to inevitably include a ""smoothing"" out of the curves on the road, essentially making it more straight? + +I've seen this personally on roads where I travel, and you can even catch a glimpse on Google satellite imagery of roads that are in the widening process: Google overlays a ""ghost"" lane to show where the new lanes of the road will be. It's faint, but you can see an example here on a road near Flowery Branch, GA: + +[![enter image description here](https://i.stack.imgur.com/xO3WZ.png)](https://i.stack.imgur.com/xO3WZ.png) + +Is this the engineers' way of correcting previous mistakes, or a response to devleopment that's sprung up around the road since its initial construction, or safety reasons? Or something else entirely?",2018/08/22,"['https://engineering.stackexchange.com/questions/23404', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/17255/']","A wider road will have faster average traffic speeds, because faster vehicles will be hindered less by slow ones, with more lanes available for overtaking. + +So longer visibility distances are needed for safety, and hence more gradual curves and more gradual changes of gradient (no ""hidden spots"" over the brow of a hill, etc). + +Note, for most ""fast"" roads traffic speeds are not limited at all by the radius of the curves, except perhaps in very severe weather conditions (snow and ice, standing rainwater, etc). Aside from breaking the law and the hazards posed by other vehicles, there would be no problem in driving a modern vehicle along the road way above the legal speed limit.","I am familiar with this effect; with careful observation you can count at least three rounds of road-straightening on highway 17 between the cities of San Jose and Santa Cruz in California. + +The first road was built over 100 years ago and carried horse-drawn wagons. At the time, moving large volumes of earth and rock was more expensive than surfacing the road and so it followed sharp curves in the mountainsides instead of being extensively built on fill from nearby road cuts. + +Then came automobiles and more and faster traffic, and when widening the original stage road the sharpest turns were rounded off to carry faster vehicles and cut-and-fill was used so the mountain contours didn't have to be closely followed. + +At each step in this decades-long process, the cost of earthmoving fell and the cost of pavement rose, and so it became economical to use more and more cut-and-fill in conjunction with straighter and straighter road paths. + +The stage road is now a 4-lane freeway which still has a few somewhat sharp turns in it but much of it is built by cut-and-fill and can be traversed at 50 to 60 MPH." +4627682,"This is an extremely elementary question but I want to make sure I understand this right. + +If someone adds two numbers in their mind and tells us the sum, it is impossible to prove mathematically what two numbers they chose (in most cases). The number of distinct ways to add two numbers to form say, an integer $n$, is something like $ceil((N+1)/2)$ ([here](https://math.stackexchange.com/questions/3034937/how-many-ways-can-a-number-be-written-as-a-sum-of-two-non-negative-integers)). This shows us that there is more than one way, for any number from 2 and beyond. + +I think I am thinking about a function mapping each pair of elements to its sum, and observing that it is not injective. + +I am just trying to understand why. As integers are sort of the conceptual basis for the concept of a group (I think), is the fact that different elements can combine to form the same element a result of ""closure"", in that, when we look at the Cayley table of a group, we will see each element of the group exactly once? So is it a necessary condition on any group that the function (x, y) -> (x + y) can not be bijective? Or is there any relationship between groups cycles and elements having unique composition? + +Maybe I am completely off-track here but I am trying to ask the fundamental question of why addition is not reversible and what kind of related structure does on the other hand have that property. What deep difference in structure or properties do they have, allowing this?",2023/01/28,"['https://math.stackexchange.com/questions/4627682', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/990260/']","If you want 4, 1+3 and 2+2 to be separate elements of your collection, then you should also be able to involve these elements in sums separately. so 5+4, 5+(1+3), and 5+(2+2) should all be different elements of your structure as well. + +Consider the set of expressions built up out of base elements via binary sums, with the trivial operation of addition being ""add parentheses and stick a + sign between"". So addition takes 5 and 4 as inputs and outputs 5+4 and addition takes 5 and 1+3 as inputs and outputs 5+(1+3). + +This is a reasonable operation, but it's not associative (we view 5+(1+3) and (5+1)+3 as different expressions) and it doesn't have inverses, so it's not a group. + +If you want a group, the operation on the one element group is bijective.","Multiplication of prime numbers is reversible, in the sense that any positive integer is expressible as a product of primes in just one way (not counting changing order...). + +(The computational difficulty of reversing the operation, that is, of *factoring* versus multiplying, is the basis of the RSA cryptosystem and other things...)" +21922305,"I have read that the `role` attribute was added to [Bootstrap](http://getbootstrap.com/) for accessibility, and I would like to know how `
` helps accessibility. See for an example of this specific usage. + +*I [searched Bootstrap's repo for ""role""](https://github.com/twbs/bootstrap/search?q=role) to no avail.* + +My issue is that the information seems redundant. The notion that the element is a *form* is already expressed by the HTML tag itself (``), so what does it help if we also add that the element is playing the `role` of `form`? It would make sense to add `role=""...""` if `role` was going to be different than `form` (I don't know what - but let's pretend); as it stands (especially without concrete reasoning / use case examples), it is puzzling at best.",2014/02/20,"['https://Stackoverflow.com/questions/21922305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/664833/']","If you add a `role=""form""` to a form, a screen reader sees it as a region on a webpage. That means that a user can easily jump to the form with his/her region quick navigation keys (for example, in JAWS 15 you use *R* for this). And also, your user will be able to easily find where the form starts and ends because screen readers mark start and end of regions.","Semantically speaking, a form by default is, well, a form. However, not all accessibility applications(screen readers, etc) are designed the same and some can use elements (even the form element) with the `role=form` attribute differently even if they understand that the parent form element will have the same semantic meaning with or without the `role=form` attribute." +21922305,"I have read that the `role` attribute was added to [Bootstrap](http://getbootstrap.com/) for accessibility, and I would like to know how `` helps accessibility. See for an example of this specific usage. + +*I [searched Bootstrap's repo for ""role""](https://github.com/twbs/bootstrap/search?q=role) to no avail.* + +My issue is that the information seems redundant. The notion that the element is a *form* is already expressed by the HTML tag itself (``), so what does it help if we also add that the element is playing the `role` of `form`? It would make sense to add `role=""...""` if `role` was going to be different than `form` (I don't know what - but let's pretend); as it stands (especially without concrete reasoning / use case examples), it is puzzling at best.",2014/02/20,"['https://Stackoverflow.com/questions/21922305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/664833/']","If you add a `role=""form""` to a form, a screen reader sees it as a region on a webpage. That means that a user can easily jump to the form with his/her region quick navigation keys (for example, in JAWS 15 you use *R* for this). And also, your user will be able to easily find where the form starts and ends because screen readers mark start and end of regions.","I'd like to point out that the article @user664833 mentioned in a [comment](https://stackoverflow.com/questions/21922305/how-does-role-form-help-accessibility#comment33241849_21922985) states that **`role=""form""` shouldn't go on `` elements**, but rather on a `
` or some other element which does not semantically indicate that it contains form elements. + +**The `` element** is probably already **handled properly** by modern screen readers. + +[Quote (link):](https://www.paciellogroup.com/blog/2013/02/using-wai-aria-landmarks-2013/#tablex) + +> +> Recommend using [`role=""form""`] on a semantically neutral element such as a `
` not on a `` element, as the element already has **default role semantics exposed**. +> +> +>" +21922305,"I have read that the `role` attribute was added to [Bootstrap](http://getbootstrap.com/) for accessibility, and I would like to know how `` helps accessibility. See for an example of this specific usage. + +*I [searched Bootstrap's repo for ""role""](https://github.com/twbs/bootstrap/search?q=role) to no avail.* + +My issue is that the information seems redundant. The notion that the element is a *form* is already expressed by the HTML tag itself (``), so what does it help if we also add that the element is playing the `role` of `form`? It would make sense to add `role=""...""` if `role` was going to be different than `form` (I don't know what - but let's pretend); as it stands (especially without concrete reasoning / use case examples), it is puzzling at best.",2014/02/20,"['https://Stackoverflow.com/questions/21922305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/664833/']","If you add a `role=""form""` to a form, a screen reader sees it as a region on a webpage. That means that a user can easily jump to the form with his/her region quick navigation keys (for example, in JAWS 15 you use *R* for this). And also, your user will be able to easily find where the form starts and ends because screen readers mark start and end of regions.","In fact, the ARIA 1.1 W3C recommendation states clearly one should not change the host language semantics in section 1.4 ([source](https://www.w3.org/TR/wai-aria-1.1/#co-evolution)): + +> +> ""It is not appropriate to create objects with style and script when +> the host language provides a semantic element for that type of object. +> While WAI-ARIA can improve the accessibility of these objects, +> accessibility is best provided by allowing the user agent to handle +> the object natively."" +> +> +> + +So, writing `` is not only redundant but against the recommendation." +21922305,"I have read that the `role` attribute was added to [Bootstrap](http://getbootstrap.com/) for accessibility, and I would like to know how `` helps accessibility. See for an example of this specific usage. + +*I [searched Bootstrap's repo for ""role""](https://github.com/twbs/bootstrap/search?q=role) to no avail.* + +My issue is that the information seems redundant. The notion that the element is a *form* is already expressed by the HTML tag itself (``), so what does it help if we also add that the element is playing the `role` of `form`? It would make sense to add `role=""...""` if `role` was going to be different than `form` (I don't know what - but let's pretend); as it stands (especially without concrete reasoning / use case examples), it is puzzling at best.",2014/02/20,"['https://Stackoverflow.com/questions/21922305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/664833/']","I'd like to point out that the article @user664833 mentioned in a [comment](https://stackoverflow.com/questions/21922305/how-does-role-form-help-accessibility#comment33241849_21922985) states that **`role=""form""` shouldn't go on `` elements**, but rather on a `
` or some other element which does not semantically indicate that it contains form elements. + +**The `` element** is probably already **handled properly** by modern screen readers. + +[Quote (link):](https://www.paciellogroup.com/blog/2013/02/using-wai-aria-landmarks-2013/#tablex) + +> +> Recommend using [`role=""form""`] on a semantically neutral element such as a `
` not on a `` element, as the element already has **default role semantics exposed**. +> +> +>","Semantically speaking, a form by default is, well, a form. However, not all accessibility applications(screen readers, etc) are designed the same and some can use elements (even the form element) with the `role=form` attribute differently even if they understand that the parent form element will have the same semantic meaning with or without the `role=form` attribute." +21922305,"I have read that the `role` attribute was added to [Bootstrap](http://getbootstrap.com/) for accessibility, and I would like to know how `` helps accessibility. See for an example of this specific usage. + +*I [searched Bootstrap's repo for ""role""](https://github.com/twbs/bootstrap/search?q=role) to no avail.* + +My issue is that the information seems redundant. The notion that the element is a *form* is already expressed by the HTML tag itself (``), so what does it help if we also add that the element is playing the `role` of `form`? It would make sense to add `role=""...""` if `role` was going to be different than `form` (I don't know what - but let's pretend); as it stands (especially without concrete reasoning / use case examples), it is puzzling at best.",2014/02/20,"['https://Stackoverflow.com/questions/21922305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/664833/']","In fact, the ARIA 1.1 W3C recommendation states clearly one should not change the host language semantics in section 1.4 ([source](https://www.w3.org/TR/wai-aria-1.1/#co-evolution)): + +> +> ""It is not appropriate to create objects with style and script when +> the host language provides a semantic element for that type of object. +> While WAI-ARIA can improve the accessibility of these objects, +> accessibility is best provided by allowing the user agent to handle +> the object natively."" +> +> +> + +So, writing `` is not only redundant but against the recommendation.","Semantically speaking, a form by default is, well, a form. However, not all accessibility applications(screen readers, etc) are designed the same and some can use elements (even the form element) with the `role=form` attribute differently even if they understand that the parent form element will have the same semantic meaning with or without the `role=form` attribute." +27997,"Suppose I have a tesselation, e.g. the Stanford bunny: + +``` +bunny = Import[""http://graphics.stanford.edu/~mdfisher/Data/Meshes/bunny.obj"", ""OBJ""] + +``` + +![Stanford bunny](https://i.stack.imgur.com/lOysk.png) + +I'd like to be able to click on one of the vertices of the tessellation and either get its coordinates, or even better, its index in the `GraphicsComplex`. + +Is there a way to do this?",2013/07/03,"['https://mathematica.stackexchange.com/questions/27997', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1010/']","The following works pretty well, I think. The problem is choosing the point that is nearest the mouse click. `MousePosition[""Graphics3DBoxIntercepts""]` returns the coordinates of the two points of the bounding box below the mouse click, which I think of as determining a line. The function `projCoords` converts the points in the bunny to ""coordinates"" that are the distance from the line determined by these points divided by 10 and the distance of the projection of the vector from the front mouse-click intercept to the point on the bunny. The ""divide by 10"" factor makes the distance from the line dominant. Sometimes a point behind the surface may be chosen, especially in non-convex regions where there are not many points in front that are close to the line. If 10 is made much smaller, then a point close to the front box intercept but far from the line may be chosen. + +The point and the index in the `GraphicsComplex` are shown in the plot label. + +``` +bunny = Import[""http://graphics.stanford.edu/~mdfisher/Data/Meshes/bunny.obj"", ""OBJ""]; + +projCoords[{v1_, v2_}] := (* #/10 emphasizes distance from line of sight *) + Function[{u}, Norm /@ ({#/10, u - v1 - #} &@Projection[u - v1, v2 - v1])] + +DynamicModule[{img = bunny, pts0, clicked = {}, mp = {}}, + Cases[img, GraphicsComplex[pts_, ___] :> (pts0 = pts), Infinity, 1]; + EventHandler[ + MouseAppearance[ + Show[img, + Graphics3D[{Red, PointSize[Large], + Dynamic@If[VectorQ[clicked, NumericQ], + {Point[clicked], Blue, Line[mp]}, + {}]}], + Boxed -> True, Axes -> True, AxesLabel -> {x, y, z}, + PlotLabel -> Dynamic[{clicked, Position[pts0, clicked]}], + AbsoluteOptions[img, PlotRange], SphericalRegion -> True], + ""Arrow""], + {""MouseClicked"" :> ({clicked} = + Nearest[(projCoords[mp = MousePosition[""Graphics3DBoxIntercepts""]] /@ + pts0) -> pts0, {0, 0}])}, PassEventsDown -> True] + ] + +``` + +![Bunny with selected point](https://i.stack.imgur.com/3ewJE.png) + +The option `PassEventsDown -> True` allows the bunny to be rotated. + +**Edit**: Added `PlotRange` control and a `MouseAppearance` that makes it easier to pinpoint a vertex.","Perhaps you can use something like this: I took the points in the `GraphisComplex` and made an additional set of `Point`s representing the vertices in `Yellow`. The points are extracted and then put back by means of a replacement rule: + +``` +data = ExampleData[{""Geometry3D"", ""StanfordBunny""}, + ""VertexData""]; +bunny = + ListSurfacePlot3D[data, MaxPlotPoints -> 50, Boxed -> False, + Axes -> None, Mesh -> False, PlotStyle -> Brown]; + +Print@Show[ + bunny /. g_GraphicsComplex :> + GraphicsComplex[g[[1]], + Join[g[[2]], {Opacity[0.5], Yellow, PointSize[.01], + Tooltip[Point[#], #] & /@ Range[Length[g[[1]]]]}]], + ImageSize -> 500 + ] + +``` + +![bunny](https://i.stack.imgur.com/DLadx.png) + +You can still use the mouse to drag and rotate the object, but when you hover over a vertex (which sticks out of the surface as a yellow object), the index of that point in the `GraphicsComplex` is displayed as a `Tooltip`. I thought this is better than making the vertices clickable because that interferes with the 3D rotation. + +The extra `Print` in front of the `Show` is needed in order to suppress a warning triggered by the large size of the `Graphics3D` output. + +**Edit** + +If you want something that respons to mouse clicks in a useful way, it's straightforward to combine the above approach with [another answer](https://mathematica.stackexchange.com/a/16927/245) where I showed a way to convert `Tooltip` into `Button` objects. If you then use the `toolSpoolRule` from that answer, you can get a *permanent record* of the vertices that you have clicked, in the form of a `List` on the `Clipboard` which can be pasted anywhere you want. + +Here I repeat the only additional definition we need: + +``` +toolSpoolRule = + Tooltip[t__] :> + Button[Tooltip[t], + CopyToClipboard[ + First@Append[ + Cases[NotebookGet[ClipboardNotebook[]], + TooltipBox[x_, ""\""Clicked Points\"""", ___] :> + Tooltip[Append[ToExpression[x], Last[{t}]], + ""Clicked Points""], Infinity], + Tooltip[{Last[{t}]}, ""Clicked Points""]]]]; + +``` + +Now replace the plot command by the following: + +``` +Print[ + Show[bunny /. + g_GraphicsComplex :> + GraphicsComplex[g[[1]], + Join[g[[2]], {Opacity[0.5], Yellow, PointSize[.01], + Tooltip[Point[#], #] & /@ Range[Length[g[[1]]]]}]], + ImageSize -> 500] /. toolSpoolRule + ] + +``` + +You get visually the same output, but when you see a `Tooltip` appearing near a vertex that you hover on, you can now click the mouse to *add the vertex index to the clipboard*. When you're done, press the paste keys and you get a list of the clicked vertices." +68397282,"Regardless of the JSON object structure (simple or complex) what would be the ideal method to extract all urls from the following object into an array to iterate over in Javascript? + +``` + { + ""url"": ""https://example.com:443/-/media/images/site/info"", + ""data"": [ + { + ""id"": ""da56fac6-6907-4055-96b8-f8427d4c64fd"", + ""title"": ""AAAA 2021"", + ""time"": """", + ""dateStart"": ""2021-03-01T08:00:00Z"", + ""dateEnd"": ""2021-12-31T15:00:00Z"", + ""address"": """", + ""geo"": { + ""longitude"": """", + ""latitude"": """", + ""mapExternalLink"": """" + }, + ""price"": ""Free Admission"", + ""masonryImage"": ""https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx"", + ""image"": ""https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx"", + ""showDateInfo"": false, + ""showDateInfoOnListings"": false, + ""showTimeInfo"": false, + ""showTimeInfoOnListings"": false, + ""tags"": [ + { + ""key"": ""Lifestyle"", + ""name"": ""Lifestyle"" + } + ], + + ""partnerName"": """", + ""sort_data"": { + ""recommended"": 0, + ""recent"": 3, + ""partner"": 0, + ""popular"": 0 + } + } + ] +} + +``` + +I would like to get the results in an array such as: + +``` +[ +https://example.com:443/-/media/images/site/info,https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx, https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx +] + +``` + +I gather that i would need to apply some regex to extract the urls but not sure how to treat the json object as string for regex processing?",2021/07/15,"['https://Stackoverflow.com/questions/68397282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/358649/']","I think the better and easier way is to stringfy given json into string and solve it by regex. +But still if you need to solve it by recursive, try the codes below: + +``` +const obj = { + url: ""https://example.com:443/-/media/images/site/info"", + data: [ + { + id: ""da56fac6-6907-4055-96b8-f8427d4c64fd"", + title: ""AAAA 2021"", + time: """", + dateStart: ""2021-03-01T08:00:00Z"", + dateEnd: ""2021-12-31T15:00:00Z"", + address: """", + geo: { + longitude: """", + latitude: """", + mapExternalLink: """", + }, + price: ""Free Admission"", + masonryImage: + ""https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx"", + image: ""https://tw.yahoo.com"", + showDateInfo: false, + showDateInfoOnListings: false, + showTimeInfo: false, + showTimeInfoOnListings: false, + tags: [ + { + key: ""Lifestyle"", + name: ""Lifestyle"", + link: ""https://www.google.com"", + }, + ], + + partnerName: """", + sort_data: { + recommended: 0, + recent: 3, + partner: 0, + popular: 0, + anotherObj: { + link: ""https://www.github.com"", + }, + }, + }, + ], + }; + function getUrl(obj) { + const ary = []; + helper(obj, ary); + return ary; + } + + function helper(item, ary) { + if (typeof item === ""string"" && isUrl(item)) { + ary.push(item); + return; + } else if (typeof item === ""object"") { + for (const k in item) { + helper(item[k], ary); + } + return; + } + + return null; + } + + function isUrl(str) { + if (typeof str !== ""string"") return false; + return /http|https/.test(str); + } + + console.log(getUrl(obj)); + +``` + +But if you use this solution you need to transfer your json into js object","i'd agree to use a JSON parser, but if you want to do it with a regular expression, you might try this + +```js +console.log(JSON.stringify({ + ""url"": ""https://example.com:443/-/media/images/site/info"", + ""data"": [{ + ""id"": ""da56fac6-6907-4055-96b8-f8427d4c64fd"", + ""title"": ""AAAA 2021"", + ""time"": """", + ""dateStart"": ""2021-03-01T08:00:00Z"", + ""dateEnd"": ""2021-12-31T15:00:00Z"", + ""address"": """", + ""geo"": { + ""longitude"": """", + ""latitude"": """", + ""mapExternalLink"": """" + }, + ""price"": ""Free Admission"", + ""masonryImage"": ""https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx"", + ""image"": ""https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx"", + ""showDateInfo"": false, + ""showDateInfoOnListings"": false, + ""showTimeInfo"": false, + ""showTimeInfoOnListings"": false, + ""tags"": [{ + ""key"": ""Lifestyle"", + ""name"": ""Lifestyle"" + }], + + ""partnerName"": """", + ""sort_data"": { + ""recommended"": 0, + ""recent"": 3, + ""partner"": 0, + ""popular"": 0 + } + }] +}).match(/(?<="")https?:\/\/[^\""]+/g)); +``` + +`(?<="")https?:\/\/[^\""]+` basically finds patterns that start with a protocol scheme (http:// or https:// preceded by a `""` character) followed by anything that is *not* `""`" +50848178,"I tried to make a odd/even 'calculator' in python and it keeps popping up errors. Here's the code: + +``` +def odd_even(): + print(""Welcome to Odd/Even"") + num = input(""Pick a number: "") + num2 = num/2 + if num2 == int: + print(""This number is even"") + else: + print(""This number is odd"") + +``` + +Id like to know whats causing the errors and solutions to them",2018/06/14,"['https://Stackoverflow.com/questions/50848178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9394239/']","There is an error in the line: `num = input(""Pick a number: "")` +Because input method always returns a `String`,so you should convert it into int to performs the `integer` operation +The currect code is: + +``` +num =int( input(""Pick a number: "")) + +```","you can't do math with strings convert it to int + +``` +try: + num = int(input(""Pick a number: "")) +except ValueError: + print('This is not a number!') + return + +```" +52041232,"Here is my problem, I would like to map a dictionary in a DataFrame but I cannot find a way to do that when the dictionary has several keys. Note that these keys are present in different columns in the DataFrame. + +Here is an example: + +this is the dataframe I have at the begining, df: + +``` + Index key +0 10 k1 +1 12 k2 +2 3 k1 +3 34 k3 + +``` + +here is the dictionary I have, d: + +``` +{('k1', 10):v1,('k1', 3):v2,('k2', 12):v3,('k3', 34):v4} + +``` + +I would like to have at the end, df: + +``` + Index key value +0 10 k1 v1 +1 12 k2 v2 +2 3 k1 v3 +3 34 k3 v4 + +``` + +is there a way to do that the same way that you can do that when you have a one key dictionary : + +> +> df[""value""] = df[""key""].map(d) +> +> +> + +thank you in advance.",2018/08/27,"['https://Stackoverflow.com/questions/52041232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10028348/']","It is explained in the [Java Language Specification](https://docs.oracle.com/javase/specs/jls/se10/html/jls-11.html#jls-11.2.3) (emphasis in bold): + +> +> It is a compile-time error if a `catch` clause *can catch* checked exception class E1 and it is not the case that the `try` block corresponding to the `catch` clause *can throw* a checked exception class that is a subclass or superclass of E1, **unless E1 is `Exception` or a superclass of `Exception`.** +> +> +> + +I guess the rationale behind this is that: `MyException` is indeed a checked exception. However, unchecked exceptions also extend `Exception` (transitive inheritance from `RuntimeException`), so having a `catch` include the `Exception` class is excluded from the exception analysis done by the compiler.","Exception extends from `RuntimeException` will considered as uncheched exception, so it's ok: + +``` +class MyException extends RuntimeException { } + +try { + ... +} catch (MyException e) { + +} + +``` + +Your exception extends from `Throwable`, so it is cheched exception. Since the compiler noticed that it is never thrown, so the compile fails." +30365008,"Hi guys i'm doing some automations scripts with Watir and trying to create a ruby class to make it better but i'm having this error: + +> +> examen.rb:6:in 'enterEmail': undefined method 'text\_field' for # (NoMethodError) +> +> +> + +This is part of my conflictive code: + +``` +require 'watir-webdriver' +class LoginPage + def enterEmail (email) + text_field(:user, :id => 'user_email').set email + end +end + +``` + +The problem that i see is: i did not define the 'text\_field()' method in my class just because is a Watir method... Anyone knows how can i use the watir method in the classes that i create?",2015/05/21,"['https://Stackoverflow.com/questions/30365008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3247357/']","`text_field` is an instance method of The `Watir::Browser` class. If you want to use it, you have to call it on an instance of that class. + +``` +class LoginPage + def initialize() + @b = Watir::Browser.new + end + + def enterEmail (email) + @b.text_field(:user, :id => 'user_email').set email + end +end + +```","Indeed, your class does not have any `text_field` method. This method is a defined on `Watir::Browser` instance. In your example, haven't created one. + +``` +class LoginPage + def initialize + @browser = Watir::Browser.new + @browser.goto ""http://example.com"" + end + + def enterEmail (email) + @browser.text_field(:user, :id => 'user_email').set email + end +end + +```" +30365008,"Hi guys i'm doing some automations scripts with Watir and trying to create a ruby class to make it better but i'm having this error: + +> +> examen.rb:6:in 'enterEmail': undefined method 'text\_field' for # (NoMethodError) +> +> +> + +This is part of my conflictive code: + +``` +require 'watir-webdriver' +class LoginPage + def enterEmail (email) + text_field(:user, :id => 'user_email').set email + end +end + +``` + +The problem that i see is: i did not define the 'text\_field()' method in my class just because is a Watir method... Anyone knows how can i use the watir method in the classes that i create?",2015/05/21,"['https://Stackoverflow.com/questions/30365008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3247357/']","`text_field` is an instance method of The `Watir::Browser` class. If you want to use it, you have to call it on an instance of that class. + +``` +class LoginPage + def initialize() + @b = Watir::Browser.new + end + + def enterEmail (email) + @b.text_field(:user, :id => 'user_email').set email + end +end + +```","Both Yossi and Martin have correct answers. But because you're defining a `LoginPage` class, you should probably look into the [page-object](http://github.com/cheezy/page-object) gem. This lets you define a `text_field` almost identical to the code you already have. Your class would look like: + +``` +class LoginPage + include PageObject + + text_field(:user, :id => 'user_email') + + def enter_email(email) + self.user = email + end +end + +``` + +And you'd execute it like: + +``` +login = LoginPage.new(browser) +login.enter_email(""my_email@example.com"") + +```" +9324563,"Consider the following registry export: + +```none +Windows Registry Editor Version 5.00 + +[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\WinSock2\Parameters\Protocol_Catalog9\Catalog_Entries\000000000001] +;... +""ProtocolName""=""@%SystemRoot%\\System32\\wshtcpip.dll,-60100"" + +``` + +The intention here appears to be for someone to load the DLL in question, and use some form of API retrieve the actual name. But I don't know what that API is :/ + +I'd like to avoid loading the DLL into my address space (and thus call `DLL_PROCESS_ATTACH`) if at all possible; can't really trust third party DLLs to be trustworthy.",2012/02/17,"['https://Stackoverflow.com/questions/9324563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82320/']","[`RegLoadMUIString`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms724890.aspx) will do the necessary for you. Note however, that it was introduced in Vista so won't help if you need to support XP. + +If you want to avoid code in the DLL running whilst you extract resources, use [`LoadLibraryEx`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms684179.aspx) passing `LOAD_LIBRARY_AS_IMAGE_RESOURCE | LOAD_LIBRARY_AS_DATAFILE`, or possibly `LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE`. Once you have done that, you can call [`LoadString`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms647486.aspx) to extract the MUI value.","This is going to help: + +``` +HMODULE hModule = LoadLibrary(_T(""wshtcpip.dll"")); // LoadLibraryEx is even better +TCHAR pszValue[1024] = { 0 }; +INT nResult = LoadString(hModule, 60100, pszValue, _countof(pszValue)); + +``` + +`LoadString` will take care of downloading resource from MUI, if needed. LoadString uses thread locale, which you might want to override prior to the call. + +Also: [Loading Language Resources](http://msdn.microsoft.com/en-us/library/windows/desktop/dd318708%28v=vs.85%29.aspx) on MSDN." +8609546,"I'm using maven and the maven-javadoc-plugin with the umlgraph-doclet to create javadoc for my project. The part from my pom: + +``` + + + + org.apache.maven.plugins + maven-site-plugin + false + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + public + true + + org.umlgraph.doclet.UmlGraphDoc + + org.umlgraph + doclet + 5.1 + + + true + + -inferrel -inferdep -quiet -hide java.* -hide org.eclipse.* -collpackages java.util.* -postfixpackage + -nodefontsize 9 -nodefontpackagesize 7 -attributes -types -visibility -operations -constructors + -enumerations -enumconstants -views + + + + + + aggregate + + + + + + + + + + +``` + +The images are generated and look fine, when building the javadoc with jdk1.6 they get automatically integrated into all javadoc pages. But when building with jdk1.7, the images still get created but are not inside the javadoc pages. Even when using the v5.4 from the official website, the javadoc is imageless. And the debug output of maven also don't give any clue. On top of that, there is no way of contacting one of the UmlGraph devs by mail. + +Can anyone give me some advice here, or have some ideas how to fix that?",2011/12/22,"['https://Stackoverflow.com/questions/8609546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094486/']","UmlGraphDoc version 5.4, altering javadocs +Warning, could not find a line that matches the pattern '/H2' + +The HTML is simply different. + +Java7 JavaDocs +START OF CLASS DATA +h2 title=""blah blah + +Java6 JavaDocs +START OF CLASS DATA +H2 + +You can decompile and modify UmlGraphDoc.java","I have the same problem. My guess is that it's this bug: + +" +8609546,"I'm using maven and the maven-javadoc-plugin with the umlgraph-doclet to create javadoc for my project. The part from my pom: + +``` + + + + org.apache.maven.plugins + maven-site-plugin + false + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + public + true + + org.umlgraph.doclet.UmlGraphDoc + + org.umlgraph + doclet + 5.1 + + + true + + -inferrel -inferdep -quiet -hide java.* -hide org.eclipse.* -collpackages java.util.* -postfixpackage + -nodefontsize 9 -nodefontpackagesize 7 -attributes -types -visibility -operations -constructors + -enumerations -enumconstants -views + + + + + + aggregate + + + + + + + + + + +``` + +The images are generated and look fine, when building the javadoc with jdk1.6 they get automatically integrated into all javadoc pages. But when building with jdk1.7, the images still get created but are not inside the javadoc pages. Even when using the v5.4 from the official website, the javadoc is imageless. And the debug output of maven also don't give any clue. On top of that, there is no way of contacting one of the UmlGraph devs by mail. + +Can anyone give me some advice here, or have some ideas how to fix that?",2011/12/22,"['https://Stackoverflow.com/questions/8609546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094486/']","I checked the possibilities, and the situation is following:. + +* relevant bug in the UmlGraph has been already fixed: +* problem is however that no stable version of UmlGraph has been released yet that would include the fix + +However good news is that there exists snapshot repository containing the fix: + +Therefor you need to get the jar file to your local repository (depending on your infrastructure setup): + +* either by adding reffered repository to your environment +* or by importing to your local repo () + +afterwards update: + +``` +org.umlgraph.doclet.UmlGraphDoc + + org.umlgraph + doclet + 5.1 + + +``` + +to the following (naming convention has been changed): + +``` +org.umlgraph.doclet.UmlGraphDoc + + org.umlgraph + umlgraph + 5.5.8-SNAPSHOT + + +```","I have the same problem. My guess is that it's this bug: + +" +8609546,"I'm using maven and the maven-javadoc-plugin with the umlgraph-doclet to create javadoc for my project. The part from my pom: + +``` + + + + org.apache.maven.plugins + maven-site-plugin + false + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + public + true + + org.umlgraph.doclet.UmlGraphDoc + + org.umlgraph + doclet + 5.1 + + + true + + -inferrel -inferdep -quiet -hide java.* -hide org.eclipse.* -collpackages java.util.* -postfixpackage + -nodefontsize 9 -nodefontpackagesize 7 -attributes -types -visibility -operations -constructors + -enumerations -enumconstants -views + + + + + + aggregate + + + + + + + + + + +``` + +The images are generated and look fine, when building the javadoc with jdk1.6 they get automatically integrated into all javadoc pages. But when building with jdk1.7, the images still get created but are not inside the javadoc pages. Even when using the v5.4 from the official website, the javadoc is imageless. And the debug output of maven also don't give any clue. On top of that, there is no way of contacting one of the UmlGraph devs by mail. + +Can anyone give me some advice here, or have some ideas how to fix that?",2011/12/22,"['https://Stackoverflow.com/questions/8609546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094486/']","Update: version 5.6.6 is now on maven central. I built with JDK 7 and diagrams look ok. + +``` + + maven-javadoc-plugin + 2.7 + + true + private + org.umlgraph.doclet.UmlGraphDoc + + org.umlgraph + umlgraph + 5.6.6 + + + + +```","I have the same problem. My guess is that it's this bug: + +" +8609546,"I'm using maven and the maven-javadoc-plugin with the umlgraph-doclet to create javadoc for my project. The part from my pom: + +``` + + + + org.apache.maven.plugins + maven-site-plugin + false + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + public + true + + org.umlgraph.doclet.UmlGraphDoc + + org.umlgraph + doclet + 5.1 + + + true + + -inferrel -inferdep -quiet -hide java.* -hide org.eclipse.* -collpackages java.util.* -postfixpackage + -nodefontsize 9 -nodefontpackagesize 7 -attributes -types -visibility -operations -constructors + -enumerations -enumconstants -views + + + + + + aggregate + + + + + + + + + + +``` + +The images are generated and look fine, when building the javadoc with jdk1.6 they get automatically integrated into all javadoc pages. But when building with jdk1.7, the images still get created but are not inside the javadoc pages. Even when using the v5.4 from the official website, the javadoc is imageless. And the debug output of maven also don't give any clue. On top of that, there is no way of contacting one of the UmlGraph devs by mail. + +Can anyone give me some advice here, or have some ideas how to fix that?",2011/12/22,"['https://Stackoverflow.com/questions/8609546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094486/']","I checked the possibilities, and the situation is following:. + +* relevant bug in the UmlGraph has been already fixed: +* problem is however that no stable version of UmlGraph has been released yet that would include the fix + +However good news is that there exists snapshot repository containing the fix: + +Therefor you need to get the jar file to your local repository (depending on your infrastructure setup): + +* either by adding reffered repository to your environment +* or by importing to your local repo () + +afterwards update: + +``` +org.umlgraph.doclet.UmlGraphDoc + + org.umlgraph + doclet + 5.1 + + +``` + +to the following (naming convention has been changed): + +``` +org.umlgraph.doclet.UmlGraphDoc + + org.umlgraph + umlgraph + 5.5.8-SNAPSHOT + + +```","UmlGraphDoc version 5.4, altering javadocs +Warning, could not find a line that matches the pattern '/H2' + +The HTML is simply different. + +Java7 JavaDocs +START OF CLASS DATA +h2 title=""blah blah + +Java6 JavaDocs +START OF CLASS DATA +H2 + +You can decompile and modify UmlGraphDoc.java" +8609546,"I'm using maven and the maven-javadoc-plugin with the umlgraph-doclet to create javadoc for my project. The part from my pom: + +``` + + + + org.apache.maven.plugins + maven-site-plugin + false + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + public + true + + org.umlgraph.doclet.UmlGraphDoc + + org.umlgraph + doclet + 5.1 + + + true + + -inferrel -inferdep -quiet -hide java.* -hide org.eclipse.* -collpackages java.util.* -postfixpackage + -nodefontsize 9 -nodefontpackagesize 7 -attributes -types -visibility -operations -constructors + -enumerations -enumconstants -views + + + + + + aggregate + + + + + + + + + + +``` + +The images are generated and look fine, when building the javadoc with jdk1.6 they get automatically integrated into all javadoc pages. But when building with jdk1.7, the images still get created but are not inside the javadoc pages. Even when using the v5.4 from the official website, the javadoc is imageless. And the debug output of maven also don't give any clue. On top of that, there is no way of contacting one of the UmlGraph devs by mail. + +Can anyone give me some advice here, or have some ideas how to fix that?",2011/12/22,"['https://Stackoverflow.com/questions/8609546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094486/']","Update: version 5.6.6 is now on maven central. I built with JDK 7 and diagrams look ok. + +``` + + maven-javadoc-plugin + 2.7 + + true + private + org.umlgraph.doclet.UmlGraphDoc + + org.umlgraph + umlgraph + 5.6.6 + + + + +```","UmlGraphDoc version 5.4, altering javadocs +Warning, could not find a line that matches the pattern '/H2' + +The HTML is simply different. + +Java7 JavaDocs +START OF CLASS DATA +h2 title=""blah blah + +Java6 JavaDocs +START OF CLASS DATA +H2 + +You can decompile and modify UmlGraphDoc.java" +5808172,"I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: + +``` +string htmlFlightDetailsJavaScript ; + +``` + +In the string there are few div and tables which have class propeties. something like div class=""bla"" + +``` +ClientScriptManager cs = Page.ClientScript; +StringBuilder csText = new StringBuilder(); +csText.Append(""fill(""+htmlFlightDetailsJavaScript+"");""); +cs.RegisterStartupScript(this.GetType(), ""alert"", csText.ToString(), true); + +``` + +Here is my javascript function: + +``` +function fill(b) +{ + alert(b); +} + +``` + +Note that my javascript function is on the ~.aspx. + +I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? + +Thank you very much",2011/04/27,"['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']",You can use the [ClientScriptManager.RegisterStartupScript](http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx) method.,"I'd take a step back and examine whether the entire HTML block is really so dynamic that it needs to be passed into the function as a parameter. + +The easier way would be to have the HTML element emitted as part of the page, then augment that from your function. ie. show or hide it. + +If your scenario still requires you to pass the HTML as a parameter, you'll need to [HTML encode](http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx) the entire string on the server side, and then [Unencode](https://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding) in JS." +5808172,"I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: + +``` +string htmlFlightDetailsJavaScript ; + +``` + +In the string there are few div and tables which have class propeties. something like div class=""bla"" + +``` +ClientScriptManager cs = Page.ClientScript; +StringBuilder csText = new StringBuilder(); +csText.Append(""fill(""+htmlFlightDetailsJavaScript+"");""); +cs.RegisterStartupScript(this.GetType(), ""alert"", csText.ToString(), true); + +``` + +Here is my javascript function: + +``` +function fill(b) +{ + alert(b); +} + +``` + +Note that my javascript function is on the ~.aspx. + +I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? + +Thank you very much",2011/04/27,"['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']","If the classes in `htmlFlightDetailsJavaScript` are in the form `div class=""bla""` you likely have to escape the quotes in the string or use single quotes, e.g. `div class='bla'`.","I'd take a step back and examine whether the entire HTML block is really so dynamic that it needs to be passed into the function as a parameter. + +The easier way would be to have the HTML element emitted as part of the page, then augment that from your function. ie. show or hide it. + +If your scenario still requires you to pass the HTML as a parameter, you'll need to [HTML encode](http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx) the entire string on the server side, and then [Unencode](https://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding) in JS." +5808172,"I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: + +``` +string htmlFlightDetailsJavaScript ; + +``` + +In the string there are few div and tables which have class propeties. something like div class=""bla"" + +``` +ClientScriptManager cs = Page.ClientScript; +StringBuilder csText = new StringBuilder(); +csText.Append(""fill(""+htmlFlightDetailsJavaScript+"");""); +cs.RegisterStartupScript(this.GetType(), ""alert"", csText.ToString(), true); + +``` + +Here is my javascript function: + +``` +function fill(b) +{ + alert(b); +} + +``` + +Note that my javascript function is on the ~.aspx. + +I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? + +Thank you very much",2011/04/27,"['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']","**This sounds like invalid Javascript is being generated**. + +This hypothesis can be verified with inspecting the *actual* Javascript transmitted and verifying the entire result, in context, for correctness. + +That is, imagine that this invalid Javascript was generated: + +``` +alert(""
"") + +``` + +**To fix this, ensure the strings literals inserted into the Javascript are valid.** + +For instance, the above might be written (using the following code) as: + +``` +RegisterClientScriptBlock(JsEncoder.Format(@""alert(""""{0}"""");"", theInput)) + +``` + +...and it won't break because the string is escaped before. (Take a look at this output and compare: the inserted literal will be still valid Javascript, even with quotes or other characters in the `theInput`. As an added bonus, `` to break the code either ;-) + +This code is ""free to use, modify, sell, whatever"". YMMV. + +``` +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace sbcjc.sei +{ + public class JsEncoder + { + static Regex EncodeLiteralRegex; + + // Format a bunch of literals. + public static string Format (string format, params object[] items) + { + return string.Format(format, + items.Select(item => EncodeString("""" + item)).ToArray()); + } + + // Given a string, return a string suitable for safe + // use within a Javascript literal inside a `, `>`, and XML vs HTML issues) + // ""/"" is not allowed because it requires an escape in JSON + var accepted = Enumerable.Range(32, 127 - 32) + .Except(new int[] { '""', '\'', '\\', '&', '<', '>', '/' }); + // pattern matches everything but accepted + EncodeLiteralRegex = new Regex(""[^"" + + string.Join("""", accepted.Select(c => @""\x"" + c.ToString(""x2"")).ToArray()) + + ""]""); + } + return EncodeLiteralRegex.Replace(value ?? """", (match) => + { + var ch = (int)match.Value[0]; // only matches a character at a time + return ch <= 127 + ? @""\x"" + ch.ToString(""x2"") // not JSON + : @""\u"" + ch.ToString(""x4""); + }); + } + } +} + +``` + +Happy coding.","I guess you can accomplish much faster if you use an ajax call and a partial control (user control) or write the content yourself. + +1) The user control will render your html data. +2) The page code behind will receive the ajax call and call the method thal will render the partial control or write. +3) The method will write on Response.Output stream and end the Response (Response.End()) +4) The javascript will handle the response and show the result. + +(using jQuery) + +``` +// main.js + +jQuery.ajax({ + type: 'POST', + data: { isajax: true, ajaxcall: 'MyMethod' }, + dataType: 'html', + success: function (data, textStatus, jqXHR) { + alert(data); + } +}); + +// CodeBehind +protected void Page_Load(object sender, EventArgs e) +{ + if (Request.HttpMethod == ""POST"" && Request[""isajax""] == ""true"") + { + this.AjaxCall(Request); + } +} + +private void AjaxCall(HttpRequest request) +{ + switch (request[""ajaxcall""]) + { + case ""MyMethod"": this.MyMethod(request); break; + default: break; + } +} + +private void MyMethod(HttpRequest request) +{ + Response.ContentType = ""text/html""; + + Response.Write(""YOUR CONTENT GOES HERE.""); + // Or, render a User Control + + Response.End(); +} + +``` + +P.S.: You can use a Generic Handler if you wish to. Just add the url option to jQuery ajax method. + +Let me know if it helps." +5808172,"I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: + +``` +string htmlFlightDetailsJavaScript ; + +``` + +In the string there are few div and tables which have class propeties. something like div class=""bla"" + +``` +ClientScriptManager cs = Page.ClientScript; +StringBuilder csText = new StringBuilder(); +csText.Append(""fill(""+htmlFlightDetailsJavaScript+"");""); +cs.RegisterStartupScript(this.GetType(), ""alert"", csText.ToString(), true); + +``` + +Here is my javascript function: + +``` +function fill(b) +{ + alert(b); +} + +``` + +Note that my javascript function is on the ~.aspx. + +I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? + +Thank you very much",2011/04/27,"['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']","**This sounds like invalid Javascript is being generated**. + +This hypothesis can be verified with inspecting the *actual* Javascript transmitted and verifying the entire result, in context, for correctness. + +That is, imagine that this invalid Javascript was generated: + +``` +alert(""
"") + +``` + +**To fix this, ensure the strings literals inserted into the Javascript are valid.** + +For instance, the above might be written (using the following code) as: + +``` +RegisterClientScriptBlock(JsEncoder.Format(@""alert(""""{0}"""");"", theInput)) + +``` + +...and it won't break because the string is escaped before. (Take a look at this output and compare: the inserted literal will be still valid Javascript, even with quotes or other characters in the `theInput`. As an added bonus, `` to break the code either ;-) + +This code is ""free to use, modify, sell, whatever"". YMMV. + +``` +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace sbcjc.sei +{ + public class JsEncoder + { + static Regex EncodeLiteralRegex; + + // Format a bunch of literals. + public static string Format (string format, params object[] items) + { + return string.Format(format, + items.Select(item => EncodeString("""" + item)).ToArray()); + } + + // Given a string, return a string suitable for safe + // use within a Javascript literal inside a `, `>`, and XML vs HTML issues) + // ""/"" is not allowed because it requires an escape in JSON + var accepted = Enumerable.Range(32, 127 - 32) + .Except(new int[] { '""', '\'', '\\', '&', '<', '>', '/' }); + // pattern matches everything but accepted + EncodeLiteralRegex = new Regex(""[^"" + + string.Join("""", accepted.Select(c => @""\x"" + c.ToString(""x2"")).ToArray()) + + ""]""); + } + return EncodeLiteralRegex.Replace(value ?? """", (match) => + { + var ch = (int)match.Value[0]; // only matches a character at a time + return ch <= 127 + ? @""\x"" + ch.ToString(""x2"") // not JSON + : @""\u"" + ch.ToString(""x4""); + }); + } + } +} + +``` + +Happy coding.","Use the RegisterClientScriptBlock() method and make sure to escape your quotes in your HTML. + +""
""" +5808172,"I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: + +``` +string htmlFlightDetailsJavaScript ; + +``` + +In the string there are few div and tables which have class propeties. something like div class=""bla"" + +``` +ClientScriptManager cs = Page.ClientScript; +StringBuilder csText = new StringBuilder(); +csText.Append(""fill(""+htmlFlightDetailsJavaScript+"");""); +cs.RegisterStartupScript(this.GetType(), ""alert"", csText.ToString(), true); + +``` + +Here is my javascript function: + +``` +function fill(b) +{ + alert(b); +} + +``` + +Note that my javascript function is on the ~.aspx. + +I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? + +Thank you very much",2011/04/27,"['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']","**This sounds like invalid Javascript is being generated**. + +This hypothesis can be verified with inspecting the *actual* Javascript transmitted and verifying the entire result, in context, for correctness. + +That is, imagine that this invalid Javascript was generated: + +``` +alert(""
"") + +``` + +**To fix this, ensure the strings literals inserted into the Javascript are valid.** + +For instance, the above might be written (using the following code) as: + +``` +RegisterClientScriptBlock(JsEncoder.Format(@""alert(""""{0}"""");"", theInput)) + +``` + +...and it won't break because the string is escaped before. (Take a look at this output and compare: the inserted literal will be still valid Javascript, even with quotes or other characters in the `theInput`. As an added bonus, `` to break the code either ;-) + +This code is ""free to use, modify, sell, whatever"". YMMV. + +``` +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace sbcjc.sei +{ + public class JsEncoder + { + static Regex EncodeLiteralRegex; + + // Format a bunch of literals. + public static string Format (string format, params object[] items) + { + return string.Format(format, + items.Select(item => EncodeString("""" + item)).ToArray()); + } + + // Given a string, return a string suitable for safe + // use within a Javascript literal inside a `, `>`, and XML vs HTML issues) + // ""/"" is not allowed because it requires an escape in JSON + var accepted = Enumerable.Range(32, 127 - 32) + .Except(new int[] { '""', '\'', '\\', '&', '<', '>', '/' }); + // pattern matches everything but accepted + EncodeLiteralRegex = new Regex(""[^"" + + string.Join("""", accepted.Select(c => @""\x"" + c.ToString(""x2"")).ToArray()) + + ""]""); + } + return EncodeLiteralRegex.Replace(value ?? """", (match) => + { + var ch = (int)match.Value[0]; // only matches a character at a time + return ch <= 127 + ? @""\x"" + ch.ToString(""x2"") // not JSON + : @""\u"" + ch.ToString(""x4""); + }); + } + } +} + +``` + +Happy coding.","I'd take a step back and examine whether the entire HTML block is really so dynamic that it needs to be passed into the function as a parameter. + +The easier way would be to have the HTML element emitted as part of the page, then augment that from your function. ie. show or hide it. + +If your scenario still requires you to pass the HTML as a parameter, you'll need to [HTML encode](http://msdn.microsoft.com/en-us/library/w3te6wfz.aspx) the entire string on the server side, and then [Unencode](https://stackoverflow.com/questions/1219860/javascript-jquery-html-encoding) in JS." +5808172,"I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: + +``` +string htmlFlightDetailsJavaScript ; + +``` + +In the string there are few div and tables which have class propeties. something like div class=""bla"" + +``` +ClientScriptManager cs = Page.ClientScript; +StringBuilder csText = new StringBuilder(); +csText.Append(""fill(""+htmlFlightDetailsJavaScript+"");""); +cs.RegisterStartupScript(this.GetType(), ""alert"", csText.ToString(), true); + +``` + +Here is my javascript function: + +``` +function fill(b) +{ + alert(b); +} + +``` + +Note that my javascript function is on the ~.aspx. + +I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? + +Thank you very much",2011/04/27,"['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']","Use the RegisterClientScriptBlock() method and make sure to escape your quotes in your HTML. + +""
""","I guess you can accomplish much faster if you use an ajax call and a partial control (user control) or write the content yourself. + +1) The user control will render your html data. +2) The page code behind will receive the ajax call and call the method thal will render the partial control or write. +3) The method will write on Response.Output stream and end the Response (Response.End()) +4) The javascript will handle the response and show the result. + +(using jQuery) + +``` +// main.js + +jQuery.ajax({ + type: 'POST', + data: { isajax: true, ajaxcall: 'MyMethod' }, + dataType: 'html', + success: function (data, textStatus, jqXHR) { + alert(data); + } +}); + +// CodeBehind +protected void Page_Load(object sender, EventArgs e) +{ + if (Request.HttpMethod == ""POST"" && Request[""isajax""] == ""true"") + { + this.AjaxCall(Request); + } +} + +private void AjaxCall(HttpRequest request) +{ + switch (request[""ajaxcall""]) + { + case ""MyMethod"": this.MyMethod(request); break; + default: break; + } +} + +private void MyMethod(HttpRequest request) +{ + Response.ContentType = ""text/html""; + + Response.Write(""YOUR CONTENT GOES HERE.""); + // Or, render a User Control + + Response.End(); +} + +``` + +P.S.: You can use a Generic Handler if you wish to. Just add the url option to jQuery ajax method. + +Let me know if it helps." +5808172,"I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: + +``` +string htmlFlightDetailsJavaScript ; + +``` + +In the string there are few div and tables which have class propeties. something like div class=""bla"" + +``` +ClientScriptManager cs = Page.ClientScript; +StringBuilder csText = new StringBuilder(); +csText.Append(""fill(""+htmlFlightDetailsJavaScript+"");""); +cs.RegisterStartupScript(this.GetType(), ""alert"", csText.ToString(), true); + +``` + +Here is my javascript function: + +``` +function fill(b) +{ + alert(b); +} + +``` + +Note that my javascript function is on the ~.aspx. + +I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? + +Thank you very much",2011/04/27,"['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']",You can use the [ClientScriptManager.RegisterStartupScript](http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx) method.,"I guess you can accomplish much faster if you use an ajax call and a partial control (user control) or write the content yourself. + +1) The user control will render your html data. +2) The page code behind will receive the ajax call and call the method thal will render the partial control or write. +3) The method will write on Response.Output stream and end the Response (Response.End()) +4) The javascript will handle the response and show the result. + +(using jQuery) + +``` +// main.js + +jQuery.ajax({ + type: 'POST', + data: { isajax: true, ajaxcall: 'MyMethod' }, + dataType: 'html', + success: function (data, textStatus, jqXHR) { + alert(data); + } +}); + +// CodeBehind +protected void Page_Load(object sender, EventArgs e) +{ + if (Request.HttpMethod == ""POST"" && Request[""isajax""] == ""true"") + { + this.AjaxCall(Request); + } +} + +private void AjaxCall(HttpRequest request) +{ + switch (request[""ajaxcall""]) + { + case ""MyMethod"": this.MyMethod(request); break; + default: break; + } +} + +private void MyMethod(HttpRequest request) +{ + Response.ContentType = ""text/html""; + + Response.Write(""YOUR CONTENT GOES HERE.""); + // Or, render a User Control + + Response.End(); +} + +``` + +P.S.: You can use a Generic Handler if you wish to. Just add the url option to jQuery ajax method. + +Let me know if it helps." +5808172,"I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: + +``` +string htmlFlightDetailsJavaScript ; + +``` + +In the string there are few div and tables which have class propeties. something like div class=""bla"" + +``` +ClientScriptManager cs = Page.ClientScript; +StringBuilder csText = new StringBuilder(); +csText.Append(""fill(""+htmlFlightDetailsJavaScript+"");""); +cs.RegisterStartupScript(this.GetType(), ""alert"", csText.ToString(), true); + +``` + +Here is my javascript function: + +``` +function fill(b) +{ + alert(b); +} + +``` + +Note that my javascript function is on the ~.aspx. + +I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? + +Thank you very much",2011/04/27,"['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']","**This sounds like invalid Javascript is being generated**. + +This hypothesis can be verified with inspecting the *actual* Javascript transmitted and verifying the entire result, in context, for correctness. + +That is, imagine that this invalid Javascript was generated: + +``` +alert(""
"") + +``` + +**To fix this, ensure the strings literals inserted into the Javascript are valid.** + +For instance, the above might be written (using the following code) as: + +``` +RegisterClientScriptBlock(JsEncoder.Format(@""alert(""""{0}"""");"", theInput)) + +``` + +...and it won't break because the string is escaped before. (Take a look at this output and compare: the inserted literal will be still valid Javascript, even with quotes or other characters in the `theInput`. As an added bonus, `` to break the code either ;-) + +This code is ""free to use, modify, sell, whatever"". YMMV. + +``` +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace sbcjc.sei +{ + public class JsEncoder + { + static Regex EncodeLiteralRegex; + + // Format a bunch of literals. + public static string Format (string format, params object[] items) + { + return string.Format(format, + items.Select(item => EncodeString("""" + item)).ToArray()); + } + + // Given a string, return a string suitable for safe + // use within a Javascript literal inside a `, `>`, and XML vs HTML issues) + // ""/"" is not allowed because it requires an escape in JSON + var accepted = Enumerable.Range(32, 127 - 32) + .Except(new int[] { '""', '\'', '\\', '&', '<', '>', '/' }); + // pattern matches everything but accepted + EncodeLiteralRegex = new Regex(""[^"" + + string.Join("""", accepted.Select(c => @""\x"" + c.ToString(""x2"")).ToArray()) + + ""]""); + } + return EncodeLiteralRegex.Replace(value ?? """", (match) => + { + var ch = (int)match.Value[0]; // only matches a character at a time + return ch <= 127 + ? @""\x"" + ch.ToString(""x2"") // not JSON + : @""\u"" + ch.ToString(""x4""); + }); + } + } +} + +``` + +Happy coding.",You can use the [ClientScriptManager.RegisterStartupScript](http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx) method. +5808172,"I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: + +``` +string htmlFlightDetailsJavaScript ; + +``` + +In the string there are few div and tables which have class propeties. something like div class=""bla"" + +``` +ClientScriptManager cs = Page.ClientScript; +StringBuilder csText = new StringBuilder(); +csText.Append(""fill(""+htmlFlightDetailsJavaScript+"");""); +cs.RegisterStartupScript(this.GetType(), ""alert"", csText.ToString(), true); + +``` + +Here is my javascript function: + +``` +function fill(b) +{ + alert(b); +} + +``` + +Note that my javascript function is on the ~.aspx. + +I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? + +Thank you very much",2011/04/27,"['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']","**This sounds like invalid Javascript is being generated**. + +This hypothesis can be verified with inspecting the *actual* Javascript transmitted and verifying the entire result, in context, for correctness. + +That is, imagine that this invalid Javascript was generated: + +``` +alert(""
"") + +``` + +**To fix this, ensure the strings literals inserted into the Javascript are valid.** + +For instance, the above might be written (using the following code) as: + +``` +RegisterClientScriptBlock(JsEncoder.Format(@""alert(""""{0}"""");"", theInput)) + +``` + +...and it won't break because the string is escaped before. (Take a look at this output and compare: the inserted literal will be still valid Javascript, even with quotes or other characters in the `theInput`. As an added bonus, `` to break the code either ;-) + +This code is ""free to use, modify, sell, whatever"". YMMV. + +``` +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace sbcjc.sei +{ + public class JsEncoder + { + static Regex EncodeLiteralRegex; + + // Format a bunch of literals. + public static string Format (string format, params object[] items) + { + return string.Format(format, + items.Select(item => EncodeString("""" + item)).ToArray()); + } + + // Given a string, return a string suitable for safe + // use within a Javascript literal inside a `, `>`, and XML vs HTML issues) + // ""/"" is not allowed because it requires an escape in JSON + var accepted = Enumerable.Range(32, 127 - 32) + .Except(new int[] { '""', '\'', '\\', '&', '<', '>', '/' }); + // pattern matches everything but accepted + EncodeLiteralRegex = new Regex(""[^"" + + string.Join("""", accepted.Select(c => @""\x"" + c.ToString(""x2"")).ToArray()) + + ""]""); + } + return EncodeLiteralRegex.Replace(value ?? """", (match) => + { + var ch = (int)match.Value[0]; // only matches a character at a time + return ch <= 127 + ? @""\x"" + ch.ToString(""x2"") // not JSON + : @""\u"" + ch.ToString(""x4""); + }); + } + } +} + +``` + +Happy coding.","If the classes in `htmlFlightDetailsJavaScript` are in the form `div class=""bla""` you likely have to escape the quotes in the string or use single quotes, e.g. `div class='bla'`." +5808172,"I am currently working on my final thesis.I have a small problem.I need to pass a HTML block which is a string block to a javascript function.I have to do this from code behind.I have tried it so much I doesnt seem as it is going to work.Here is the code in code-behind: + +``` +string htmlFlightDetailsJavaScript ; + +``` + +In the string there are few div and tables which have class propeties. something like div class=""bla"" + +``` +ClientScriptManager cs = Page.ClientScript; +StringBuilder csText = new StringBuilder(); +csText.Append(""fill(""+htmlFlightDetailsJavaScript+"");""); +cs.RegisterStartupScript(this.GetType(), ""alert"", csText.ToString(), true); + +``` + +Here is my javascript function: + +``` +function fill(b) +{ + alert(b); +} + +``` + +Note that my javascript function is on the ~.aspx. + +I have tried to pass the string without classes which are in the div and the table in string and it is working.But when I try to pass it with the classes,it does not work.Can anyone help me? + +Thank you very much",2011/04/27,"['https://Stackoverflow.com/questions/5808172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727788/']","If the classes in `htmlFlightDetailsJavaScript` are in the form `div class=""bla""` you likely have to escape the quotes in the string or use single quotes, e.g. `div class='bla'`.","I guess you can accomplish much faster if you use an ajax call and a partial control (user control) or write the content yourself. + +1) The user control will render your html data. +2) The page code behind will receive the ajax call and call the method thal will render the partial control or write. +3) The method will write on Response.Output stream and end the Response (Response.End()) +4) The javascript will handle the response and show the result. + +(using jQuery) + +``` +// main.js + +jQuery.ajax({ + type: 'POST', + data: { isajax: true, ajaxcall: 'MyMethod' }, + dataType: 'html', + success: function (data, textStatus, jqXHR) { + alert(data); + } +}); + +// CodeBehind +protected void Page_Load(object sender, EventArgs e) +{ + if (Request.HttpMethod == ""POST"" && Request[""isajax""] == ""true"") + { + this.AjaxCall(Request); + } +} + +private void AjaxCall(HttpRequest request) +{ + switch (request[""ajaxcall""]) + { + case ""MyMethod"": this.MyMethod(request); break; + default: break; + } +} + +private void MyMethod(HttpRequest request) +{ + Response.ContentType = ""text/html""; + + Response.Write(""YOUR CONTENT GOES HERE.""); + // Or, render a User Control + + Response.End(); +} + +``` + +P.S.: You can use a Generic Handler if you wish to. Just add the url option to jQuery ajax method. + +Let me know if it helps." +18881883,"I need to take two parameters in my spring controller. + + + +I have controller which will return Json for this request. + +``` +@RequestMapping(value = ""/getDetails"", method = RequestMethod.GET,params = ""id,subId"", produces=""application/json"") + @ResponseBody + public MyBean getsubIds(@RequestParam String id, @RequestParam String subId) { + return MyBean + } + +``` + +I am getting 400 for when i tried to invoke the URL. Any thoughts on this? +I was able to get it with one parameter.",2013/09/18,"['https://Stackoverflow.com/questions/18881883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1322144/']","Try specifying which parameter in the query string should match the parameter in the method like so: + +``` +public MyBean getsubIds(@RequestParam(""id"") String id, @RequestParam(""subId"") String subId) { + +``` + +If the code is being compiled without the parameter names, Spring can have trouble figuring out which is which.","As for me it works (by calling: ): + +``` +@RequestMapping(value = ""/getDetails"", method = RequestMethod.GET, produces=""application/json"") +@ResponseBody +public MyBean getsubIds(@RequestParam(""id"") String id, @RequestParam(""subId"") String subId) { + return new MyBean(); +} + +``` + +P.S. Assuming you have class MyBean." +26682,"My band is working with a somewhat pricey mastering engineer and we are wanting to keep the price down. For a price we're comfortable with, he will either provide us with hi-res masters (24bit, 48khz - the recording quality), or with CD-quality masters + DDP file (16bit-44.1khz). + +My gut is to get the hi-res masters, buy [Triumph](http://www.audiofile-engineering.com/triumph/) for $79, and do the conversion and create the DDP file myself. However, the engineer said he does a separate mastering pass for each quality he does. + +My question is: what might necessitate a different mastering pass for the CD-quality version? What benefit might there be to getting the mastering engineer to do the CD-quality version instead of just converting it myself from the hi-res version?",2014/01/31,"['https://sound.stackexchange.com/questions/26682', 'https://sound.stackexchange.com', 'https://sound.stackexchange.com/users/7283/']","Dither, Noise Shaping, and Bit Quantization. These are the reasons for the separate mastering passes. All of which do not need to be considered when mixing/bouncing the audio in the native digital format it was converted to (24bit/48khz). + +Also, it sounds like he will provide you with individual ""HiRes"" native files OR Will downsample for you and create a DDP file. (Which is a FINAL Copy including play order and silence between songs that you can usually upload directly to a CD cuplication service.) + +If you are not making CDs or distributing digitally only (itunes?). You have no use for a ddp file. Although u may have use for the MEs tools and know how when it comes to downsampling. + +EDIT: I suppose it is possible for the ME to EQ specifically for the lower quality (not likely!) to produce better translation at the format? Also he may handle level peaks differently when downsampling. + +IF it were me, Id take the native hi res master and be about my business. Ive also been an audio engineer for years tho.","For going from 24 bit to 16 bit is relativity simple since it is evenly divisible, however you will still want to apply a dither to make up for the way the originally analog signal loses resolution. This allows simulating a wider set of distinct values than 16 bits would normally allow in exchange for some minimal noise. A great link about this was included by Takuya in the comments below. + +With 48khz sampling, you can accurately capture waveforms of up to 24khz frequency. There may be some weird harmonic issues that occur during the conversion, but they would be outside the human hearing range. + +It isn't truly a lossless experience since it isn't evenly divisible, but it shouldn't cause major issues either." +168731,"I'm just starting WoW for the first time... + +My question: Is the storyline and quests that I'm doing the same as what players did when the game started (in 2002 or whatever)? + +Or have events happened in the game that have progressed the entire timeline/story of the game for new players?",2014/05/20,"['https://gaming.stackexchange.com/questions/168731', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/76989/']","Each continent roughly corresponds to an expansion e.g. an arc in the timeline. + +* Outlands: Burning Crusade (2007). It is unmodified. +* Northrend: Wrath of the Lich King (2008). It is unmodified. +* Eastern Kingdoms and Kalimdor: Cataclysm (2010). This expansion completely replaces the quests and map from the classic version of the game. The classic story arc is no longer available on the main servers. Thrall is no longer warchief, Garrosh is. +* Pandaria: Mists of Pandaria (2012). It is unmodified except for the Vale of Eternal Blossoms, which was destroyed. You can't go back to the original Vale. Also, the legendary cape questline is removed from the game. +* Draenor: Warlords of Draenor (2014). The legendary ring questline is removed from the game. +* Broken Isles: Legion (2016). Weapon artifacts still have stats and can be leveled up, but they no longer have abilities. Legendary items, besides your weapon artifact, are disabled. +* Kul Tiras and Zandalar: Battle for Azeroth (2018). Azerite armor, the Heart of Azeroth, the legendary cloak all seem to still be in the game - expect none of these to be useful in shadowlands. Corrupted gear is no longer attainable and corruption effects are deactivated. + +You can play in all of the above content to get to level 50. You can start any or all of the expansions, switch expansions at any time, switch back. Whatever you want to do. + +For levels 50-60, you'll play in the new Shadowlands (2021) content. + +There is one more bit of content to mention: + +* Original Eastern Kingdoms and original Kalimdor: Classic (aka Vanilla) (2004). There is a separate installer/server for this content. You can create a separate character to play this content.",The whole world has changed into a cataclysmic world. It should be the same but with more quests and a higher level cap. +168731,"I'm just starting WoW for the first time... + +My question: Is the storyline and quests that I'm doing the same as what players did when the game started (in 2002 or whatever)? + +Or have events happened in the game that have progressed the entire timeline/story of the game for new players?",2014/05/20,"['https://gaming.stackexchange.com/questions/168731', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/76989/']","With each expansion, in the World of Warcraft universe, the level cap of your character increases by 5-10 levels. There is a general ""theme"", and throughout the release and consequent patches, there are some significant events that take place in terms of storyline. + +Each expansion is catered predominantly for players within its respective level group. Burning Crusade content caters to levels 60-70, Wrath of the Lich King caters to 70-80 and so on. + +Each consequent expansion can, in theory, both limit and improve your ability to experience the story line of its predecessors. + +Most end-game content is designed for groups of players, in anything from 5 to 40 man dungeons. There is a reliance on being able to play alongside other players, in order to have a chance against completing some of these events. + +With most players leaning towards current content, there can be fewer players available to participate in older content, however, due to the level increases with each expansion, you can often find older content a lot easier to handle given fewer players. + +As for if you miss out on any content, no, not really. While there is a lot of content, to begin with, you still have access to *most* of the major events surrounding the World of Warcraft universe. For example, you can still easily handle the major end-game raid released for vanilla World of Warcraft, [Ahn'Qiraj](http://wowwiki.wikia.com/Ahn%27Qiraj), with only a handful of level 70s. However, [the event that precipitated its opening](http://wowwiki.wikia.com/Gates_of_Ahn%27Qiraj) [no longer features](http://wowwiki.wikia.com/Gates_of_Ahn%27Qiraj#Permanent_.22Closure.22_of_the_Event), and can not be experienced. + +You will still be able to experience the majority of each expansions story. The only difference is, you can experience it in a different order, given the ability to freely roam within your characters level restrictions. + +Eastern Kingdoms and Kalimdor, the two major regions from Vanilla WoW, have undergone a massive redesign with the release of Cataclysm. You will likely experience a difference, here, in comparison to the original WoW. Most of this has been Blizzards way of bringing the vanilla content up to the standards reached with Burning Crusade and Wrath of the Lich King, and you will still experience all the ""original lore"" storyline in your initial character progression. + +For reference, here is a list of expansions, along with their general themes and included ""racial backstory"". You can generally focus on the content from a particular expansion, to experience the story surrounding its theme. + +* **The Burning Crusade (60-70)**: Explores Outland, the old homeland of the Orcs and Draenei, featured in the events of Warcraft 3: The Frozen Throne. Plot involves the storming of The Black Temple, and the overthrow of Illidan, the threat of the Zul'jin and his Zul'Aman empire, and the betrayal of Keal'thas Sunstrider, in attempting to summon the demon lord Kil'jaeden through the Blood Elves Sunwell. The Draenei and the Blood Elves are also introduced. +* **Wrath of the Lich King (70-80)**: Explores Northrend, a forgotten contintent to the north, featured in the events of Warcraft 3. Plot involves the discovery of an old titan complex, an old prison built to hold an Old God, and the war efforts in fighting the undead scourge, leading up to the penultimate battle against The Lich King, himself. This expansion also introduces the Death Knight, a special hero class with their own backstory, and play style. +* **Cataclysm (80-85)**: Introduces a massive apocalyptic event known as The Cataclysm, during which a great majority of The Eastern Kingdoms and Kalimdor undergoes a considerable change, including the appearance of the Maelstrom region. Plot involves the alliance and uprising of the Zandalari trolls, the defence against the firelord, Ragnaros, and the fight against the rouge dragon, Deathwing the Destroyer. This Goblins and Worgen are also introduced as more prominent races. +* **Mists of Pandaria (85-90)**: Introduces the newly discovered islands of Pandaria. Plot focuses on the renewed fight between the Horde and the Alliance, as well as the civil disputes within the factions. Further plot focuses on the return of the Mogu, the and siege of Orgrimmar. The Pandaran race is also introduced as the games first natural race. +* **Warlords of Draenor (90-100)**: Introduces an alternate timeline, as well as the planet Draenor, which eventually became Outland after being torn apart. Plot focuses on an altered timeline, where the orcs do not drink the blood of the demon lord Mannoroth. This leads to an unnatural uprising of the Iron Horde, and a major invasion of Azeroth.",The whole world has changed into a cataclysmic world. It should be the same but with more quests and a higher level cap. +168731,"I'm just starting WoW for the first time... + +My question: Is the storyline and quests that I'm doing the same as what players did when the game started (in 2002 or whatever)? + +Or have events happened in the game that have progressed the entire timeline/story of the game for new players?",2014/05/20,"['https://gaming.stackexchange.com/questions/168731', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/76989/']","Each continent roughly corresponds to an expansion e.g. an arc in the timeline. + +* Outlands: Burning Crusade (2007). It is unmodified. +* Northrend: Wrath of the Lich King (2008). It is unmodified. +* Eastern Kingdoms and Kalimdor: Cataclysm (2010). This expansion completely replaces the quests and map from the classic version of the game. The classic story arc is no longer available on the main servers. Thrall is no longer warchief, Garrosh is. +* Pandaria: Mists of Pandaria (2012). It is unmodified except for the Vale of Eternal Blossoms, which was destroyed. You can't go back to the original Vale. Also, the legendary cape questline is removed from the game. +* Draenor: Warlords of Draenor (2014). The legendary ring questline is removed from the game. +* Broken Isles: Legion (2016). Weapon artifacts still have stats and can be leveled up, but they no longer have abilities. Legendary items, besides your weapon artifact, are disabled. +* Kul Tiras and Zandalar: Battle for Azeroth (2018). Azerite armor, the Heart of Azeroth, the legendary cloak all seem to still be in the game - expect none of these to be useful in shadowlands. Corrupted gear is no longer attainable and corruption effects are deactivated. + +You can play in all of the above content to get to level 50. You can start any or all of the expansions, switch expansions at any time, switch back. Whatever you want to do. + +For levels 50-60, you'll play in the new Shadowlands (2021) content. + +There is one more bit of content to mention: + +* Original Eastern Kingdoms and original Kalimdor: Classic (aka Vanilla) (2004). There is a separate installer/server for this content. You can create a separate character to play this content.","With each expansion, in the World of Warcraft universe, the level cap of your character increases by 5-10 levels. There is a general ""theme"", and throughout the release and consequent patches, there are some significant events that take place in terms of storyline. + +Each expansion is catered predominantly for players within its respective level group. Burning Crusade content caters to levels 60-70, Wrath of the Lich King caters to 70-80 and so on. + +Each consequent expansion can, in theory, both limit and improve your ability to experience the story line of its predecessors. + +Most end-game content is designed for groups of players, in anything from 5 to 40 man dungeons. There is a reliance on being able to play alongside other players, in order to have a chance against completing some of these events. + +With most players leaning towards current content, there can be fewer players available to participate in older content, however, due to the level increases with each expansion, you can often find older content a lot easier to handle given fewer players. + +As for if you miss out on any content, no, not really. While there is a lot of content, to begin with, you still have access to *most* of the major events surrounding the World of Warcraft universe. For example, you can still easily handle the major end-game raid released for vanilla World of Warcraft, [Ahn'Qiraj](http://wowwiki.wikia.com/Ahn%27Qiraj), with only a handful of level 70s. However, [the event that precipitated its opening](http://wowwiki.wikia.com/Gates_of_Ahn%27Qiraj) [no longer features](http://wowwiki.wikia.com/Gates_of_Ahn%27Qiraj#Permanent_.22Closure.22_of_the_Event), and can not be experienced. + +You will still be able to experience the majority of each expansions story. The only difference is, you can experience it in a different order, given the ability to freely roam within your characters level restrictions. + +Eastern Kingdoms and Kalimdor, the two major regions from Vanilla WoW, have undergone a massive redesign with the release of Cataclysm. You will likely experience a difference, here, in comparison to the original WoW. Most of this has been Blizzards way of bringing the vanilla content up to the standards reached with Burning Crusade and Wrath of the Lich King, and you will still experience all the ""original lore"" storyline in your initial character progression. + +For reference, here is a list of expansions, along with their general themes and included ""racial backstory"". You can generally focus on the content from a particular expansion, to experience the story surrounding its theme. + +* **The Burning Crusade (60-70)**: Explores Outland, the old homeland of the Orcs and Draenei, featured in the events of Warcraft 3: The Frozen Throne. Plot involves the storming of The Black Temple, and the overthrow of Illidan, the threat of the Zul'jin and his Zul'Aman empire, and the betrayal of Keal'thas Sunstrider, in attempting to summon the demon lord Kil'jaeden through the Blood Elves Sunwell. The Draenei and the Blood Elves are also introduced. +* **Wrath of the Lich King (70-80)**: Explores Northrend, a forgotten contintent to the north, featured in the events of Warcraft 3. Plot involves the discovery of an old titan complex, an old prison built to hold an Old God, and the war efforts in fighting the undead scourge, leading up to the penultimate battle against The Lich King, himself. This expansion also introduces the Death Knight, a special hero class with their own backstory, and play style. +* **Cataclysm (80-85)**: Introduces a massive apocalyptic event known as The Cataclysm, during which a great majority of The Eastern Kingdoms and Kalimdor undergoes a considerable change, including the appearance of the Maelstrom region. Plot involves the alliance and uprising of the Zandalari trolls, the defence against the firelord, Ragnaros, and the fight against the rouge dragon, Deathwing the Destroyer. This Goblins and Worgen are also introduced as more prominent races. +* **Mists of Pandaria (85-90)**: Introduces the newly discovered islands of Pandaria. Plot focuses on the renewed fight between the Horde and the Alliance, as well as the civil disputes within the factions. Further plot focuses on the return of the Mogu, the and siege of Orgrimmar. The Pandaran race is also introduced as the games first natural race. +* **Warlords of Draenor (90-100)**: Introduces an alternate timeline, as well as the planet Draenor, which eventually became Outland after being torn apart. Plot focuses on an altered timeline, where the orcs do not drink the blood of the demon lord Mannoroth. This leads to an unnatural uprising of the Iron Horde, and a major invasion of Azeroth." +4371698,"A money pouch contains a certain number of cents and only one dime. You and your friend are playing a game: They alternate turns and pick one coin at a time, which they put in their pockets. Whoever picks the dime wins. You are trying to decide whether it is better to play first or second: Initially you think that if you pick the dime in your first draw, you immediately win, while if you opt to play second, your probability to pick the dime increases. Which of the two options is more favorable for you? We assume that you can’t see the coins before taking them out of the pouch and also that you can’t tell from the size which coin is which. + +My thought: Let's say we have $n$ coins in total. If I play first, I have probability of picking the dime: $\frac {1}{n}+\frac {1}{n-2}+\frac {1}{n-4}...$ while if I play second, I have $\frac {1}{n-1}+\frac {1}{n-3}+\frac {1}{n-5}...$. Clearly the second option gives a larger number. +Is this correct? + +Thank you.",2022/02/01,"['https://math.stackexchange.com/questions/4371698', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/594462/']","The first essential point is that *the dime has no preference for position*, thus its Pr of being at *any* position is $\frac{1}{n}$ + +The second essential point is that we don't know whether $n$ is odd or even, and if it is odd, we get one extra try if we go first + +Thus it is always preferable to go first","Suppose we extend the game as follows. We start off the same where we draw coins one at a time, but we number the draws and mark down which coin was drawn on which numbered draw. Once we reach the dime, we record the winner as usual, but we also continue drawing the remaining coins and marking the draw number of each. + +In the end, we wind up with $n$ coins drawn, and the draw number for the dime is equiprobable among all $n$ draws. We mark the first player a winner if the dime was drawn in an odd-numbered draw, and we mark the second player the winner if the dime was drawn in an even numbered draw. + +We know that this will yield the same results. + +Next, all of the coins that were drawn on odd-numbered draws are distributed to the first player and all the coins that were drawn on even numbered draws are distributed to the second player. If the dime appears in the player's pile, we mark them as a winner again. + +Again, we know that this will yield the same results. + +Finally, we start over and mix up all the coins randomly and assign them into two piles. If $n$ is even, the two piles each have $\frac{n}{2}$ coins. If $n$ is odd, one pile has $\frac{n+1}{2}$ coins and the other has $\frac{n-1}{2}$ coins. We give one pile to one player and the other pile to the other. If the pile they are given contains a dime, we mark down the win. + +But, we continue and allow them to take turns drawing coins from their own pile. If one pile more coins than the other, the first draw must be from the bigger pile. We mark whichever player draws the dime as the winner. + +Again this yield the same results as the original game. We have just demonstrated different games, each with an injective set of outcomes. This demonstrates there exists a bijection between the sets of outcomes. Any probabilities of winning calculated for any of these three games applies to all three. + +The easiest is of course the last game where you just split up the piles evenly and whoever has the dime wins. + +I realize this was a lot of words, and it wasn't necessary to go through all of these steps. I explained it this way in hopes that it shows why it works. + +If $n$ is even, the first player wins half the time and second player wins half the time. If $n$ is odd, the first player wins $\dfrac{n+1}{2n}$ while the second player wins $\dfrac{n-1}{2n}$ of the time. + +Not knowing if $n$ is odd or even, there is a slight advantage in choosing to go first all the time, just in case $n$ is odd." +2331476,How do you list your commits along with their SHA1 values in git?,2010/02/25,"['https://Stackoverflow.com/questions/2331476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111674/']","Exactly what format do you want? For just the one line summary and the SHA1: + +``` +git log --pretty=oneline + +``` + +See git log --help for more formating options.","I'm not sure what you mean. Listing a commit *is* listing its hash, and the easiest way to do it is with git rev-list. + +``` + +$ git rev-list HEAD + +``` + +will give the the reverse chronological list of all commits reachable from the current HEAD." +2331476,How do you list your commits along with their SHA1 values in git?,2010/02/25,"['https://Stackoverflow.com/questions/2331476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111674/']","Exactly what format do you want? For just the one line summary and the SHA1: + +``` +git log --pretty=oneline + +``` + +See git log --help for more formating options.","While P00ya's answer is correct, newer versions of git allow a simpler syntax: + +``` +git log --oneline + +``` + +which is shorthand for `git log --pretty=oneline --abbrev-commit` used together." +11641563,"I don't mean to be vague, but I'm skeptical of the idea of releasing code that is intentionally turned off, and I've not been able to find any good sources relating to the subject. This may truly be a ""it depends"" question, in which case please feel free to down vote and remove. + +My specific context is a web app that we host ourselves, with bi-weekly ""releases"" (push to production). Also, we currently use Subversion, though there's a push to move to Git in the near future. + +One scenario I've heard is deploying a feature that is dependent upon a library with a known feature that hasn't been released yet, whether your own library, or a 3rd party's. + +Another is releasing portions of a feature as they are finished, but disabled until all the pieces are together in production. + +While both of these at first sounded good, I'm questioning the value of code living in production that is disabled, especially as a general practice. It seems like this could lead to unfinished features cluttering the code base, as well as leading to larger configuration files than are needed, just to provide means for disabling/enabling features. + +What, if any, are the benefits of deploying intentionally disabled code, and what concerns need to be addressed before we do this with any sort of frequency? + +Also, please share any links, and tell me if this practice has a name.",2012/07/25,"['https://Stackoverflow.com/questions/11641563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/95546/']","It is called [feature toggles](http://martinfowler.com/bliki/FeatureToggle.html) + +I'd argue that it is no more risky that enabling/disabling features using role-based-authorizations. Your concerns regarding code clutter and increased configurations are valid but advocates of continuous delivery would argue that the alternatives (feature branches) are worse.","The primary basis for doing this I've seen is to separate code pushes from configuration pushes. It's easier to determine whether you have a bad release or bad configuration if you can separate them. You can push a release with incomplete feature X off by default, continue to push releases that can be rolled back without enabling it, then when you decide to turn it on, you can update your config which can also be rolled back if needed." +126705,"I'm following a course where the trainer recommends to identify all the vulnerabilities affecting a web application before trying to exploit them. + +While I understand the need to identify all the vulnerabilities, I don't understand why **I should wait before trying to exploit a vulnerability I just found (like a sql injection, a command injection, remote file inclusion, ...) and come back to it later?** + +**Is there any reason to proceed like that?**",2016/06/11,"['https://security.stackexchange.com/questions/126705', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/70136/']","That sounds more like a course in how to hack someone else's site than to test yours. + +Following the suggested logic allows the perpetrator to better plan a quick attack that will let them gain control of the machine before anyone has time to notice the attempts. + +That provides no benefit for someone who is only testing their own system's security.","If you keep looking you may find an easier to exploit vulnerability or one that gives you more privilege. Of course, if you first find an easy to exploit remote code execution vulnerability there's really no need to look for more." +126705,"I'm following a course where the trainer recommends to identify all the vulnerabilities affecting a web application before trying to exploit them. + +While I understand the need to identify all the vulnerabilities, I don't understand why **I should wait before trying to exploit a vulnerability I just found (like a sql injection, a command injection, remote file inclusion, ...) and come back to it later?** + +**Is there any reason to proceed like that?**",2016/06/11,"['https://security.stackexchange.com/questions/126705', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/70136/']","There's a chance that the result of exploiting a vulnerability early in the test could change the application. Either crashing it or just breaking certain functionality. Thus making the need to scan for additional vulnerabilities moot. + +Another reason for thoroughly identifying vulnerabilities is to give the person performing the test a full understanding of the application. Perhaps that first vulnerability could be exploited even further with information gained in the later stages of the vulnerability assessment.","That sounds more like a course in how to hack someone else's site than to test yours. + +Following the suggested logic allows the perpetrator to better plan a quick attack that will let them gain control of the machine before anyone has time to notice the attempts. + +That provides no benefit for someone who is only testing their own system's security." +126705,"I'm following a course where the trainer recommends to identify all the vulnerabilities affecting a web application before trying to exploit them. + +While I understand the need to identify all the vulnerabilities, I don't understand why **I should wait before trying to exploit a vulnerability I just found (like a sql injection, a command injection, remote file inclusion, ...) and come back to it later?** + +**Is there any reason to proceed like that?**",2016/06/11,"['https://security.stackexchange.com/questions/126705', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/70136/']","There's a chance that the result of exploiting a vulnerability early in the test could change the application. Either crashing it or just breaking certain functionality. Thus making the need to scan for additional vulnerabilities moot. + +Another reason for thoroughly identifying vulnerabilities is to give the person performing the test a full understanding of the application. Perhaps that first vulnerability could be exploited even further with information gained in the later stages of the vulnerability assessment.","If you keep looking you may find an easier to exploit vulnerability or one that gives you more privilege. Of course, if you first find an easy to exploit remote code execution vulnerability there's really no need to look for more." +60384568,"This is a question about Template Toolkit for perl. + +I render my templates with a little command-line utility that has the following option enabled + +``` + DEBUG => Template::Constants::DEBUG_UNDEF, + +``` + +The syntax is `render var1 val1 var2 val2 ....` +This is very convenient because the user gets prompts about values that need to be defined, for example + +``` +$ render file.tt +undef error - var1 is undefined + +$ render file.tt var1 foo +undef error - var2 is undefined + +$ render file.tt var1 foo var2 bar +... template renders correctly + +``` + +For some (optional) values, templates provide defaults, for example: + +``` +[%- DEFAULT + hostname = 0 +%] + +``` + +Then the template body would typically contain: + +``` + [% IF hostname %] hostname = [% hostname %][% ELSE %][% -- a comment, variable hostname not provided %][% END %] + +``` + +How do I make the above idiom work for variables where `0` is a valid value? + +I want the following to happen: + +``` +render template.tt + +``` + +Template renders: + +``` + -- this is a comment, variable enable_networking not provided + +``` + +For + +``` + render template.tt enable_networking 0 + +``` + +I want + +``` + enable_networking = 0 + +``` + +The problem is differentiating between defined values and false values. I have tried using `-1` (instead of `0`) both in the `DEFAULT` block and in the `[% IF enable_networking == -1 %]` statement. + +However, the following `DEFAULT` block + +``` +[% DEFAULT enable_networking = -1 %] + +``` + +will override value `0` specified on the command-line. (It sees a `enable_networking` is false and sets it to -1) + +Are there any easy work-arounds (some config variable maybe?)",2020/02/24,"['https://Stackoverflow.com/questions/60384568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12312873/']","To check if a variable is undefined or not you could check if its `size` method returns something greater than 0. Of course this case only aplies if the variable is not initialized or defined at all (`enable_networking = ''` has size = 1, the same with `enable_networking = 0`) + +To check if a variable is not false... well... first you have to describe wich type of value is false. + +In this case i will take size = 0 (or size doesn't exists) as undefined, -1 as false and everything else as true: + +``` +[% IF enable_networking.size and enable_networking != -1 %] + enable_networking = [% enable_networking %] +[% ELSE %] + -- a comment, variable enable_networking not provided +[% END %] + +``` + +With the code above if you run + +``` +render template.tt enable_networking 0 + +``` + +The output will be `enable_networking = 0` + +And if you run + +``` +render template.tt + +``` + +The output will be `-- a comment, variable enable_networking not provided` even if you don't declare `[% DEFAULT enable_networking = -1 %]` + +**EDIT 1:** + +The `length` method is better suited for this job: + +``` +[% IF enable_networking.length and enable_networking != -1 %] + enable_networking = [% enable_networking %] +[% ELSE %] + -- a comment, variable enable_networking not provided +[% END %] + +``` + +Using `length` instead of `size` also allows you to use `enable_networking = ''` as FALSE along with -1 + +**EDIT 2:** + +Ok, after the comments i found a workaround that do the trick: the `TRY` - `CATCH` directives... + +For optional variables that can have value of 0 the objective would be to `TRY` setting the variable value to itself, if the variable is defined the value will be assigned, otherwise we `CATCH` the undef error and set the default value. For any other type of variable we can use the `DEFAULT` directive: + +``` +[% DEFAULT + hostname = 0 +%] +[% TRY %] [% enable_networking = enable_networking %] [% CATCH %] [% enable_networking = -1; %] [% END %] + +hostname = [% hostname %] +[% IF enable_networking != -1 AND enable_networking.length %] enable_networking = [% enable_networking %][% ELSE %]-- variable enable_networking not provided[% END %] + +``` + +With this new template if you run + +``` +$ render template.tt +hostname = 0 +-- variable enable_networking not provided + +$ render template.tt enable_networking """" +hostname = 0 +-- variable enable_networking not provided + +$ render template.tt hostname myhost enable_networking 0 +hostname = myhost +enable_networking = 0 + +```","All scalar values in TT have a `.defined` vmethod. + +``` +[% IF hostname.defined %] hostname = [% hostname %][% ELSE %][% -- a comment, variable hostname not provided %][% END %] + +``` + +This is discussed in [the manual](https://metacpan.org/pod/distribution/Template-Toolkit/lib/Template/Manual/VMethods.pod#defined)." +267534,"I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. + +Is there a single-line native method in php that would allow me to do the following. +Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. + +``` +$rand_place = explode("","",loadFile(""csvOf20000places.txt"")){rand(0,1000)}; + +``` + +This is a syntax error, however ideally it would be great if this worked! + +Currently, it seems unavoidable that one must create a temporary array, ie + +**The following is what I want to avoid:** + +``` +$temporary_places_array = explode("","",loadFile(""csvOf20000places.txt"")); +$rand_place = $temporary_places_array[rand(0,1000)]; + +``` + +Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. + +**NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**",2008/11/06,"['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']","There is no native PHP method of doing this. + +You could make a function like this: + +``` +function array_value($array, $key) { + return $array[$key]; +} + +``` + +And then use it like this: + +``` +$places = ""alabama,alaska,arizona .... zimbabway""; +$random_place = array_value(explode("","", $places), rand(0, 1000)); + +```","If it's memory concerns, there are other ways of going about this that don't split out into an array. But no, there is nothing builtin to handle this sort of situation. + +As an alternative, you might try: + +``` +$pos = 0; +$num = 0; +while(($pos = strpos($places, ',', $pos+1)) !== false) {$num++;} +$which = rand(0, $num); +$num = 0; +while($num <= $which) {$pos = strpos($places, ',', $pos+1);} +$random_place = substr($places, $pos, strpos($places, ',', $pos+1)); + +``` + +I havn't tested this, so there may be a few off-by-one issues in it, but you get the idea. This could be made shorter (and quicker) by cacheing the positions that you work out in the first loop, but this brings you back to the memory issues." +267534,"I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. + +Is there a single-line native method in php that would allow me to do the following. +Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. + +``` +$rand_place = explode("","",loadFile(""csvOf20000places.txt"")){rand(0,1000)}; + +``` + +This is a syntax error, however ideally it would be great if this worked! + +Currently, it seems unavoidable that one must create a temporary array, ie + +**The following is what I want to avoid:** + +``` +$temporary_places_array = explode("","",loadFile(""csvOf20000places.txt"")); +$rand_place = $temporary_places_array[rand(0,1000)]; + +``` + +Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. + +**NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**",2008/11/06,"['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']","There is no native PHP method of doing this. + +You could make a function like this: + +``` +function array_value($array, $key) { + return $array[$key]; +} + +``` + +And then use it like this: + +``` +$places = ""alabama,alaska,arizona .... zimbabway""; +$random_place = array_value(explode("","", $places), rand(0, 1000)); + +```","I spent a great deal of last year researching advanced CSV parsing for PHP and I admit it would be nice to randomly seek at will on a file. One of my semi-deadend's was to scan through a known file and make an index of the position of all known \n's that were not at the beginning of the line. + +``` + //Grab and load our index +$index = unserialize(file_get_contents('somefile.ext.ind')); +//What it looks like +$index = array( 0 => 83, 1 => 162, 2 => 178, ....); + +$fHandle = fopen(""somefile.ext"",'RB'); +$randPos = rand(0, count($index)); +fseek($fHandle, $index[$randPos]); +$line = explode("","", fgets($fHandle)); + +``` + +Tha's the only way I could see it being done anywhere close to what you need. As for creating the index, that's rudimentary stuff. + +``` +$fHandle = fopen('somefile.ext','rb'); +$index = array(); +for($i = 0; false !== ($char = fgetc($fHandle)); $i++){ + if($char === ""\n"") $index[] = $i; +} + +```" +267534,"I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. + +Is there a single-line native method in php that would allow me to do the following. +Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. + +``` +$rand_place = explode("","",loadFile(""csvOf20000places.txt"")){rand(0,1000)}; + +``` + +This is a syntax error, however ideally it would be great if this worked! + +Currently, it seems unavoidable that one must create a temporary array, ie + +**The following is what I want to avoid:** + +``` +$temporary_places_array = explode("","",loadFile(""csvOf20000places.txt"")); +$rand_place = $temporary_places_array[rand(0,1000)]; + +``` + +Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. + +**NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**",2008/11/06,"['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']","**No, there is no way to do that natively.** + +You can, however: + +1.- Store the unavoidable array instead of the string. Given PHP's limitation this is what makes most sense in my opinion. + +Also, don't forget you can [unset()](http://php.net/unset) + +2.- Use strpos() and friends to parse the string into what you need, as shown in other answers I won't paste here. + +3.- Create a function.","If it's memory concerns, there are other ways of going about this that don't split out into an array. But no, there is nothing builtin to handle this sort of situation. + +As an alternative, you might try: + +``` +$pos = 0; +$num = 0; +while(($pos = strpos($places, ',', $pos+1)) !== false) {$num++;} +$which = rand(0, $num); +$num = 0; +while($num <= $which) {$pos = strpos($places, ',', $pos+1);} +$random_place = substr($places, $pos, strpos($places, ',', $pos+1)); + +``` + +I havn't tested this, so there may be a few off-by-one issues in it, but you get the idea. This could be made shorter (and quicker) by cacheing the positions that you work out in the first loop, but this brings you back to the memory issues." +267534,"I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. + +Is there a single-line native method in php that would allow me to do the following. +Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. + +``` +$rand_place = explode("","",loadFile(""csvOf20000places.txt"")){rand(0,1000)}; + +``` + +This is a syntax error, however ideally it would be great if this worked! + +Currently, it seems unavoidable that one must create a temporary array, ie + +**The following is what I want to avoid:** + +``` +$temporary_places_array = explode("","",loadFile(""csvOf20000places.txt"")); +$rand_place = $temporary_places_array[rand(0,1000)]; + +``` + +Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. + +**NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**",2008/11/06,"['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']","**No, there is no way to do that natively.** + +You can, however: + +1.- Store the unavoidable array instead of the string. Given PHP's limitation this is what makes most sense in my opinion. + +Also, don't forget you can [unset()](http://php.net/unset) + +2.- Use strpos() and friends to parse the string into what you need, as shown in other answers I won't paste here. + +3.- Create a function.","``` +list($rand_place) = array_slice(explode(',', loadFile(""csvOf20000places.txt"")), array_rand(explode(',', loadFile(""csvOf20000places.txt""))), 1); + +``` + +**EDIT:** Ok, you're right. The question is *very* hard to understand but, I think this is it. The code above will pull random items from the csv file but, to just pull whatever you want out, use this: + +``` +list($rand_place) = array_slice(explode(',', loadFile(""csvOf20000places.txt"")), {YOUR_NUMBER}, 1); + +``` + +Replace the holder with the numeric key of the value you want to pull out." +267534,"I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. + +Is there a single-line native method in php that would allow me to do the following. +Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. + +``` +$rand_place = explode("","",loadFile(""csvOf20000places.txt"")){rand(0,1000)}; + +``` + +This is a syntax error, however ideally it would be great if this worked! + +Currently, it seems unavoidable that one must create a temporary array, ie + +**The following is what I want to avoid:** + +``` +$temporary_places_array = explode("","",loadFile(""csvOf20000places.txt"")); +$rand_place = $temporary_places_array[rand(0,1000)]; + +``` + +Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. + +**NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**",2008/11/06,"['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']","I know it's poor form to answer a question with a question, but why are you concerned about this? Is it a nitpick, or an optimization question? The Zend engine will optimize this away. + +However, I'd point out you don't have to create a temporary variable *necessarily*: + +``` +$rand_place = explode("","",loadFile(""csvOf20000places.txt"")); +$rand_place = $rand_place[rand(0,1000)]; + +``` + +Because of type mutability, you could reuse the variable. Of course, you're still not skipping a step.","You can do this: + +``` +offsetGet(1); // ""one"" +?> + +``` + +Sadly you **can't** do this: + +``` +echo (new ArrayObject(explode("","", ""zero,one,two"")))->offsetGet(2); + +```" +267534,"I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. + +Is there a single-line native method in php that would allow me to do the following. +Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. + +``` +$rand_place = explode("","",loadFile(""csvOf20000places.txt"")){rand(0,1000)}; + +``` + +This is a syntax error, however ideally it would be great if this worked! + +Currently, it seems unavoidable that one must create a temporary array, ie + +**The following is what I want to avoid:** + +``` +$temporary_places_array = explode("","",loadFile(""csvOf20000places.txt"")); +$rand_place = $temporary_places_array[rand(0,1000)]; + +``` + +Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. + +**NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**",2008/11/06,"['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']","**No, there is no way to do that natively.** + +You can, however: + +1.- Store the unavoidable array instead of the string. Given PHP's limitation this is what makes most sense in my opinion. + +Also, don't forget you can [unset()](http://php.net/unset) + +2.- Use strpos() and friends to parse the string into what you need, as shown in other answers I won't paste here. + +3.- Create a function.","I spent a great deal of last year researching advanced CSV parsing for PHP and I admit it would be nice to randomly seek at will on a file. One of my semi-deadend's was to scan through a known file and make an index of the position of all known \n's that were not at the beginning of the line. + +``` + //Grab and load our index +$index = unserialize(file_get_contents('somefile.ext.ind')); +//What it looks like +$index = array( 0 => 83, 1 => 162, 2 => 178, ....); + +$fHandle = fopen(""somefile.ext"",'RB'); +$randPos = rand(0, count($index)); +fseek($fHandle, $index[$randPos]); +$line = explode("","", fgets($fHandle)); + +``` + +Tha's the only way I could see it being done anywhere close to what you need. As for creating the index, that's rudimentary stuff. + +``` +$fHandle = fopen('somefile.ext','rb'); +$index = array(); +for($i = 0; false !== ($char = fgetc($fHandle)); $i++){ + if($char === ""\n"") $index[] = $i; +} + +```" +267534,"I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. + +Is there a single-line native method in php that would allow me to do the following. +Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. + +``` +$rand_place = explode("","",loadFile(""csvOf20000places.txt"")){rand(0,1000)}; + +``` + +This is a syntax error, however ideally it would be great if this worked! + +Currently, it seems unavoidable that one must create a temporary array, ie + +**The following is what I want to avoid:** + +``` +$temporary_places_array = explode("","",loadFile(""csvOf20000places.txt"")); +$rand_place = $temporary_places_array[rand(0,1000)]; + +``` + +Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. + +**NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**",2008/11/06,"['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']","``` +list($rand_place) = array_slice(explode(',', loadFile(""csvOf20000places.txt"")), array_rand(explode(',', loadFile(""csvOf20000places.txt""))), 1); + +``` + +**EDIT:** Ok, you're right. The question is *very* hard to understand but, I think this is it. The code above will pull random items from the csv file but, to just pull whatever you want out, use this: + +``` +list($rand_place) = array_slice(explode(',', loadFile(""csvOf20000places.txt"")), {YOUR_NUMBER}, 1); + +``` + +Replace the holder with the numeric key of the value you want to pull out.","I spent a great deal of last year researching advanced CSV parsing for PHP and I admit it would be nice to randomly seek at will on a file. One of my semi-deadend's was to scan through a known file and make an index of the position of all known \n's that were not at the beginning of the line. + +``` + //Grab and load our index +$index = unserialize(file_get_contents('somefile.ext.ind')); +//What it looks like +$index = array( 0 => 83, 1 => 162, 2 => 178, ....); + +$fHandle = fopen(""somefile.ext"",'RB'); +$randPos = rand(0, count($index)); +fseek($fHandle, $index[$randPos]); +$line = explode("","", fgets($fHandle)); + +``` + +Tha's the only way I could see it being done anywhere close to what you need. As for creating the index, that's rudimentary stuff. + +``` +$fHandle = fopen('somefile.ext','rb'); +$index = array(); +for($i = 0; false !== ($char = fgetc($fHandle)); $i++){ + if($char === ""\n"") $index[] = $i; +} + +```" +267534,"I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. + +Is there a single-line native method in php that would allow me to do the following. +Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. + +``` +$rand_place = explode("","",loadFile(""csvOf20000places.txt"")){rand(0,1000)}; + +``` + +This is a syntax error, however ideally it would be great if this worked! + +Currently, it seems unavoidable that one must create a temporary array, ie + +**The following is what I want to avoid:** + +``` +$temporary_places_array = explode("","",loadFile(""csvOf20000places.txt"")); +$rand_place = $temporary_places_array[rand(0,1000)]; + +``` + +Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. + +**NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**",2008/11/06,"['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']","``` +list($rand_place) = array_slice(explode(',', loadFile(""csvOf20000places.txt"")), array_rand(explode(',', loadFile(""csvOf20000places.txt""))), 1); + +``` + +**EDIT:** Ok, you're right. The question is *very* hard to understand but, I think this is it. The code above will pull random items from the csv file but, to just pull whatever you want out, use this: + +``` +list($rand_place) = array_slice(explode(',', loadFile(""csvOf20000places.txt"")), {YOUR_NUMBER}, 1); + +``` + +Replace the holder with the numeric key of the value you want to pull out.","You can do this: + +``` +offsetGet(1); // ""one"" +?> + +``` + +Sadly you **can't** do this: + +``` +echo (new ArrayObject(explode("","", ""zero,one,two"")))->offsetGet(2); + +```" +267534,"I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. + +Is there a single-line native method in php that would allow me to do the following. +Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. + +``` +$rand_place = explode("","",loadFile(""csvOf20000places.txt"")){rand(0,1000)}; + +``` + +This is a syntax error, however ideally it would be great if this worked! + +Currently, it seems unavoidable that one must create a temporary array, ie + +**The following is what I want to avoid:** + +``` +$temporary_places_array = explode("","",loadFile(""csvOf20000places.txt"")); +$rand_place = $temporary_places_array[rand(0,1000)]; + +``` + +Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. + +**NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**",2008/11/06,"['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']","I know it's poor form to answer a question with a question, but why are you concerned about this? Is it a nitpick, or an optimization question? The Zend engine will optimize this away. + +However, I'd point out you don't have to create a temporary variable *necessarily*: + +``` +$rand_place = explode("","",loadFile(""csvOf20000places.txt"")); +$rand_place = $rand_place[rand(0,1000)]; + +``` + +Because of type mutability, you could reuse the variable. Of course, you're still not skipping a step.","If it's memory concerns, there are other ways of going about this that don't split out into an array. But no, there is nothing builtin to handle this sort of situation. + +As an alternative, you might try: + +``` +$pos = 0; +$num = 0; +while(($pos = strpos($places, ',', $pos+1)) !== false) {$num++;} +$which = rand(0, $num); +$num = 0; +while($num <= $which) {$pos = strpos($places, ',', $pos+1);} +$random_place = substr($places, $pos, strpos($places, ',', $pos+1)); + +``` + +I havn't tested this, so there may be a few off-by-one issues in it, but you get the idea. This could be made shorter (and quicker) by cacheing the positions that you work out in the first loop, but this brings you back to the memory issues." +267534,"I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again. + +Is there a single-line native method in php that would allow me to do the following. +Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**. + +``` +$rand_place = explode("","",loadFile(""csvOf20000places.txt"")){rand(0,1000)}; + +``` + +This is a syntax error, however ideally it would be great if this worked! + +Currently, it seems unavoidable that one must create a temporary array, ie + +**The following is what I want to avoid:** + +``` +$temporary_places_array = explode("","",loadFile(""csvOf20000places.txt"")); +$rand_place = $temporary_places_array[rand(0,1000)]; + +``` + +Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable. + +**NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**",2008/11/06,"['https://Stackoverflow.com/questions/267534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34561/']","``` +list($rand_place) = array_slice(explode(',', loadFile(""csvOf20000places.txt"")), array_rand(explode(',', loadFile(""csvOf20000places.txt""))), 1); + +``` + +**EDIT:** Ok, you're right. The question is *very* hard to understand but, I think this is it. The code above will pull random items from the csv file but, to just pull whatever you want out, use this: + +``` +list($rand_place) = array_slice(explode(',', loadFile(""csvOf20000places.txt"")), {YOUR_NUMBER}, 1); + +``` + +Replace the holder with the numeric key of the value you want to pull out.","If it's memory concerns, there are other ways of going about this that don't split out into an array. But no, there is nothing builtin to handle this sort of situation. + +As an alternative, you might try: + +``` +$pos = 0; +$num = 0; +while(($pos = strpos($places, ',', $pos+1)) !== false) {$num++;} +$which = rand(0, $num); +$num = 0; +while($num <= $which) {$pos = strpos($places, ',', $pos+1);} +$random_place = substr($places, $pos, strpos($places, ',', $pos+1)); + +``` + +I havn't tested this, so there may be a few off-by-one issues in it, but you get the idea. This could be made shorter (and quicker) by cacheing the positions that you work out in the first loop, but this brings you back to the memory issues." +5054428,"javascript noob trying to figure something out. I saw a script located here: + +[Using jQuery to open all external links in a new window](https://stackoverflow.com/questions/1871371/using-jquery-to-open-all-external-links-in-a-new-window) + +in which urls on a page are checked to see if they match the current page url. If not, this particular script would open them in a new window. I would like to use the same test on urls but if they are external I would like ?iframe to be appended to each url, a la fancybox syntax. My noob script is: + +``` +$(document).ready(function() { + $('a[@href^=""http://""]').filter(function() { + return this.hostname && this.hostname !== location.hostname; + }).append('?iframe') +}); + +``` + +which I believe is incorrect. Any assistance? Thanks",2011/02/20,"['https://Stackoverflow.com/questions/5054428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/611318/']","You have to change the `href` attribute using [`attr`](http://api.jquery.com/attr/), not `append` new child elements: + +``` +$('a[href^=""http://""]').filter(function() { // no @ before the attribute name + return this.hostname && this.hostname !== location.hostname; +}).attr('href', function(i, value) { + // takes care of URLs with parameters + return value + (value.indexOf('?') > 0 ? '&' : '?') + 'iframe'; +}); + +``` + +Note that `hostname` is [only available in HTML5](https://developer.mozilla.org/en/DOM/HTMLAnchorElement). So in browsers not supporting HTML 5, the filter would discard every element (*Update: Given that the question you linked to is from 2009, it seems browsers implemented `hostname` but it was not part of any specification*). You can change it to: + +``` +var hostname = new RegExp(""^http://"" + location.hostname); + +$('a[href^=""http://""]').filter(function() { + return !hostname.test(this.href); +}).attr('href', function(i, value) { + return value + (value.indexOf('?') > 0 ? '&' : '?') + 'iframe'; +}); + +``` + +And if you also want to convert links to `https` websites, ditch the attribute selector and change the regular expression: + +``` +var hostname = new RegExp(""^https?://"" + location.hostname); + +$('a').filter(function() {... + +``` + +--- + +**Update:** + +Specifically for fancybox, according to the [documentation](http://fancybox.net/howto), it should work this way. However, you are right, you could just add the `iframe` class: + +``` + $('a').filter(function() {...}).addClass('iframe'); + +```","Instead of append, which modifies the inner HTML of the element, modify the href attribute: + +``` +$(document).ready(function() { + var elements = $('a[@href^=""http://""]').filter(function() { + return this.hostname && this.hostname !== location.hostname; + }); + + elements.each(function(index, value) { + $(this).attr('href', $(this).attr('href') + '?iframe'); + }); +}); + +```" +5054428,"javascript noob trying to figure something out. I saw a script located here: + +[Using jQuery to open all external links in a new window](https://stackoverflow.com/questions/1871371/using-jquery-to-open-all-external-links-in-a-new-window) + +in which urls on a page are checked to see if they match the current page url. If not, this particular script would open them in a new window. I would like to use the same test on urls but if they are external I would like ?iframe to be appended to each url, a la fancybox syntax. My noob script is: + +``` +$(document).ready(function() { + $('a[@href^=""http://""]').filter(function() { + return this.hostname && this.hostname !== location.hostname; + }).append('?iframe') +}); + +``` + +which I believe is incorrect. Any assistance? Thanks",2011/02/20,"['https://Stackoverflow.com/questions/5054428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/611318/']","You have to change the `href` attribute using [`attr`](http://api.jquery.com/attr/), not `append` new child elements: + +``` +$('a[href^=""http://""]').filter(function() { // no @ before the attribute name + return this.hostname && this.hostname !== location.hostname; +}).attr('href', function(i, value) { + // takes care of URLs with parameters + return value + (value.indexOf('?') > 0 ? '&' : '?') + 'iframe'; +}); + +``` + +Note that `hostname` is [only available in HTML5](https://developer.mozilla.org/en/DOM/HTMLAnchorElement). So in browsers not supporting HTML 5, the filter would discard every element (*Update: Given that the question you linked to is from 2009, it seems browsers implemented `hostname` but it was not part of any specification*). You can change it to: + +``` +var hostname = new RegExp(""^http://"" + location.hostname); + +$('a[href^=""http://""]').filter(function() { + return !hostname.test(this.href); +}).attr('href', function(i, value) { + return value + (value.indexOf('?') > 0 ? '&' : '?') + 'iframe'; +}); + +``` + +And if you also want to convert links to `https` websites, ditch the attribute selector and change the regular expression: + +``` +var hostname = new RegExp(""^https?://"" + location.hostname); + +$('a').filter(function() {... + +``` + +--- + +**Update:** + +Specifically for fancybox, according to the [documentation](http://fancybox.net/howto), it should work this way. However, you are right, you could just add the `iframe` class: + +``` + $('a').filter(function() {...}).addClass('iframe'); + +```","Your use of the `append` method is incorrect. The following code shows how to achieve what you require, plus it takes into account a couple of additional factors that you need to bear in mind, namely: + +1) What about links that use https rather than http? + +2) What about links that already contains querystring parameters? should be changed to rather than + +``` +$(function() { + $('a[href^=""http""]').filter(function() { + return this.hostname && this.hostname !== location.hostname; + }).each(function() { + this.href += ((this.href.indexOf('?') >= 0) ? '&' : '?') + 'iframe'; + }); +}); + +```" +3396783,"I'm playing with my favorite thing, xml (have the decency to kill me please) and the ultimate goal is save it in-house and use the data in a different manner (this is an export from another system). I've got goo that works, but meh, I think it can be a lot better. + +``` + public Position(XElement element) + { + Id = element.GetElementByName(""id""); + Title = element.GetElementByName(""title""); + } + +``` + +I'm thinking of making it more automated (hacky) by adding data annotations for the xml element it represents. Something like this for instance. + +``` + [XmlElement(""id"")] + public string Id { get; set; } + + [XmlElement(""title"")] + public string Title { get; set; } + +``` + +then writing some reflection/mapper code but both ways feels ... dirty. Should I care? Is there a better way? Maybe deserialize is the right approach? I just have a feeling there's a mo' bettah way to do this.",2010/08/03,"['https://Stackoverflow.com/questions/3396783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/202728/']","You can use the [`XmlSerializer`](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx) class and markup your class properties with [attributes](http://msdn.microsoft.com/en-us/library/83y7df3e(VS.71).aspx) to control the serialization and deserialization of the objects. + +Here's a simple method you can use to deserialize your `XDocument` into your object: + +``` +public static T DeserializeXml(XDocument document) +{ + using (var reader = document.CreateReader()) + { + var serializer = new XmlSerializer(typeof (T)); + return (T) serializer.Deserialize(reader); + } +} + +``` + +and a simple serializer method: + +``` +public static String ToXml(T instance) +{ + using (var output = new StringWriter(new StringBuilder())) + { + var serializer = new XmlSerializer(typeof(T)); + serializer.Serialize(output, instance); + + return output.ToString(); + } +} + +```","The mechanism that you are suggesting already exists in the form of the [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx) class and a set of custom attributes that you can use to control the serialisation process. + +In fact the .Net framework comes with a tool [xsd.exe](http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx) which will generate these class files for you from a schema definition (.xsd) file. + +Also, just to make things really easy, Visual Studio even has the ability to generate you an .xsd schema for an xml snippet (its hidden away in the Xml menu somewhere)." +176382,"Introduction: +------------- + +I'm trying to make a Sorcerer subclass that has a Lovecraftian/Far Realm theme. I tried to balance it around Shadow, Divine Soul, Storm and the Abberant/Psionic Mind UA. (I realize that is probably over-tuned some) I'm hoping this isn't overly powerful though probably on the higher end of the spectrum. I'll be play testing it in about a month give or take a week. + +Design +------ + +One of the things I wanted in this subclass was an extended spell list as I feel, having played a sorcerer in Pathfinder 1e and DnD 5e, that the limited spells known combined with everyone being a spontaneous caster shoehorn Sorcerers a bit too much into glass cannons with no real versatility. + +I also wanted a unique feel and theme without stepping on the other subclasses' toes. + +The Subclass +------------ + +Umbra Spawn +----------- + +Level 1: + +Improved Dark Vision: + +* Dark Vision - 120 Feet + +This is right from Shadow Sorcery + +* Expanded Spell List: + +These spells are granted as you gain the appropriate level in this subclass to cast them. +They are gained automatically and do not count towards spells known. You can see through magical darkness caused by any of these spells that you cast. + +``` +Spell Name Spell Level Class Level +Arms of Hadar level 1 level 1 +Darkness level 2 level 3 +Hunger of Hadar level 3 level 5 +Shadow of Moil level 4 level 7 +Synaptic Static level 5 level 9 + +``` + +I'm not too thrilled with Synaptic Static but couldn't find a better thematic spell from PHB or XtGE. I thought about giving Dimension Door at 9 but it made the wording clunky and I felt a linear progression made more sense. I also considered making these spells castable through Sorcery points a la Shadow Magic, though I left that out. + +Level 6: + +Far Touch: + +* You can cast spells with a range of touch up to a range of 30 feet. + +I'm unsure of how necessary this is, it might make level 6 too strong, though feels thematic. + +Umbra Tendril: + +* As a bonus action you can create a void tendril to push or pull +yourself or another creature you can see 10 feet. If the creature is unwilling, +it makes a strength save against your spell save DC. This ability has +a range of 30 feet. + +I discussed this feature with the DM of my upcoming game, he's going to rule that a creature willing to be moved will trigger Attacks of Opportunity. So the question becomes how powerful is the versatility of this ability. + +Level 14: + +Into the Void: + +* As a reaction to being targeted by a creature you can see, you may spend 2 sorcery points, you are under the effect of blur until the +start of your next turn. This does not require concentration. + +I originally had levels 6 and 14 switched, but I want the core of the class to be the tendril and not the blur. The downside being a lack of sorcery point dumps for 14 levels. + +Level 18: + +Umbra Incarnate: + +* As a bonus action you may spend 6 sorcery points to manifest the void +for 1 minute. While under this effect you gain the following: + + + You have a Flying Speed equal to your movement speed. + + You may use your void tendrils up to three times as a bonus action and when this ability + is activated. If the target fails their save they take 2D6 force damage. + + Magical Darkness is centered around you with a radius of 15 feet. Any number of creatures in + range you designate when this ability is activated can see through this darkness. + + You are immune to fear effects. + +Question +-------- + +**Is this balanced as a Sorcerer subclass and is the wording and intent of each feature clear and in line with officially published materials?** + +I had the flavor of the class in mind while designing this and really wanted the expanded spell list. I am completely unsure of how the tendrils, especially at level 18, are balanced as they work a bit differently from published materials I am aware of.",2020/10/12,"['https://rpg.stackexchange.com/questions/176382', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/59619/']","Most of this looks fine, so I'll mainly focus on the outliers. + +**And boy-oh-boy is the level 18 ability an outlier.** That said, I do want to preface this by saying that stepping outside the bounds of balance is the best part of homebrew. This criticism shouldn't distract from the fact that you've got a fun subclass on your hands; it just needs a bit of tweaking. + +Umbral Incarnate is *significantly* more powerful than any other Sorcerer option, and probably any other ability in 5e. +----------------------------------------------------------------------------------------------------------------------- + +I would be scared to put this ability on a BBEG, let alone a PC. As it stands, it will warp player choices across classes while simultaneously resulting in an unsatisfying gameplay pattern. Let's start from the top. + +* *Flying speed*: by itself, this is a perfectly sound choice. Flight is prevalent at higher levels and lends itself well to over-the-top, dynamic battles. No problems here. +* *3x tentacle use + 2d6 force damage per tentacle*: This provides far too much battlefield control and damage. This effectively allows the user to emulate a Repelling Blast/Grasp of Hadar Warlock's entire Eldritch Blast rotation on a *bonus action*. Martial classes salivate at the idea of this much battlefield influence. + + Thematically, necrotic damage would be a better fit for this ability. + + **Recommendation**: I can sense that this is intended to amplify the satisfaction of using the tentacles, which I think is a good goal, as it's the most unique thing this class has to offer. This should require a full action. As it stands, it provides far too much utility and versatility to be balanced. +* *Magical darkness penetrable by you and your allies*: very few creatures can see through magical darkness. To my knowledge, only devils and creatures with blindsight or truesight are capable of doing so. This means that the sorcerer and their party will be effectively under the effect of *Greater Invisibility* against *almost every creature in 5e*. All their attacks will have advantage, all attacks against them will be made at disadvantage, and they will be immune to any spells that require sight... *at any range* (as heavily obscured is distance-agnostic). With this effect alone, Umbra Incarnate obliterates this and *any* other similar ability in the game, bar none. + + Compare this to the Draconic Bloodline's capstone ability: it + inflicts the significantly weaker Frightened condition (disadvantage + on attacks + movement penalization), **requires a save**, **requires + Concentration**, ***is activated on an action***, only affects targets + out to 60 feet, and provides *no* benefits to allies. + + This effect has anti-synergy with the flight ability, which encourages movement, as the Sorcerer will be encouraged to stay bound to their party at all times. + + **Recommendation**: this should just be regular magical darkness that only the Sorcerer can see through. Applying it to allies makes this stronger than just about any capstone ability in 5e. Additionally, this is too strong of an effect to be activated on a bonus action; make this an action instead. +* *Frightened immunity*: there's enough going on here already. + + **Recommendation**: remove this. + +Overall, there's just way too much stuff in this ability, *but it's not a bad idea*. Tone it down and you have a cool kit-amplification ability. + +6th Level has too much packed into it. +-------------------------------------- + +Either abilities are fine on their own, but I strongly prefer keeping Umbra Tentacle over Far Touch: + +Umbra Tentacle is a neat, gameplay defining tool, as it: + +* Requires no sorcery points to use. +* Takes a bonus action, meaning it's almost always available, as Sorcerers rarely take bonus actions. + +I would clean up the verbiage to make it the source of the ability more clear (does it come from you or a point of your choosing?), but on its own I think this ability is a solid foundation to build upon. + +Far Touch, however, takes this ability over the top. Umbra Tentacle is similar in power to each other 6th Level ability, so there's no need to cram another ability in, especially something as powerful as a *cost-free* Distant Spell usage on every touch spell. + +Far Touch should be moved to 14th Level. Into the Void can go. +-------------------------------------------------------------- + +As the ability to see through magical darkness is an integral part of this subclass, in most cases the Sorcerer will want to engage enemies from the cover of magical darkness. As such, attacks against them will already be made at disadvantage, so Into the Void will rarely be useful. + +Good news: this is the perfect spot for Far Touch. + +1st Level is great! +------------------- + +1st Level is thematically satisfying and directs the Sorcerer into choices that will reinforce the thematic of this subclass. No tweaks needed here.","Balanced yes, though some changes may make the subclass more distinct +===================================================================== + +Sorcerer Homebrews are difficult to balance, because you always have to think about the sorcery point cost of abilities. What I've given below are estimates of what I think would be balanced, but the best way to be sure of what does and does not work is to playtest. + +*Extended Darkvision* - Useful, probably letting you see most hidden creature before they see you, but not overpowered. + +*Expanded Spell list* - My only worry about giving the sorcerer extra spells would be their interaction with Metamagic, however I don't believe any of these would be problematic. If you don't like Synaptic Static, Maybe consider Enervation (Though its interaction with Metamagic may be strange, specifically Twinned Spell) or Negative Energy Flood. + +*Far Touch* - This is basically giving the player the Distant Spell Metamagic but removing the Sorcerer point cost. Useful, but might be unnecessarily overlapping. + +*Umbra Tentacle* - This is interesting, and sorcerers don't often get to make use of there bonus action so it is a nice addition, however I think the two level 6 abilities might be best if combined together, as below: + +> +> **Umbra Tentacle** - As a bonus action, you summon a spectral milky black tentacle within 30 feet of yourself. The tentacle has an AC of 10 + your Charisma Modifier, and hit points equal to 2 times your sorcerer level. The tentacle can then target a creature within 5 feet of it and force them to make a strength saving throw. On a failure, the creature is pushed 10 feet from the tentacle. On subsequent turns you can move the tentacle up to 20 feet and attempt the push again as a bonus action. You are also able to cast spells with a range of touch on creatures you can see as though you were in the tentacle's space. The tentacle disappears after one minute or if you end your turn more than 50 feet from the tentacle. You are unable to summon the tentacle again until after a long rest or if you spend 2 sorcery points. +> +> +> + +This changes the tentacle to be something you need to control its location, instead of these 2 abilities being able to influence anything on the battlefield in range. I think by making the tentacle have a location and having to move it around the battlefield makes the pull unnecessary, and the ability should be fine with just a push. I tried to make this ability comparable to other similar abilities: + +* the Shadow Sorcerers *Hound of Ill Omen* ability is comparable, though it is able to deal damage, which I think makes it strong enough to justify the extra sorcery point cost compared to this ability. +* The Trickery Domain Cleric has its *Channel Divinity: Invoke Duplicity*, which is very similar; the main difference being the Cleric can cast any spell, not just touch from the target space, and the Umbra tentacle also has its push and can be hit. +* EDIT: the UA Lurker in the Deep Warlock subclass has a similar ability as the tendril, Grasp of the Deep. This is a damaging attack more than a utility one like yours, however it still might be worth taking into consideration for any future iterations of this class you try. +Overall this may still feel a bit underwhelming, maybe adding some damage to the tentacles push, and increasing the Sorcery point cost to 3 could buff this up, but you would have to play test to confirm. + +*Into the Void* - I'm not sure if 2 sorcery points is the correct cost for this ability. Blur itself is a second level spell, and it lasts for a full minute, though this ability is able to be used as a reaction. My idea using my alternative Umbra Tentacle: + +> +> **Void Swap** - as a reaction to being targeted by an attack from a creature you can see, you spend 1 sorcery point swap your position with your Umbra Tentacle. The attack has disadvantage on the tentacle, as the tendril's squirms in place after the transfer. +> +> +> + +Since you wanted the tendril to be the core of the class, this would give the level 14 ability a further tie to the tendril, while still having a similar effect to the original ability. Again, Playtest to figure out the correct number of sorcery points here, I decreased the cost as it would only apply to a single attack instead of until the start of your next turn, and you are likely to use this ability frequently when targeted. + +*Umbra Incarnate* - I think this is excellent! Really matches the flavour of the class, gives a buff to the Tendril (and works with my alternative), and seems powerful enough to justify being a level 18 ability. Nicely done. Only thing to address is Sorcery Point cost: at level 18 you can use this ability 3 times before a long rest, which seems good to me, but you would need to playtest to be sure. **EDIT** I missed that you now get to use your tentacle three times as a bonus action. Tha's too much. Make it still one time and overall the ability is nice. + +Summary: Playtest! +------------------ + +The only way to know if this class is working is to playtest over and over and over again. Is the Spell List sensible? Does the Tendril have too high of a cost? Does the reaction drain spell points too quickly? You won't know until you see it in action." +26739981,"I'm new to Cake php. +I have a problem using bake + +I set up a migration with user table + +``` +public $migration = array( + 'up' => array( + 'create_table' => array( + 'users' => array( + 'user_id' => array('type' => 'integer', 'null' => false, 'key' => 'primary'), + 'username' => array('type' => 'string', 'null' => false, 'length' => 250), + 'password' => array('type' => 'text', 'null' => false), + 'created' => array('type' => 'string', 'null' => false, 'length' => 14), + 'modified' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 14), + 'indexes' => array( + 'PRIMARY' => array('column' => 'user_id', 'unique' => 1) + ) + ) + ) + ), + 'down' => array( + 'drop_table' => array( + 'users' + ) + ) + ); + +``` + +and migrate this file on the db then I tried to do the command ""cake bake all"" +the problem is that User made a reference to itself with belongsTo and hasMany +is that the default of using bake? + +``` +class User extends AppModel { + +/** + * Validation rules + * + * @var array + */ + public $validate = array( + 'user_id' => array( + 'numeric' => array( + 'rule' => array('numeric'), + //'message' => 'Your custom message here', + //'allowEmpty' => false, + //'required' => false, + //'last' => false, // Stop validation after this rule + //'on' => 'create', // Limit validation to 'create' or 'update' operations + ), + ), + 'username' => array( + 'notEmpty' => array( + 'rule' => array('notEmpty'), + //'message' => 'Your custom message here', + //'allowEmpty' => false, + //'required' => false, + //'last' => false, // Stop validation after this rule + //'on' => 'create', // Limit validation to 'create' or 'update' operations + ), + ), + 'date_created' => array( + 'notEmpty' => array( + 'rule' => array('notEmpty'), + //'message' => 'Your custom message here', + //'allowEmpty' => false, + //'required' => false, + //'last' => false, // Stop validation after this rule + //'on' => 'create', // Limit validation to 'create' or 'update' operations + ), + ), + ); + + //The Associations below have been created with all possible keys, those that are not needed can be removed + +/** + * belongsTo associations + * + * @var array + */ + public $belongsTo = array( + 'User' => array( + 'className' => 'User', + 'foreignKey' => 'user_id', + 'conditions' => '', + 'fields' => '', + 'order' => '' + ) + ); + +/** + * hasMany associations + * + * @var array + */ + public $hasMany = array( + 'User' => array( + 'className' => 'User', + 'foreignKey' => 'user_id', + 'dependent' => false, + 'conditions' => '', + 'fields' => '', + 'order' => '', + 'limit' => '', + 'offset' => '', + 'exclusive' => '', + 'finderQuery' => '', + 'counterQuery' => '' + ) + ); + +} + +``` + +is there something I missing here? +Should I leave that and modify it manually or there's a config that I missed.",2014/11/04,"['https://Stackoverflow.com/questions/26739981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1097307/']","> +> Today I have the need to allocate a vector with size 100000 in Matlab. +> +> +> + +Now, as noted in the comments and such, the method you tried (`a=ones(100000);`) creates a 100000x100000 matrix, which is not what you want. + +I would suggest you try: + +``` +a = ones(1, 100000); + +``` + +Since that creates a vector rather than a matrix.","Well the first declaration tries to build a matrix of 1000000x1000000 ones. That would be **~931 GB**. + +The second tries to declare a matrix of 10000 x 10000. That would be **~95MB**. + +I assumed each one is stored on a byte. If they use floats, than the requested memory size will be 4 times larger." +26739981,"I'm new to Cake php. +I have a problem using bake + +I set up a migration with user table + +``` +public $migration = array( + 'up' => array( + 'create_table' => array( + 'users' => array( + 'user_id' => array('type' => 'integer', 'null' => false, 'key' => 'primary'), + 'username' => array('type' => 'string', 'null' => false, 'length' => 250), + 'password' => array('type' => 'text', 'null' => false), + 'created' => array('type' => 'string', 'null' => false, 'length' => 14), + 'modified' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 14), + 'indexes' => array( + 'PRIMARY' => array('column' => 'user_id', 'unique' => 1) + ) + ) + ) + ), + 'down' => array( + 'drop_table' => array( + 'users' + ) + ) + ); + +``` + +and migrate this file on the db then I tried to do the command ""cake bake all"" +the problem is that User made a reference to itself with belongsTo and hasMany +is that the default of using bake? + +``` +class User extends AppModel { + +/** + * Validation rules + * + * @var array + */ + public $validate = array( + 'user_id' => array( + 'numeric' => array( + 'rule' => array('numeric'), + //'message' => 'Your custom message here', + //'allowEmpty' => false, + //'required' => false, + //'last' => false, // Stop validation after this rule + //'on' => 'create', // Limit validation to 'create' or 'update' operations + ), + ), + 'username' => array( + 'notEmpty' => array( + 'rule' => array('notEmpty'), + //'message' => 'Your custom message here', + //'allowEmpty' => false, + //'required' => false, + //'last' => false, // Stop validation after this rule + //'on' => 'create', // Limit validation to 'create' or 'update' operations + ), + ), + 'date_created' => array( + 'notEmpty' => array( + 'rule' => array('notEmpty'), + //'message' => 'Your custom message here', + //'allowEmpty' => false, + //'required' => false, + //'last' => false, // Stop validation after this rule + //'on' => 'create', // Limit validation to 'create' or 'update' operations + ), + ), + ); + + //The Associations below have been created with all possible keys, those that are not needed can be removed + +/** + * belongsTo associations + * + * @var array + */ + public $belongsTo = array( + 'User' => array( + 'className' => 'User', + 'foreignKey' => 'user_id', + 'conditions' => '', + 'fields' => '', + 'order' => '' + ) + ); + +/** + * hasMany associations + * + * @var array + */ + public $hasMany = array( + 'User' => array( + 'className' => 'User', + 'foreignKey' => 'user_id', + 'dependent' => false, + 'conditions' => '', + 'fields' => '', + 'order' => '', + 'limit' => '', + 'offset' => '', + 'exclusive' => '', + 'finderQuery' => '', + 'counterQuery' => '' + ) + ); + +} + +``` + +is there something I missing here? +Should I leave that and modify it manually or there's a config that I missed.",2014/11/04,"['https://Stackoverflow.com/questions/26739981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1097307/']","> +> Today I have the need to allocate a vector with size 100000 in Matlab. +> +> +> + +Now, as noted in the comments and such, the method you tried (`a=ones(100000);`) creates a 100000x100000 matrix, which is not what you want. + +I would suggest you try: + +``` +a = ones(1, 100000); + +``` + +Since that creates a vector rather than a matrix.","Arguments Matter +================ + +Calling Matlab's `ones()` or `zeros()` or `magic()` with a single argument `n`, creates a *square* matrix with size `n-by-n`: + +```matlab +>> a = ones(5) + a = 1 1 1 1 1 + 1 1 1 1 1 + 1 1 1 1 1 + 1 1 1 1 1 + 1 1 1 1 1 + +``` + +Calling the same functions with 2 arguments `(r, c)` instead creates a matrix of size `r-by-c`: + +```matlab +>> a = ones(2, 5) + a = 1 1 1 1 1 + 1 1 1 1 1 + +``` + +This is all well documented in [Matlab's documentation](http://www.mathworks.de/help/matlab/ref/zeros.html). + +Size Matters Too +================ + +Doubles +------- + +Having said this, when you do `a = zeros(1e6)` you are creating a square matrix of size `1e6 * 1e6 = 1e12`. Since these are doubles the total allocated size would be `8 * 1e12 Bytes` which is circa `(8 * 1e12) / 1024^3 = 7450.6GB`. Do you have this much RAM on your machine? + +Compare this with `a = zeros(1, 1e6)` which creates a column-vector of size `1 * 1e6 = 1e6`, for a total allocated size of `(8 * 1e6) / 1024^3 = 7.63MB`. + +Logicals +-------- + +Logical values, on the other hand are boolean values, which can be set to either `0` or `1` representing `False` or `True`. With this in mind, you can allocate matrices of logicals using either [`false()`](http://www.mathworks.de/help/matlab/ref/false.html) or [`true()`](http://www.mathworks.de/help/matlab/ref/true.html). Here the same single-argument rule applies, hence `a = false(1e6)` creates a square matrix of size `1e6 * 1e6 = 1e12`. Matlab today, as many other programming languages, stores bit values, such as booleans, into single Bytes. Even though there is a clear cost in terms of memory usage, such a mechanism provides significant performance improvements. This is because it is [accessing single bits is a slow operation](http://www.mathworks.com/matlabcentral/answers/22439-logical-array-memory-allocation). + +The total allocated size of our `a = false(1e6)` matrix would therefore be `1e12 Bytes` which is circa `1e12 / 1024^3 = 931.32GB`." +107330,"We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. + +What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? + +I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. + +To clarify, my order of operations is: + +* Server PXE boots +* Various Things are done to the hardware to prep it +* Image is copied onto the hard drive +* Image is customized (network settings) + +(Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)",2010/01/28,"['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']","DHCP is the only choice (IMHO) when you get over 5 or 6 machines ( and even then ... ) + +In your case I would also setup dDNS so that your hosts register in DNS when they get a DHCP lease, so if you know the host name you know the ip address. + +As far as host needed a static IP address. The best way is to let them configure off DHCP, but in the DHCP configuration reserve the IP address for that machine's MAC address. This lets you not have to manually configure IPs but still have ""static"" ip addressing.","Here's your main issue (as stated): + +> +> **""We don't have access to the DHCP server""** +> +> +> + +Why don't you have access to your internal DHCP server? **(fix this!)**... Your number of clients concords with most environments using DHCP (recommended). Yes, static IPs would drive you nuts!" +107330,"We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. + +What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? + +I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. + +To clarify, my order of operations is: + +* Server PXE boots +* Various Things are done to the hardware to prep it +* Image is copied onto the hard drive +* Image is customized (network settings) + +(Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)",2010/01/28,"['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']","Here's your main issue (as stated): + +> +> **""We don't have access to the DHCP server""** +> +> +> + +Why don't you have access to your internal DHCP server? **(fix this!)**... Your number of clients concords with most environments using DHCP (recommended). Yes, static IPs would drive you nuts!",Maintaining a static addressed network quickly becomes a hassle with more than 10-15 machines. You can set static addresses within the DHCP server's GUI. While these are only faux static addresses they ensure that no other device can get that address by requesting it from the DHCP server and when that particular device asks for an address it will always receive the same one. +107330,"We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. + +What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? + +I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. + +To clarify, my order of operations is: + +* Server PXE boots +* Various Things are done to the hardware to prep it +* Image is copied onto the hard drive +* Image is customized (network settings) + +(Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)",2010/01/28,"['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']","DHCP is the only choice (IMHO) when you get over 5 or 6 machines ( and even then ... ) + +In your case I would also setup dDNS so that your hosts register in DNS when they get a DHCP lease, so if you know the host name you know the ip address. + +As far as host needed a static IP address. The best way is to let them configure off DHCP, but in the DHCP configuration reserve the IP address for that machine's MAC address. This lets you not have to manually configure IPs but still have ""static"" ip addressing.",Maintaining a static addressed network quickly becomes a hassle with more than 10-15 machines. You can set static addresses within the DHCP server's GUI. While these are only faux static addresses they ensure that no other device can get that address by requesting it from the DHCP server and when that particular device asks for an address it will always receive the same one. +107330,"We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. + +What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? + +I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. + +To clarify, my order of operations is: + +* Server PXE boots +* Various Things are done to the hardware to prep it +* Image is copied onto the hard drive +* Image is customized (network settings) + +(Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)",2010/01/28,"['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']","DHCP is the only choice (IMHO) when you get over 5 or 6 machines ( and even then ... ) + +In your case I would also setup dDNS so that your hosts register in DNS when they get a DHCP lease, so if you know the host name you know the ip address. + +As far as host needed a static IP address. The best way is to let them configure off DHCP, but in the DHCP configuration reserve the IP address for that machine's MAC address. This lets you not have to manually configure IPs but still have ""static"" ip addressing.","If you're talking about servers you **should not** be using DHCP to configure their IP addresses. This creates all sorts of headaches long-term, and even Microsoft will tell you it's not a recommended practice. + +I relate the parable of the DHCP network that got moved to CoLocation and left the DHCP server behind: Needless to say nothing worked at the CoLo and the admin in question looked looked like an idiot. + +--- + +For Desktops and Laptops by all means use DHCP, possibly in combination with static leases if you need to ensure that machines always have the same IP when they come onto your network. This is the most sensible configuration for your end users as it lets them put their laptops on other networks (home, hotel, starbucks) without jumping through a million hoops." +107330,"We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. + +What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? + +I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. + +To clarify, my order of operations is: + +* Server PXE boots +* Various Things are done to the hardware to prep it +* Image is copied onto the hard drive +* Image is customized (network settings) + +(Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)",2010/01/28,"['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']","DHCP is the only choice (IMHO) when you get over 5 or 6 machines ( and even then ... ) + +In your case I would also setup dDNS so that your hosts register in DNS when they get a DHCP lease, so if you know the host name you know the ip address. + +As far as host needed a static IP address. The best way is to let them configure off DHCP, but in the DHCP configuration reserve the IP address for that machine's MAC address. This lets you not have to manually configure IPs but still have ""static"" ip addressing.","Fixed IP addresses for servers - always. Printers and the like can be done either way but my preference is for fixed. Workstations, laptops and the like should always be DHCP. You should be able to solve your problems by using dynamically updated DNS. Then you don't need an IP address because you can just use the machine name. + +As l0c0b0x says, if you don't have access to the DHCP server you really need to fix that. An administrator should always have control over his/her network." +107330,"We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. + +What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? + +I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. + +To clarify, my order of operations is: + +* Server PXE boots +* Various Things are done to the hardware to prep it +* Image is copied onto the hard drive +* Image is customized (network settings) + +(Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)",2010/01/28,"['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']","If you're talking about servers you **should not** be using DHCP to configure their IP addresses. This creates all sorts of headaches long-term, and even Microsoft will tell you it's not a recommended practice. + +I relate the parable of the DHCP network that got moved to CoLocation and left the DHCP server behind: Needless to say nothing worked at the CoLo and the admin in question looked looked like an idiot. + +--- + +For Desktops and Laptops by all means use DHCP, possibly in combination with static leases if you need to ensure that machines always have the same IP when they come onto your network. This is the most sensible configuration for your end users as it lets them put their laptops on other networks (home, hotel, starbucks) without jumping through a million hoops.",Maintaining a static addressed network quickly becomes a hassle with more than 10-15 machines. You can set static addresses within the DHCP server's GUI. While these are only faux static addresses they ensure that no other device can get that address by requesting it from the DHCP server and when that particular device asks for an address it will always receive the same one. +107330,"We have an environment where we have blasted a prepped Windows image out to multiple machines. We now need to customize the networking settings on each image en masse. + +What tools exist to modify that image and customize the IP address/netmask/gateway post-imaging? + +I would also look at a commercial solution that is able to deploy and customize Windows images as long as it runs on Linux and is fully scriptable. + +To clarify, my order of operations is: + +* Server PXE boots +* Various Things are done to the hardware to prep it +* Image is copied onto the hard drive +* Image is customized (network settings) + +(Naturally, if such a deployment tool exists that can do the last two in one step, I'll take that)",2010/01/28,"['https://serverfault.com/questions/107330', 'https://serverfault.com', 'https://serverfault.com/users/2101/']","Fixed IP addresses for servers - always. Printers and the like can be done either way but my preference is for fixed. Workstations, laptops and the like should always be DHCP. You should be able to solve your problems by using dynamically updated DNS. Then you don't need an IP address because you can just use the machine name. + +As l0c0b0x says, if you don't have access to the DHCP server you really need to fix that. An administrator should always have control over his/her network.",Maintaining a static addressed network quickly becomes a hassle with more than 10-15 machines. You can set static addresses within the DHCP server's GUI. While these are only faux static addresses they ensure that no other device can get that address by requesting it from the DHCP server and when that particular device asks for an address it will always receive the same one. +20077653,"I am new to android. I am trying to zoom a series of images as I have 10 images in drawable. I have an image view in main xml and 2 buttons to change the images. I took the whole idea from a question in stackoverflow. The problem is that all the images are changing perfectly but I have no idea to zoom these images. I tried the touch image view codes but remained unsuccessful. Plz help me. +Main xml; + +``` + + +``` + +Main java. + +``` + package com.galerionsekiz; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class Main extends Activity { private ImageView hImageViewPic; private Button iButton, gButton; private int currentImage = 0; int[] images = { R.drawable.r1, R.drawable.r2, R.drawable.r3, R.drawable.r4, R.drawable.r5, R.drawable.r6, R.drawable.r7, R.drawable.r8, R.drawable.r9, R.drawable.r10 }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); hImageViewPic = (ImageView)findViewById(R.id.idImageViewPic); iButton = (Button) findViewById(R.id.bIleri); gButton = (Button) findViewById(R.id.bGeri); //Just set one Click listener for the image iButton.setOnClickListener(iButtonChangeImageListener); gButton.setOnClickListener(gButtonChangeImageListener); } View.OnClickListener iButtonChangeImageListener = new OnClickListener() {public void onClick(View v) { //Increase Counter to move to next Image currentImage++; currentImage = currentImage % images.length; hImageViewPic.setImageResource(images[currentImage]); } }; View.OnClickListener gButtonChangeImageListener = new OnClickListener() { public void onClick(View v) { //Increase Counter to move to next Image currentImage--; currentImage = (currentImage + images.length) % images.length; hImageViewPic.setImageResource(images[currentImage]); } + +```",2013/11/19,"['https://Stackoverflow.com/questions/20077653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3004150/']",Read this [tutorial](http://www.androidhive.info/2013/09/android-fullscreen-image-slider-with-swipe-and-pinch-zoom-gestures/). It is an awesome integration of all image view related possibilities.,You can use [this](https://github.com/chrisbanes/PhotoView) library. It is very easy to implement what you want using this. +16819394,"I'm having the hardest time using the dropdown list side of Krypton Dropbuttons -- specifically, I don't know how to register that I've actually selected something within the dropdown list. + +In my project, I am using a dropbutton to apply a change over time, where simply clicking is immediate and the drop list has various increments of time -- I am using tweener-dotnet for the value change over time, as my calculus is awful and why reinvent the wheel?. + +I am able to use the dropbutton as a regular button just fine. In addition to that, I've been able to set my ContextMenu in the dropbutton, so when I build the solution and click on the dropdown arrow, the list shows up. What I can't do, however, is figure out how to tell the code that I've actually selected something within the dropdown list. + +I've spent a couple hours, collectively, staring at all three iterations of the DropButton examples, and none of them actually show what I'm looking for (seriously, Component Factory?!). + +**How do I use the dropdown side of the Krypton Dropbutton?** + +(For open source sake, I may just go back to a regular dropdown list and a regular button, but I really like the simplicity of the Krypton DropButton, and open source isn't really a priority with this project.)",2013/05/29,"['https://Stackoverflow.com/questions/16819394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672020/']","I know that this is late, but I've been dealing with something similar. + +For a `KryptonDropButton` you need to create a `KryptonContextMenu`, as @Roberto has stated. + +Then I went to add a listener to the manu items that I've added to the assigned `KryptonContextMenu` and found out that the designer does not support the `Name` property (or maybe I was too blind to find it). + +Anyway, I navigated to the designer file I found that those menu items were generated anyway, with default names. + +Something like this: + +![enter image description here](https://i.stack.imgur.com/ZTLIp.png) + +I then went to rename those and added events like I would normally to respond to user selection, but I won't hide that this is overkill.","**Update 2018:** the toolkit has been opensourced here: + +Component factory hasn't been actively worked on since 2011. ~~Its still closed source so that is an issue.~~ + +The Krypton Toolkit itself is a bit iffy in .net 4 and above. The KryptonContextMenu that you need with the KryptonDropButton is one of the bits that I've been having difficulty getting to work." +16819394,"I'm having the hardest time using the dropdown list side of Krypton Dropbuttons -- specifically, I don't know how to register that I've actually selected something within the dropdown list. + +In my project, I am using a dropbutton to apply a change over time, where simply clicking is immediate and the drop list has various increments of time -- I am using tweener-dotnet for the value change over time, as my calculus is awful and why reinvent the wheel?. + +I am able to use the dropbutton as a regular button just fine. In addition to that, I've been able to set my ContextMenu in the dropbutton, so when I build the solution and click on the dropdown arrow, the list shows up. What I can't do, however, is figure out how to tell the code that I've actually selected something within the dropdown list. + +I've spent a couple hours, collectively, staring at all three iterations of the DropButton examples, and none of them actually show what I'm looking for (seriously, Component Factory?!). + +**How do I use the dropdown side of the Krypton Dropbutton?** + +(For open source sake, I may just go back to a regular dropdown list and a regular button, but I really like the simplicity of the Krypton DropButton, and open source isn't really a priority with this project.)",2013/05/29,"['https://Stackoverflow.com/questions/16819394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672020/']","I'm about a year and a half late, but here's a radiobutton click event. + +Just select the control and event at the top of the IDE. + +``` +Public Sub KryptonContextMenuRadioButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles KryptonContextMenuRadioButton1.Click + +'do something + +End Sub + +```","**Update 2018:** the toolkit has been opensourced here: + +Component factory hasn't been actively worked on since 2011. ~~Its still closed source so that is an issue.~~ + +The Krypton Toolkit itself is a bit iffy in .net 4 and above. The KryptonContextMenu that you need with the KryptonDropButton is one of the bits that I've been having difficulty getting to work." +16819394,"I'm having the hardest time using the dropdown list side of Krypton Dropbuttons -- specifically, I don't know how to register that I've actually selected something within the dropdown list. + +In my project, I am using a dropbutton to apply a change over time, where simply clicking is immediate and the drop list has various increments of time -- I am using tweener-dotnet for the value change over time, as my calculus is awful and why reinvent the wheel?. + +I am able to use the dropbutton as a regular button just fine. In addition to that, I've been able to set my ContextMenu in the dropbutton, so when I build the solution and click on the dropdown arrow, the list shows up. What I can't do, however, is figure out how to tell the code that I've actually selected something within the dropdown list. + +I've spent a couple hours, collectively, staring at all three iterations of the DropButton examples, and none of them actually show what I'm looking for (seriously, Component Factory?!). + +**How do I use the dropdown side of the Krypton Dropbutton?** + +(For open source sake, I may just go back to a regular dropdown list and a regular button, but I really like the simplicity of the Krypton DropButton, and open source isn't really a priority with this project.)",2013/05/29,"['https://Stackoverflow.com/questions/16819394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672020/']","I know that this is late, but I've been dealing with something similar. + +For a `KryptonDropButton` you need to create a `KryptonContextMenu`, as @Roberto has stated. + +Then I went to add a listener to the manu items that I've added to the assigned `KryptonContextMenu` and found out that the designer does not support the `Name` property (or maybe I was too blind to find it). + +Anyway, I navigated to the designer file I found that those menu items were generated anyway, with default names. + +Something like this: + +![enter image description here](https://i.stack.imgur.com/ZTLIp.png) + +I then went to rename those and added events like I would normally to respond to user selection, but I won't hide that this is overkill.","I'm about a year and a half late, but here's a radiobutton click event. + +Just select the control and event at the top of the IDE. + +``` +Public Sub KryptonContextMenuRadioButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles KryptonContextMenuRadioButton1.Click + +'do something + +End Sub + +```" +11486756,"I am having issues creating a html table to display stats from a text file. I am sure there are 100 ways to do this better but here it is: + +**(The comments in the following script show the outputs)** + +``` +#!/bin/bash + +function getapistats () { + curl -s http://api.example.com/stats > api-stats.txt + awk {'print $1'} api-stats.txt > api-stats-int.txt + awk {'print $2'} api-stats.txt > api-stats-fqdm.txt +} + +# api-stats.txt example +# 992 cdn.example.com +# 227 static.foo.com +# 225 imgcdn.bar.com +# end api-stats.txt example + +function get_int () { + + for i in `cat api-stats-int.txt`; + do echo -e ""${i}""; + done +} + +function get_fqdn () { + + for f in `cat api-stats-fqdn.txt`; + do echo -e ""${f}""; + done + +} + +function build_table () { + +echo """"; +echo -e ""`get_int`"" ""`get_fqdn`""; +#echo -e ""`get_fqdn`""; +echo ""
""; +} + +getapistats; + +build_table > api-stats.html; + +# Output fail :| +# +# +# +# +# +# + +# Desired output: +# +# ... + +```",2012/07/14,"['https://Stackoverflow.com/questions/11486756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1258484/']","This is reasonably simple to do in pure awk: + +``` +curl -s http://api.example.com/stats > api-stats.txt +awk 'BEGIN { print ""
992
227
225cdn.example.com
static.foo.com
imgcdn.bar.com
992cdn.example.com
"" } + { print """" } + END { print ""
"" $1 """" $2 ""
"" }' api-stats.txt > api-stats.html + +``` + +Awk is really made for this type of use.","this can be done w/ bash ;) + +``` + + while read -u 3 a && read -u 4 b;do + echo $a$b; + done 3 api-stats.txt + awk {'print $1'} api-stats.txt > api-stats-int.txt + awk {'print $2'} api-stats.txt > api-stats-fqdm.txt +} + +# api-stats.txt example +# 992 cdn.example.com +# 227 static.foo.com +# 225 imgcdn.bar.com +# end api-stats.txt example + +function get_int () { + + for i in `cat api-stats-int.txt`; + do echo -e ""${i}""; + done +} + +function get_fqdn () { + + for f in `cat api-stats-fqdn.txt`; + do echo -e ""${f}""; + done + +} + +function build_table () { + +echo """"; +echo -e ""`get_int`"" ""`get_fqdn`""; +#echo -e ""`get_fqdn`""; +echo ""
""; +} + +getapistats; + +build_table > api-stats.html; + +# Output fail :| +# +# +# +# +# +# + +# Desired output: +# +# ... + +```",2012/07/14,"['https://Stackoverflow.com/questions/11486756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1258484/']","You can do it with one awk at least. + +``` +curl -s http://api.example.com/stats | awk ' + BEGIN{print ""
992
227
225cdn.example.com
static.foo.com
imgcdn.bar.com
992cdn.example.com
""} + {printf(""\n"",$1,$2)} + END{print ""
%d%s
""} +' + +```","this can be done w/ bash ;) + +``` + + while read -u 3 a && read -u 4 b;do + echo $a$b; + done 3 api-stats.txt + awk {'print $1'} api-stats.txt > api-stats-int.txt + awk {'print $2'} api-stats.txt > api-stats-fqdm.txt +} + +# api-stats.txt example +# 992 cdn.example.com +# 227 static.foo.com +# 225 imgcdn.bar.com +# end api-stats.txt example + +function get_int () { + + for i in `cat api-stats-int.txt`; + do echo -e ""${i}""; + done +} + +function get_fqdn () { + + for f in `cat api-stats-fqdn.txt`; + do echo -e ""${f}""; + done + +} + +function build_table () { + +echo """"; +echo -e ""`get_int`"" ""`get_fqdn`""; +#echo -e ""`get_fqdn`""; +echo ""
""; +} + +getapistats; + +build_table > api-stats.html; + +# Output fail :| +# +# +# +# +# +# + +# Desired output: +# +# ... + +```",2012/07/14,"['https://Stackoverflow.com/questions/11486756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1258484/']","This is reasonably simple to do in pure awk: + +``` +curl -s http://api.example.com/stats > api-stats.txt +awk 'BEGIN { print ""
992
227
225cdn.example.com
static.foo.com
imgcdn.bar.com
992cdn.example.com
"" } + { print """" } + END { print ""
"" $1 """" $2 ""
"" }' api-stats.txt > api-stats.html + +``` + +Awk is really made for this type of use.","You can do it with one awk at least. + +``` +curl -s http://api.example.com/stats | awk ' + BEGIN{print """"} + {printf(""\n"",$1,$2)} + END{print ""
%d%s
""} +' + +```" +78346,"just a quick question. Is the tissue fluid the same water potential as the cells it surrounds? I am a bit confused because if it was lower it would cause water to leave the cell and if it was higher water would enter the cell and both aren't really good for the cell. I believe tissue fluid is isotonic, am I correct?",2018/10/20,"['https://biology.stackexchange.com/questions/78346', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/46295/']","Yes, cell membranes are highly permeable for water. While diffusion through the membrane is possible ([description](https://socratic.org/questions/how-can-water-pass-through-the-lipid-bilayer), [and some science](https://pubs.acs.org/doi/pdf/10.1021/j100066a040)), it is most effective through water channel proteins ([aquaporins](https://www.anaesthesiamcq.com/FluidBook/fl1_2.php)). The different expression levels of aquaporins in different cell types result in differences in the permeability. + +And yes, the tissue fluid has to be isotonic to the cell interior. The water balance in the body is therefore highly regulated. If not enough water is available, the blood osmolarity (ratio between solubles and water) increases. This is sensed in the hypothalamus (an area in the brain which is a major player in hormone regulation) and results in production of the hormone vasopressin. This will not only increase your thirst (and therefore add more water to the system) but also regulate aquaporin expression, improving reabsorbtion of water in the kidney ([nicely shown here](https://opentextbc.ca/anatomyandphysiology/chapter/26-2-water-balance/), [actual science here](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4714093/)). Urine production is of course also important in the response to drinking too much, which can be harmful as well.. + +If tonicity is deregulated, this has serious consequences for the body ([some more science](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4895078/)). For example, mutations in vasopressin or kindney aquaporins can result in very similar phenotypes, characterized by dehydration because water levels cannot be properly regulated ([even more science](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4400507/)). + +edited for more explanation, because people complain when I give short answers to short questions ;)","Not necessarily- +cells are surrounded by a *plasma membrane* that creates a waterproof seal from their surroundings. This membrane contains embedded proteins, called *transporters* and *channels*, that enable the selective passage of water, ions, and solutes to maintain a *membrane potential*, or concentration difference between inside and outside. This enables cells to maintain homeostasis, despite changing external conditions. + +You can learn more about these processes here: + +" +190902,"Let's say that a (recursively axiomatizable) set theory $T$ extending ZF is ""ordinal-categorical"" if, whenever $M$ and $N$ are standard models of $T$ sharing the same ordinals, one has $M = N$. For example, if $T$ proves $V = L$, then $T$ is ordinal-categorical. I think the same is true if $T$ proves $V = L(0^\sharp)$. + +Is there anything else that can be said about such theories $T$? In particular, is there a way to find an axiom or axiom schema A such that all ordinal-categorical theories $T$ are precisely the (recursively axiomatizable) extensions of ZF+A? If this is not known, is finding such an A a goal of the inner model program? + +(Note: In the original post I used the word ""canonical"" instead of ""ordinal-categorical.)",2014/12/16,"['https://mathoverflow.net/questions/190902', 'https://mathoverflow.net', 'https://mathoverflow.net/users/17218/']","> +> In this edit, the statement of Friedman's theorem is reformulated (the previous formulation was incorrectly stated). Thanks to Dmytro Taranovsky and Farmer Schultzenberg for pointing out the blooper. *See also Remark 2 for recent progress (January 2023) on this topic by Schultzenberg and Taranovsky.* +> +> +> + +An old theorem of Harvey Friedman answers the question: + +**Theorem.** *Under a mild set theoretical hypothesis* $\mathrm{H}$ (see Note 1 below), *there is a cofinal subset* $U$ *of* $\omega\_1$ (see Note 2 below) *such that if* $T$ *is any r.e. extension of* $\mathrm{ZF + V \neq L}$ *that has a countable transitive model* $M$ *of height* $\alpha$, *then* $T$ *has another model* $N \neq M$ *of height* $\alpha$. + +**Note 1.** The mild set theoretical hypothesis $\mathrm{H}$ above asserts that there is an ordinal $\alpha$ of uncountable cofinality such that $V\_{\alpha} \models \mathrm{ZF}$. Thus the existence of a strongly inaccessible cardinal implies $\mathrm{H}$. + +**Note 2.** $U$ consists of $\omega\_1 \cap G$, where $G$ consists of ordinals $\alpha$ such that $L\_{\mathrm{n}(\alpha)} \cap V\_{\alpha}=L\_{\alpha}$. Here $\mathrm{n}(\alpha)$ is Friedman's notation (in the paper below) for the next admissiable ordinal after $\alpha$, i.e., the least admissible ordinal greater than $\alpha$; this ordinal is denoted $\alpha^{+,\mathrm{CK}}$ [in this MO question of Taranovsky](https://mathoverflow.net/questions/438081/minimum-transitive-models-and-v-l). + +**Note 3.**  The above Theorem follows from putting together the proof of the hard direction of Theorem 6.2 together with the proof of Lemma 6.3.1 of Friedman's paper below: + +*Countable models of set theories*, In A. R. D. Mathias & H. Rogers (eds.), **Cambridge Summer School in Mathematical Logic**, Lecture Notes in Mathematics vol. 337, Springer-Verlag. pp. 539--573 (1973). + +Two Remarks are in order. + +**Remark 1.** It is known that if the theory $\mathrm{ZF + V = L(0 ^{\#}})$ has transitive model of height $\alpha < \omega\_1$, then $\alpha \in U$; coupled with Friedman's above theorem, this implies that $\mathrm{ZF + V = L(0 ^{\#}})$ has more than one transitive model of height $\alpha$. Thus two transitive models of set theory of the same height could both believe that $0 ^{\#}$ exists, and yet they might have distinct $0 ^{\#}$s. Recall that the complexity of $0 ^{\#}$ is $\Delta^1\_3$. + +**Remark 2.** In the introduction to his aforementioned paper, Friedman posed the hitherto open question of whether the conclusion of the theorem above holds for $\alpha$ = the ordinal height of the Shepherdson-Cohen minimal model of set theory (it is known that $\alpha \notin U$). Schultzenberg's construction to [this MO question of Taranovsky](https://mathoverflow.net/questions/438081/minimum-transitive-models-and-v-l) implicitly yields a negative answer to Friedman's question. See Taranovsky's answer below for a proposed striking generalization of Schultzenberg's construction.","$\newcommand\Ord{\text{Ord}}\newcommand\Z{\mathbb{Z}}\newcommand\Q{\mathbb{Q}}$This is a nice question, and I don't have much to say about it, +except that I did want to mention that it is important in your +account that you are talking about standard models, which I take +to mean well-founded or transitive models. If you dropped that, +the phenomenon would disappear, for the following reason. + +**Theorem.** For any consistent theory $T$ extending ZF, there are +two models of $T$ with the same ordinals, such that they are not +isomorphic by any isomorphism fixing the ordinals. + +**Proof.** Let $M$ be any countable computably saturated model of $T$. +It follows that the natural numbers of the model $\omega^M$ are +nonstandard and have order type $\omega+\Z\cdot\Q$. The ordinals +of $M$ have type $\Ord^M$, which is the same as +$\omega^M\cdot\Ord^M$, by an internal isomorphism, and this has order type +$(\omega+\Z\cdot\Q)\cdot\Ord^M$. It follows that there is an +order-automorphism $\pi:\Ord^M\cong\Ord^M$ that shifts the ordinals within the nonstandard +parts of these blocks of $\omega^M$ by one (or one can make more +complicated automorphisms). That is, we shift all the $\Z$-chains by one. Since $\Ord^M\subset M$, we may extend +$\pi$ to an isomorphism $\pi:M\cong N$ to some model $N$, where $M$ +and $N$ have exactly the same ordinals, but where many ordinals +$\alpha$ that are even in $M$ are odd in $N$ and vice versa (this +will be true exactly for the ordinals that are a nonstandard +natural number successor of the largest limit ordinal below them). +Thus, $M$ and $N$ have exactly the same ordinals, but are not +isomorphic by any isomorphism fixing those ordinals. **QED** + +In particular, if ZFC is consistent, then there can be models of +ZFC+V=L that have exactly the same ordinals, but think different +things are true of those ordinals." +190902,"Let's say that a (recursively axiomatizable) set theory $T$ extending ZF is ""ordinal-categorical"" if, whenever $M$ and $N$ are standard models of $T$ sharing the same ordinals, one has $M = N$. For example, if $T$ proves $V = L$, then $T$ is ordinal-categorical. I think the same is true if $T$ proves $V = L(0^\sharp)$. + +Is there anything else that can be said about such theories $T$? In particular, is there a way to find an axiom or axiom schema A such that all ordinal-categorical theories $T$ are precisely the (recursively axiomatizable) extensions of ZF+A? If this is not known, is finding such an A a goal of the inner model program? + +(Note: In the original post I used the word ""canonical"" instead of ""ordinal-categorical.)",2014/12/16,"['https://mathoverflow.net/questions/190902', 'https://mathoverflow.net', 'https://mathoverflow.net/users/17218/']","> +> In this edit, the statement of Friedman's theorem is reformulated (the previous formulation was incorrectly stated). Thanks to Dmytro Taranovsky and Farmer Schultzenberg for pointing out the blooper. *See also Remark 2 for recent progress (January 2023) on this topic by Schultzenberg and Taranovsky.* +> +> +> + +An old theorem of Harvey Friedman answers the question: + +**Theorem.** *Under a mild set theoretical hypothesis* $\mathrm{H}$ (see Note 1 below), *there is a cofinal subset* $U$ *of* $\omega\_1$ (see Note 2 below) *such that if* $T$ *is any r.e. extension of* $\mathrm{ZF + V \neq L}$ *that has a countable transitive model* $M$ *of height* $\alpha$, *then* $T$ *has another model* $N \neq M$ *of height* $\alpha$. + +**Note 1.** The mild set theoretical hypothesis $\mathrm{H}$ above asserts that there is an ordinal $\alpha$ of uncountable cofinality such that $V\_{\alpha} \models \mathrm{ZF}$. Thus the existence of a strongly inaccessible cardinal implies $\mathrm{H}$. + +**Note 2.** $U$ consists of $\omega\_1 \cap G$, where $G$ consists of ordinals $\alpha$ such that $L\_{\mathrm{n}(\alpha)} \cap V\_{\alpha}=L\_{\alpha}$. Here $\mathrm{n}(\alpha)$ is Friedman's notation (in the paper below) for the next admissiable ordinal after $\alpha$, i.e., the least admissible ordinal greater than $\alpha$; this ordinal is denoted $\alpha^{+,\mathrm{CK}}$ [in this MO question of Taranovsky](https://mathoverflow.net/questions/438081/minimum-transitive-models-and-v-l). + +**Note 3.**  The above Theorem follows from putting together the proof of the hard direction of Theorem 6.2 together with the proof of Lemma 6.3.1 of Friedman's paper below: + +*Countable models of set theories*, In A. R. D. Mathias & H. Rogers (eds.), **Cambridge Summer School in Mathematical Logic**, Lecture Notes in Mathematics vol. 337, Springer-Verlag. pp. 539--573 (1973). + +Two Remarks are in order. + +**Remark 1.** It is known that if the theory $\mathrm{ZF + V = L(0 ^{\#}})$ has transitive model of height $\alpha < \omega\_1$, then $\alpha \in U$; coupled with Friedman's above theorem, this implies that $\mathrm{ZF + V = L(0 ^{\#}})$ has more than one transitive model of height $\alpha$. Thus two transitive models of set theory of the same height could both believe that $0 ^{\#}$ exists, and yet they might have distinct $0 ^{\#}$s. Recall that the complexity of $0 ^{\#}$ is $\Delta^1\_3$. + +**Remark 2.** In the introduction to his aforementioned paper, Friedman posed the hitherto open question of whether the conclusion of the theorem above holds for $\alpha$ = the ordinal height of the Shepherdson-Cohen minimal model of set theory (it is known that $\alpha \notin U$). Schultzenberg's construction to [this MO question of Taranovsky](https://mathoverflow.net/questions/438081/minimum-transitive-models-and-v-l) implicitly yields a negative answer to Friedman's question. See Taranovsky's answer below for a proposed striking generalization of Schultzenberg's construction.","For every c.e theory $T$ extending KP (Kripke-Platek) with a model $M$ of height $α<ω\_1$, the intersection of all such $M$ is a subset of $L\_{α^{+,\mathrm{CK}}}$. This holds since the existence of such $M$ is $Σ^1\_1(α)$. Every model $\text{ZF}+0^\#$ (or just $\text{KP}+0^\#$) of height $α$ includes a set outside of $L\_{α^{+,\mathrm{CK}}}$, so such theories do not have unique models for countable $α$. + +The interplay of uniqueness and non-uniqueness — and the conditions to guarantee uniqueness — is an important theme in inner model theory. Theories such as $\text{ACA}\_0$ or the primitive recursive set theory have unique minimal $ω$-models, but then for c.e. theories extending $\text{ATR}\_0$, the intersection of all $ω$-models (if there are any) equals HYP. (HYP is the set of hyperarithmetic sets; it corresponds to $L\_{ω\_1^{\mathrm{CK}}}$, the minimal transitive model of KPω.) With $0^\#$, uniqueness of minimal transitive models fails. And going further, $L[M\_1^\#]$ does not satisfy $V=HOD$: Despite being an inner model, $L[M\_1^\#]$ lacks sufficient closure to iterate and identify the true $M\_1^\#$ (the sharp for a Woodin cardinal). + +Back to the question, for every ordinal-categorical (as defined in the question) c.e. theory $T$, all transitive models are constructible, and for a model $M⊨T$ of possibly uncountable height $α$, $M⊂L\_{α^{+,\mathrm{CK}}}$ (uncountable $α$ can handled using countable elementary submodels). Thus, if $On^M$ is a cardinal (and $T⊢\text{KP}$), then $M ⊨ V=L$. + +Surprisingly, however, we have the following, which adapts Farmer Schlutzenberg's answer to my recent question [Minimum transitive models and V=L](https://mathoverflow.net/questions/438081/minimum-transitive-models-and-v-l?noredirect=1&lq=1) (the discussions in the two questions complement each other). + +**Theorem:** There are ordinal-categorical c.e. theories extending $\text{ZFC} + V≠L$ that have arbitrarily large transitive models (assuming ZFC has arbitrarily large transitive models). + +**Proof:** To get such models, we use existence of (non-trivial) $≤κ$-closed forcings with (as viewed from the generic extension) unique generics. Ordinarily, we might have $V[G]=V[G']$ (which interferes with defining our $G$ in $V[G]$), but we can get unique generics by encoding $G$ into choices for subsequent rounds of forcing and iterating $ω$ times (with full support). Next, for every ordinal $κ$ (including uncountable $κ$), the minimum transitive model $M$ of ZFC of height $>κ$ is pointwise definable with ordinals $<κ$ as constants. Fix a formula picking a $κ$ (as above) in $M$, and a parameter-free definable forcing as above. Using the pointwise definability of $M$ (with ordinals $<κ$ as constants) and the $≤κ$-closure, every dense open set has a parameter-free definable (in $M$) dense open subset. Thus, we can fix a choice of the generic $G$ using a computable schema as in the linked answer. Specifically, enumerate formulas; if a formula $φ\_0$ defines a dense open set here, then pick its first element (under some fixed parameter-free definable well-ordering), and then repeat with $φ\_1, φ\_2, ...$, picking the first element compatible with the previous ones. Our theory will be $\text{ZFC} + V=M[G]$ with $M$ and $G$ as above. + +A remaining open question is whether there is an ordinal-categorical theory $\text{ZFC} + A + V≠L$ (with a transitive model) where $A$ is a single statement. A model of such a theory cannot be obtained by set forcing (unlike a schema, a statement in the generic extension would be forced by some condition in the poset), and so may require new (perhaps, still forcing-like) construction methods." +33750465,"I'm working on an app's user interface, and I'm doing it programmatically. I understand the idea behind retain cycles, and feel quite confident I could identify one, but Xcode is giving me warnings when I'm trying to avoid a retain cycle. + +Essentially, I'm creating a property called `titleLabel` which will have my title, and in `viewDidLoad` I'm initializing it, and placing it on my view. The only problem is, I'm getting an Xcode warning that says: + +> +> Assigning retained object to weak variable; object will be released after assignment +> +> +> + +My property definition is as follows: + +``` +@property (nonatomic, weak) UILabel *titleLabel; + +``` + +Obviously I could fix the Xcode warning by changing `weak` to `strong` in my property definition, but I believe that would create a retain cycle (from my understanding) because the button is holding onto the View Controller and the View Controller is holding onto the button. + +Can anyone give me some insight as to how to do this properly?",2015/11/17,"['https://Stackoverflow.com/questions/33750465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3411191/']","Your understanding is flawed. If the label were to retain a reference to its view controller, you would have a retain cycle if the property were defined as `strong`. However, views do not retain references to their view controllers, so there is no cycle. Xcode is warning you correctly that your label reference will go away after the assignment. You aren't even saved by adding it as a subview (which would retain it), because it's already released by the time you try. + +The one quasi-exception to views not retaining references to controllers is with table and collection views, which have delegates and datasources which are usually their managing view controller. However, those delegate/datasource properties are defined as `assign` properties (which has another set of problems) so there is no retain cycle there, either.",i think you can set property to strong which will retain its memory and when your view will disappear call then you can set this object to nil which will release its memory. +33750465,"I'm working on an app's user interface, and I'm doing it programmatically. I understand the idea behind retain cycles, and feel quite confident I could identify one, but Xcode is giving me warnings when I'm trying to avoid a retain cycle. + +Essentially, I'm creating a property called `titleLabel` which will have my title, and in `viewDidLoad` I'm initializing it, and placing it on my view. The only problem is, I'm getting an Xcode warning that says: + +> +> Assigning retained object to weak variable; object will be released after assignment +> +> +> + +My property definition is as follows: + +``` +@property (nonatomic, weak) UILabel *titleLabel; + +``` + +Obviously I could fix the Xcode warning by changing `weak` to `strong` in my property definition, but I believe that would create a retain cycle (from my understanding) because the button is holding onto the View Controller and the View Controller is holding onto the button. + +Can anyone give me some insight as to how to do this properly?",2015/11/17,"['https://Stackoverflow.com/questions/33750465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3411191/']","Your understanding is flawed. If the label were to retain a reference to its view controller, you would have a retain cycle if the property were defined as `strong`. However, views do not retain references to their view controllers, so there is no cycle. Xcode is warning you correctly that your label reference will go away after the assignment. You aren't even saved by adding it as a subview (which would retain it), because it's already released by the time you try. + +The one quasi-exception to views not retaining references to controllers is with table and collection views, which have delegates and datasources which are usually their managing view controller. However, those delegate/datasource properties are defined as `assign` properties (which has another set of problems) so there is no retain cycle there, either.","When you create a UI element and add it as a subview to parent view. The Parent view keeps a strong reference to sub View. In your case, you could just create a UILabel variable within your function and add it to the parent. + +You could then declare a weak property that keeps a reference to this newly created label. This way, the parent view ""owns"" the label, and it takes care of cleaning up the label when the parent view goes off screen. + +``` +@interface MasterViewController () + +@property (nonatomic,weak) UILabel * theLabel; + +@end + +@implementation MasterViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + + UILabel* myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; + [self.view addSubview:myLabel]; + self.theLabel = myLabel; +} + +```" +51943181,"Hey guys so i got this dummy data: + +``` +115,IROM,1 +125,FOLCOM,1 +135,SE,1 +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 +144,BLIZZARC,1 +166,STEAD,3 +166,STEAD,3 +166,STEAD,3 +168,BANDOI,1 +179,FOX,1 +199,C4,2 +199,C4,2 + +``` + +Desired output: + +``` +IROM,1 +FOLCOM,1 +SE,1 +ATLUZ,3 +BLIZZARC,1 +STEAD,1 +BANDOI,1 +FOX,1 +C4,1 + +``` + +which comes from counting the distinct game id (the 115,125,etc). so for example the + +``` +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 + +``` + +Will be + +``` +ATLUZ,3 + +``` + +Since it have 3 distinct game id + +I tried using + +``` +cut -d',' -f 2 game.csv|uniq -c + +``` + +Where i got the following output + +``` + 1 IROM + 1 FOLCOM + 1 SE + 5 ATLUZ + 1 BLIZZARC COMP + 3 STEAD + 1 BANDOI + 1 FOX + 2 C4 + +``` + +How do i fix this ? using bash ?",2018/08/21,"['https://Stackoverflow.com/questions/51943181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3646742/']","Before executing the `cut` command, do a `uniq`. This will remove the redundant lines and then you follow your command, i.e. apply `cut` to extract `2` field and do `uniq -c` to count character + +``` +uniq game.csv | cut -d',' -f 2 | uniq -c + +```","Could you please try following too in a single `awk`. + +``` +awk -F, ' +!a[$1,$2,$3]++{ + b[$1,$2,$3]++ +} +!f[$2]++{ + g[++count]=$2 +} +END{ + for(i in b){ + split(i,array,"","") + c[array[2]]++ + } + for(q=1;q<=count;q++){ + print c[g[q]],g[q] + } +}' SUBSEP="","" Input_file + +``` + +It will give the order of output same as Input\_file's 2nd field occurrence as follows. + +``` +1 IROM +1 FOLCOM +1 SE +3 ATLUZ +1 BLIZZARC +1 STEAD +1 BANDOI +1 FOX +1 C4 + +```" +51943181,"Hey guys so i got this dummy data: + +``` +115,IROM,1 +125,FOLCOM,1 +135,SE,1 +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 +144,BLIZZARC,1 +166,STEAD,3 +166,STEAD,3 +166,STEAD,3 +168,BANDOI,1 +179,FOX,1 +199,C4,2 +199,C4,2 + +``` + +Desired output: + +``` +IROM,1 +FOLCOM,1 +SE,1 +ATLUZ,3 +BLIZZARC,1 +STEAD,1 +BANDOI,1 +FOX,1 +C4,1 + +``` + +which comes from counting the distinct game id (the 115,125,etc). so for example the + +``` +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 + +``` + +Will be + +``` +ATLUZ,3 + +``` + +Since it have 3 distinct game id + +I tried using + +``` +cut -d',' -f 2 game.csv|uniq -c + +``` + +Where i got the following output + +``` + 1 IROM + 1 FOLCOM + 1 SE + 5 ATLUZ + 1 BLIZZARC COMP + 3 STEAD + 1 BANDOI + 1 FOX + 2 C4 + +``` + +How do i fix this ? using bash ?",2018/08/21,"['https://Stackoverflow.com/questions/51943181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3646742/']","Before executing the `cut` command, do a `uniq`. This will remove the redundant lines and then you follow your command, i.e. apply `cut` to extract `2` field and do `uniq -c` to count character + +``` +uniq game.csv | cut -d',' -f 2 | uniq -c + +```","Less elegant, but you may use awk as well. If it is not granted that the same ID+NAME combos will always come consecutively, you have to count each by reading the whole file before output: + +``` +awk -F, '{c[$1,$2]+=1}END{for (ck in c){split(ck,ca,SUBSEP); print ca[2];g[ca[2]]+=1}for(gk in g){print gk,g[gk]}}' game.csv + +``` + +This will count first every [COL1,COL2] pairs then for each COL2 it counts how many distinct [COL1,COL2] pairs are nonzero." +51943181,"Hey guys so i got this dummy data: + +``` +115,IROM,1 +125,FOLCOM,1 +135,SE,1 +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 +144,BLIZZARC,1 +166,STEAD,3 +166,STEAD,3 +166,STEAD,3 +168,BANDOI,1 +179,FOX,1 +199,C4,2 +199,C4,2 + +``` + +Desired output: + +``` +IROM,1 +FOLCOM,1 +SE,1 +ATLUZ,3 +BLIZZARC,1 +STEAD,1 +BANDOI,1 +FOX,1 +C4,1 + +``` + +which comes from counting the distinct game id (the 115,125,etc). so for example the + +``` +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 + +``` + +Will be + +``` +ATLUZ,3 + +``` + +Since it have 3 distinct game id + +I tried using + +``` +cut -d',' -f 2 game.csv|uniq -c + +``` + +Where i got the following output + +``` + 1 IROM + 1 FOLCOM + 1 SE + 5 ATLUZ + 1 BLIZZARC COMP + 3 STEAD + 1 BANDOI + 1 FOX + 2 C4 + +``` + +How do i fix this ? using bash ?",2018/08/21,"['https://Stackoverflow.com/questions/51943181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3646742/']","Before executing the `cut` command, do a `uniq`. This will remove the redundant lines and then you follow your command, i.e. apply `cut` to extract `2` field and do `uniq -c` to count character + +``` +uniq game.csv | cut -d',' -f 2 | uniq -c + +```","Using [GNU `datamash`](https://www.gnu.org/software/datamash/manual/datamash.html): + +``` +datamash -t, --sort --group 2 countunique 1 < input + +``` + +Using [`awk`](https://www.gnu.org/software/gawk/manual/gawk.html): + +``` +awk -F, '!a[$1,$2]++{b[$2]++}END{for(i in b)print i FS b[i]}' input + +``` + +Using [`sort`](https://www.gnu.org/software/coreutils/manual/html_node/sort-invocation.html), [`cut`](https://www.gnu.org/software/coreutils/manual/html_node/cut-invocation.html), [`uniq`](https://www.gnu.org/software/coreutils/manual/html_node/uniq-invocation.html): + +``` +sort -u -t, -k2,2 -k1,1 input | cut -d, -f2 | uniq -c + +``` + +--- + +**Test run:** + +``` +$ cat input +111,ATLUZ,1 +121,ATLUZ,1 +121,ATLUZ,2 +142,ATLUZ,2 +115,IROM,1 +142,ATLUZ,2 +$ datamash -t, --sort --group 2 countunique 1 < input +ATLUZ,3 +IROM,1 + +``` + +As you can see, `121,ATLUZ,1` and `121,ATLUZ,2` are correctly considered to be just one `game ID`." +51943181,"Hey guys so i got this dummy data: + +``` +115,IROM,1 +125,FOLCOM,1 +135,SE,1 +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 +144,BLIZZARC,1 +166,STEAD,3 +166,STEAD,3 +166,STEAD,3 +168,BANDOI,1 +179,FOX,1 +199,C4,2 +199,C4,2 + +``` + +Desired output: + +``` +IROM,1 +FOLCOM,1 +SE,1 +ATLUZ,3 +BLIZZARC,1 +STEAD,1 +BANDOI,1 +FOX,1 +C4,1 + +``` + +which comes from counting the distinct game id (the 115,125,etc). so for example the + +``` +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 + +``` + +Will be + +``` +ATLUZ,3 + +``` + +Since it have 3 distinct game id + +I tried using + +``` +cut -d',' -f 2 game.csv|uniq -c + +``` + +Where i got the following output + +``` + 1 IROM + 1 FOLCOM + 1 SE + 5 ATLUZ + 1 BLIZZARC COMP + 3 STEAD + 1 BANDOI + 1 FOX + 2 C4 + +``` + +How do i fix this ? using bash ?",2018/08/21,"['https://Stackoverflow.com/questions/51943181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3646742/']","Before executing the `cut` command, do a `uniq`. This will remove the redundant lines and then you follow your command, i.e. apply `cut` to extract `2` field and do `uniq -c` to count character + +``` +uniq game.csv | cut -d',' -f 2 | uniq -c + +```","This also does the trick. The only thing is that your output is not sorted. + +``` +awk 'BEGIN{ FS = OFS = "","" }{ a[$2 FS $1] }END{ for ( i in a ){ split(i, b, "","" ); c[b[1]]++ } for ( i in c ) print i, c[i] }' yourfile + +``` + +Output: + +``` +BANDOI,1 +C4,1 +STEAD,1 +BLIZZARC,1 +FOLCOM,1 +ATLUZ,3 +SE,1 +IROM,1 +FOX,1 + +```" +51943181,"Hey guys so i got this dummy data: + +``` +115,IROM,1 +125,FOLCOM,1 +135,SE,1 +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 +144,BLIZZARC,1 +166,STEAD,3 +166,STEAD,3 +166,STEAD,3 +168,BANDOI,1 +179,FOX,1 +199,C4,2 +199,C4,2 + +``` + +Desired output: + +``` +IROM,1 +FOLCOM,1 +SE,1 +ATLUZ,3 +BLIZZARC,1 +STEAD,1 +BANDOI,1 +FOX,1 +C4,1 + +``` + +which comes from counting the distinct game id (the 115,125,etc). so for example the + +``` +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 + +``` + +Will be + +``` +ATLUZ,3 + +``` + +Since it have 3 distinct game id + +I tried using + +``` +cut -d',' -f 2 game.csv|uniq -c + +``` + +Where i got the following output + +``` + 1 IROM + 1 FOLCOM + 1 SE + 5 ATLUZ + 1 BLIZZARC COMP + 3 STEAD + 1 BANDOI + 1 FOX + 2 C4 + +``` + +How do i fix this ? using bash ?",2018/08/21,"['https://Stackoverflow.com/questions/51943181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3646742/']","Could you please try following too in a single `awk`. + +``` +awk -F, ' +!a[$1,$2,$3]++{ + b[$1,$2,$3]++ +} +!f[$2]++{ + g[++count]=$2 +} +END{ + for(i in b){ + split(i,array,"","") + c[array[2]]++ + } + for(q=1;q<=count;q++){ + print c[g[q]],g[q] + } +}' SUBSEP="","" Input_file + +``` + +It will give the order of output same as Input\_file's 2nd field occurrence as follows. + +``` +1 IROM +1 FOLCOM +1 SE +3 ATLUZ +1 BLIZZARC +1 STEAD +1 BANDOI +1 FOX +1 C4 + +```","Less elegant, but you may use awk as well. If it is not granted that the same ID+NAME combos will always come consecutively, you have to count each by reading the whole file before output: + +``` +awk -F, '{c[$1,$2]+=1}END{for (ck in c){split(ck,ca,SUBSEP); print ca[2];g[ca[2]]+=1}for(gk in g){print gk,g[gk]}}' game.csv + +``` + +This will count first every [COL1,COL2] pairs then for each COL2 it counts how many distinct [COL1,COL2] pairs are nonzero." +51943181,"Hey guys so i got this dummy data: + +``` +115,IROM,1 +125,FOLCOM,1 +135,SE,1 +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 +144,BLIZZARC,1 +166,STEAD,3 +166,STEAD,3 +166,STEAD,3 +168,BANDOI,1 +179,FOX,1 +199,C4,2 +199,C4,2 + +``` + +Desired output: + +``` +IROM,1 +FOLCOM,1 +SE,1 +ATLUZ,3 +BLIZZARC,1 +STEAD,1 +BANDOI,1 +FOX,1 +C4,1 + +``` + +which comes from counting the distinct game id (the 115,125,etc). so for example the + +``` +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 + +``` + +Will be + +``` +ATLUZ,3 + +``` + +Since it have 3 distinct game id + +I tried using + +``` +cut -d',' -f 2 game.csv|uniq -c + +``` + +Where i got the following output + +``` + 1 IROM + 1 FOLCOM + 1 SE + 5 ATLUZ + 1 BLIZZARC COMP + 3 STEAD + 1 BANDOI + 1 FOX + 2 C4 + +``` + +How do i fix this ? using bash ?",2018/08/21,"['https://Stackoverflow.com/questions/51943181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3646742/']","Could you please try following too in a single `awk`. + +``` +awk -F, ' +!a[$1,$2,$3]++{ + b[$1,$2,$3]++ +} +!f[$2]++{ + g[++count]=$2 +} +END{ + for(i in b){ + split(i,array,"","") + c[array[2]]++ + } + for(q=1;q<=count;q++){ + print c[g[q]],g[q] + } +}' SUBSEP="","" Input_file + +``` + +It will give the order of output same as Input\_file's 2nd field occurrence as follows. + +``` +1 IROM +1 FOLCOM +1 SE +3 ATLUZ +1 BLIZZARC +1 STEAD +1 BANDOI +1 FOX +1 C4 + +```","Using [GNU `datamash`](https://www.gnu.org/software/datamash/manual/datamash.html): + +``` +datamash -t, --sort --group 2 countunique 1 < input + +``` + +Using [`awk`](https://www.gnu.org/software/gawk/manual/gawk.html): + +``` +awk -F, '!a[$1,$2]++{b[$2]++}END{for(i in b)print i FS b[i]}' input + +``` + +Using [`sort`](https://www.gnu.org/software/coreutils/manual/html_node/sort-invocation.html), [`cut`](https://www.gnu.org/software/coreutils/manual/html_node/cut-invocation.html), [`uniq`](https://www.gnu.org/software/coreutils/manual/html_node/uniq-invocation.html): + +``` +sort -u -t, -k2,2 -k1,1 input | cut -d, -f2 | uniq -c + +``` + +--- + +**Test run:** + +``` +$ cat input +111,ATLUZ,1 +121,ATLUZ,1 +121,ATLUZ,2 +142,ATLUZ,2 +115,IROM,1 +142,ATLUZ,2 +$ datamash -t, --sort --group 2 countunique 1 < input +ATLUZ,3 +IROM,1 + +``` + +As you can see, `121,ATLUZ,1` and `121,ATLUZ,2` are correctly considered to be just one `game ID`." +51943181,"Hey guys so i got this dummy data: + +``` +115,IROM,1 +125,FOLCOM,1 +135,SE,1 +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 +144,BLIZZARC,1 +166,STEAD,3 +166,STEAD,3 +166,STEAD,3 +168,BANDOI,1 +179,FOX,1 +199,C4,2 +199,C4,2 + +``` + +Desired output: + +``` +IROM,1 +FOLCOM,1 +SE,1 +ATLUZ,3 +BLIZZARC,1 +STEAD,1 +BANDOI,1 +FOX,1 +C4,1 + +``` + +which comes from counting the distinct game id (the 115,125,etc). so for example the + +``` +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 + +``` + +Will be + +``` +ATLUZ,3 + +``` + +Since it have 3 distinct game id + +I tried using + +``` +cut -d',' -f 2 game.csv|uniq -c + +``` + +Where i got the following output + +``` + 1 IROM + 1 FOLCOM + 1 SE + 5 ATLUZ + 1 BLIZZARC COMP + 3 STEAD + 1 BANDOI + 1 FOX + 2 C4 + +``` + +How do i fix this ? using bash ?",2018/08/21,"['https://Stackoverflow.com/questions/51943181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3646742/']","Could you please try following too in a single `awk`. + +``` +awk -F, ' +!a[$1,$2,$3]++{ + b[$1,$2,$3]++ +} +!f[$2]++{ + g[++count]=$2 +} +END{ + for(i in b){ + split(i,array,"","") + c[array[2]]++ + } + for(q=1;q<=count;q++){ + print c[g[q]],g[q] + } +}' SUBSEP="","" Input_file + +``` + +It will give the order of output same as Input\_file's 2nd field occurrence as follows. + +``` +1 IROM +1 FOLCOM +1 SE +3 ATLUZ +1 BLIZZARC +1 STEAD +1 BANDOI +1 FOX +1 C4 + +```","This also does the trick. The only thing is that your output is not sorted. + +``` +awk 'BEGIN{ FS = OFS = "","" }{ a[$2 FS $1] }END{ for ( i in a ){ split(i, b, "","" ); c[b[1]]++ } for ( i in c ) print i, c[i] }' yourfile + +``` + +Output: + +``` +BANDOI,1 +C4,1 +STEAD,1 +BLIZZARC,1 +FOLCOM,1 +ATLUZ,3 +SE,1 +IROM,1 +FOX,1 + +```" +51943181,"Hey guys so i got this dummy data: + +``` +115,IROM,1 +125,FOLCOM,1 +135,SE,1 +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 +144,BLIZZARC,1 +166,STEAD,3 +166,STEAD,3 +166,STEAD,3 +168,BANDOI,1 +179,FOX,1 +199,C4,2 +199,C4,2 + +``` + +Desired output: + +``` +IROM,1 +FOLCOM,1 +SE,1 +ATLUZ,3 +BLIZZARC,1 +STEAD,1 +BANDOI,1 +FOX,1 +C4,1 + +``` + +which comes from counting the distinct game id (the 115,125,etc). so for example the + +``` +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 + +``` + +Will be + +``` +ATLUZ,3 + +``` + +Since it have 3 distinct game id + +I tried using + +``` +cut -d',' -f 2 game.csv|uniq -c + +``` + +Where i got the following output + +``` + 1 IROM + 1 FOLCOM + 1 SE + 5 ATLUZ + 1 BLIZZARC COMP + 3 STEAD + 1 BANDOI + 1 FOX + 2 C4 + +``` + +How do i fix this ? using bash ?",2018/08/21,"['https://Stackoverflow.com/questions/51943181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3646742/']","Using [GNU `datamash`](https://www.gnu.org/software/datamash/manual/datamash.html): + +``` +datamash -t, --sort --group 2 countunique 1 < input + +``` + +Using [`awk`](https://www.gnu.org/software/gawk/manual/gawk.html): + +``` +awk -F, '!a[$1,$2]++{b[$2]++}END{for(i in b)print i FS b[i]}' input + +``` + +Using [`sort`](https://www.gnu.org/software/coreutils/manual/html_node/sort-invocation.html), [`cut`](https://www.gnu.org/software/coreutils/manual/html_node/cut-invocation.html), [`uniq`](https://www.gnu.org/software/coreutils/manual/html_node/uniq-invocation.html): + +``` +sort -u -t, -k2,2 -k1,1 input | cut -d, -f2 | uniq -c + +``` + +--- + +**Test run:** + +``` +$ cat input +111,ATLUZ,1 +121,ATLUZ,1 +121,ATLUZ,2 +142,ATLUZ,2 +115,IROM,1 +142,ATLUZ,2 +$ datamash -t, --sort --group 2 countunique 1 < input +ATLUZ,3 +IROM,1 + +``` + +As you can see, `121,ATLUZ,1` and `121,ATLUZ,2` are correctly considered to be just one `game ID`.","Less elegant, but you may use awk as well. If it is not granted that the same ID+NAME combos will always come consecutively, you have to count each by reading the whole file before output: + +``` +awk -F, '{c[$1,$2]+=1}END{for (ck in c){split(ck,ca,SUBSEP); print ca[2];g[ca[2]]+=1}for(gk in g){print gk,g[gk]}}' game.csv + +``` + +This will count first every [COL1,COL2] pairs then for each COL2 it counts how many distinct [COL1,COL2] pairs are nonzero." +51943181,"Hey guys so i got this dummy data: + +``` +115,IROM,1 +125,FOLCOM,1 +135,SE,1 +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 +144,BLIZZARC,1 +166,STEAD,3 +166,STEAD,3 +166,STEAD,3 +168,BANDOI,1 +179,FOX,1 +199,C4,2 +199,C4,2 + +``` + +Desired output: + +``` +IROM,1 +FOLCOM,1 +SE,1 +ATLUZ,3 +BLIZZARC,1 +STEAD,1 +BANDOI,1 +FOX,1 +C4,1 + +``` + +which comes from counting the distinct game id (the 115,125,etc). so for example the + +``` +111,ATLUZ,1 +121,ATLUZ,2 +121,ATLUZ,2 +142,ATLUZ,2 +142,ATLUZ,2 + +``` + +Will be + +``` +ATLUZ,3 + +``` + +Since it have 3 distinct game id + +I tried using + +``` +cut -d',' -f 2 game.csv|uniq -c + +``` + +Where i got the following output + +``` + 1 IROM + 1 FOLCOM + 1 SE + 5 ATLUZ + 1 BLIZZARC COMP + 3 STEAD + 1 BANDOI + 1 FOX + 2 C4 + +``` + +How do i fix this ? using bash ?",2018/08/21,"['https://Stackoverflow.com/questions/51943181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3646742/']","Using [GNU `datamash`](https://www.gnu.org/software/datamash/manual/datamash.html): + +``` +datamash -t, --sort --group 2 countunique 1 < input + +``` + +Using [`awk`](https://www.gnu.org/software/gawk/manual/gawk.html): + +``` +awk -F, '!a[$1,$2]++{b[$2]++}END{for(i in b)print i FS b[i]}' input + +``` + +Using [`sort`](https://www.gnu.org/software/coreutils/manual/html_node/sort-invocation.html), [`cut`](https://www.gnu.org/software/coreutils/manual/html_node/cut-invocation.html), [`uniq`](https://www.gnu.org/software/coreutils/manual/html_node/uniq-invocation.html): + +``` +sort -u -t, -k2,2 -k1,1 input | cut -d, -f2 | uniq -c + +``` + +--- + +**Test run:** + +``` +$ cat input +111,ATLUZ,1 +121,ATLUZ,1 +121,ATLUZ,2 +142,ATLUZ,2 +115,IROM,1 +142,ATLUZ,2 +$ datamash -t, --sort --group 2 countunique 1 < input +ATLUZ,3 +IROM,1 + +``` + +As you can see, `121,ATLUZ,1` and `121,ATLUZ,2` are correctly considered to be just one `game ID`.","This also does the trick. The only thing is that your output is not sorted. + +``` +awk 'BEGIN{ FS = OFS = "","" }{ a[$2 FS $1] }END{ for ( i in a ){ split(i, b, "","" ); c[b[1]]++ } for ( i in c ) print i, c[i] }' yourfile + +``` + +Output: + +``` +BANDOI,1 +C4,1 +STEAD,1 +BLIZZARC,1 +FOLCOM,1 +ATLUZ,3 +SE,1 +IROM,1 +FOX,1 + +```" +20473565,"We have a automated batch Script which takes care of merge and outputs all the log (conflicts) in a text file for developers to get proper visibility. +Now the problem is sometimes it stops in between and gives the below error + +**svn: E155015: One or more conflicts were produced while merging Resolve all conflicts and rerun the merge to apply the remaining In autoated Merge Script** +Below is the command + +svn merge C:\WORKSPACE\Trunk\ --username=xyz--password=zyz --non-interactive >> C:\mergelogs\logs + +Any help would be appreciated I tried a lot of ways to fix this but no success + +Regards +Pravin",2013/12/09,"['https://Stackoverflow.com/questions/20473565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2971999/']","This happens when some of the commits were already ""cherry-picked"", i.e. merged using the `-r x:y` flag. In such case subversion first merges everything up to `x` and than everything above `y`. If merging `x` fails, it gives this error. + +I don't think you should be working around it. If you want to do the merge, just do it manually. If you don't, just tell the script to stop trying.","I would try adding the parameters: + +``` +--accept=postpone + +``` + +I use this for running `svn merge` and what it will do is add conflict markers to the files, but should always return. I'm surprised that the `--non-interactive` flag doesn't do this automatically though. The other thing to try is amend the redirection to include `2>&1` which will also redirect standard error, in case there's a warning that isn't being caught in the log file. So your new command becomes: + +``` +svn merge http://xyzBranch.local.com C:\WORKSPACE\Trunk\ --username=xyz--password=zyz --non-interactive --accept=postpone >> C:\mergelogs\logs 2>&1 + +```" +1765441,"I am updating a piece of legacy code in one of our web apps. The app allows the user to upload a spreadsheet, which we will process as a background job. + +Each of these user uploads creates a new table to store the spreadsheet data, so the number of tables in my SQL Server 2000 database will grow quickly - thousands of tables in the near term. I'm worried that this might not be something that SQL Server is optimized for. + +It would be easiest to leave this mechanism as-is, but I don't want to leave a time-bomb that is going to blow up later. Better to fix it now if it needs fixing (the obvious alternative is one large table with a key associating records with user batches). + +Is this architecture likely to create a performance problem as the number of tables grows? And if so, could the problem be mitigated by upgrading to a later version of SQL Server ? + +**Edit**: Some more information in response to questions: + +* Each of these tables has the same schema. There is no reason that it couldn't have been implemented as one large table; it just wasn't. +* Deleting old tables is also an option. They might be needed for a month or two, no longer than that.",2009/11/19,"['https://Stackoverflow.com/questions/1765441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13356/']","Having many tables is not an issue for the engine. The catalog metadata is optimized for very large sizes. There are also some advantages on having each user own its table, like ability to have separate security ACLs per table, separate table statistics for each user content and not least improve query performance for the 'accidental' table scan. + +What is a problem though is maintenance. If you leave this in place you must absolutely set up task for automated maintenance, you cannot let this as a manual task for your admins.","I think this is definitely a problem that will be a pain later. Why would you need to create a new table every time? Unless there is a really good reason to do so, I would not do it. + +The best way would be to simply create an ID and associate all uploaded data with an ID, all in the same table. This will require some work on your part, but it's much safer and more manageable to boot." +1765441,"I am updating a piece of legacy code in one of our web apps. The app allows the user to upload a spreadsheet, which we will process as a background job. + +Each of these user uploads creates a new table to store the spreadsheet data, so the number of tables in my SQL Server 2000 database will grow quickly - thousands of tables in the near term. I'm worried that this might not be something that SQL Server is optimized for. + +It would be easiest to leave this mechanism as-is, but I don't want to leave a time-bomb that is going to blow up later. Better to fix it now if it needs fixing (the obvious alternative is one large table with a key associating records with user batches). + +Is this architecture likely to create a performance problem as the number of tables grows? And if so, could the problem be mitigated by upgrading to a later version of SQL Server ? + +**Edit**: Some more information in response to questions: + +* Each of these tables has the same schema. There is no reason that it couldn't have been implemented as one large table; it just wasn't. +* Deleting old tables is also an option. They might be needed for a month or two, no longer than that.",2009/11/19,"['https://Stackoverflow.com/questions/1765441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13356/']","I think this is definitely a problem that will be a pain later. Why would you need to create a new table every time? Unless there is a really good reason to do so, I would not do it. + +The best way would be to simply create an ID and associate all uploaded data with an ID, all in the same table. This will require some work on your part, but it's much safer and more manageable to boot.","I will suggest you to store these data in a single table. At the server side you can create a console from where user/operator could manually start the task of freeing up the table entries. You can ask them for range of dates whose data is no longer needed and the same will be deleted from the db. + +You can take a step ahead and set a database trigger to wipe the entries/records after a specified time period. You can again add the UI from where the User/Operator/Admin could set these data validity limit + +Thus you could create the system such that the junk data will be auto deleted after specified time which could again be set by the Admin, as well as provide them with a console using which they can manually delete additional unwanted data." +1765441,"I am updating a piece of legacy code in one of our web apps. The app allows the user to upload a spreadsheet, which we will process as a background job. + +Each of these user uploads creates a new table to store the spreadsheet data, so the number of tables in my SQL Server 2000 database will grow quickly - thousands of tables in the near term. I'm worried that this might not be something that SQL Server is optimized for. + +It would be easiest to leave this mechanism as-is, but I don't want to leave a time-bomb that is going to blow up later. Better to fix it now if it needs fixing (the obvious alternative is one large table with a key associating records with user batches). + +Is this architecture likely to create a performance problem as the number of tables grows? And if so, could the problem be mitigated by upgrading to a later version of SQL Server ? + +**Edit**: Some more information in response to questions: + +* Each of these tables has the same schema. There is no reason that it couldn't have been implemented as one large table; it just wasn't. +* Deleting old tables is also an option. They might be needed for a month or two, no longer than that.",2009/11/19,"['https://Stackoverflow.com/questions/1765441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13356/']","Having many tables is not an issue for the engine. The catalog metadata is optimized for very large sizes. There are also some advantages on having each user own its table, like ability to have separate security ACLs per table, separate table statistics for each user content and not least improve query performance for the 'accidental' table scan. + +What is a problem though is maintenance. If you leave this in place you must absolutely set up task for automated maintenance, you cannot let this as a manual task for your admins.","Having all of these tables isn't ideal for any database. After the upload, does the web app use the newly created table? Maybe it gives some feedback to the user on what was uploaded? + +Does your application utilize all of these tables for any reporting etc? You mentioned keeping them around for a few months - not sure why. If not move the contents to a central table and drop the individual table. + +Once the backend is taken care of, recode the website to save uploads to a central table. You may need two tables. An UploadHeader table to track the upload batch: who uploaded, when, etc. and link to a detail table with the individual records from the excel upload." +1765441,"I am updating a piece of legacy code in one of our web apps. The app allows the user to upload a spreadsheet, which we will process as a background job. + +Each of these user uploads creates a new table to store the spreadsheet data, so the number of tables in my SQL Server 2000 database will grow quickly - thousands of tables in the near term. I'm worried that this might not be something that SQL Server is optimized for. + +It would be easiest to leave this mechanism as-is, but I don't want to leave a time-bomb that is going to blow up later. Better to fix it now if it needs fixing (the obvious alternative is one large table with a key associating records with user batches). + +Is this architecture likely to create a performance problem as the number of tables grows? And if so, could the problem be mitigated by upgrading to a later version of SQL Server ? + +**Edit**: Some more information in response to questions: + +* Each of these tables has the same schema. There is no reason that it couldn't have been implemented as one large table; it just wasn't. +* Deleting old tables is also an option. They might be needed for a month or two, no longer than that.",2009/11/19,"['https://Stackoverflow.com/questions/1765441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13356/']","Having many tables is not an issue for the engine. The catalog metadata is optimized for very large sizes. There are also some advantages on having each user own its table, like ability to have separate security ACLs per table, separate table statistics for each user content and not least improve query performance for the 'accidental' table scan. + +What is a problem though is maintenance. If you leave this in place you must absolutely set up task for automated maintenance, you cannot let this as a manual task for your admins.","I will suggest you to store these data in a single table. At the server side you can create a console from where user/operator could manually start the task of freeing up the table entries. You can ask them for range of dates whose data is no longer needed and the same will be deleted from the db. + +You can take a step ahead and set a database trigger to wipe the entries/records after a specified time period. You can again add the UI from where the User/Operator/Admin could set these data validity limit + +Thus you could create the system such that the junk data will be auto deleted after specified time which could again be set by the Admin, as well as provide them with a console using which they can manually delete additional unwanted data." +1765441,"I am updating a piece of legacy code in one of our web apps. The app allows the user to upload a spreadsheet, which we will process as a background job. + +Each of these user uploads creates a new table to store the spreadsheet data, so the number of tables in my SQL Server 2000 database will grow quickly - thousands of tables in the near term. I'm worried that this might not be something that SQL Server is optimized for. + +It would be easiest to leave this mechanism as-is, but I don't want to leave a time-bomb that is going to blow up later. Better to fix it now if it needs fixing (the obvious alternative is one large table with a key associating records with user batches). + +Is this architecture likely to create a performance problem as the number of tables grows? And if so, could the problem be mitigated by upgrading to a later version of SQL Server ? + +**Edit**: Some more information in response to questions: + +* Each of these tables has the same schema. There is no reason that it couldn't have been implemented as one large table; it just wasn't. +* Deleting old tables is also an option. They might be needed for a month or two, no longer than that.",2009/11/19,"['https://Stackoverflow.com/questions/1765441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13356/']","Having all of these tables isn't ideal for any database. After the upload, does the web app use the newly created table? Maybe it gives some feedback to the user on what was uploaded? + +Does your application utilize all of these tables for any reporting etc? You mentioned keeping them around for a few months - not sure why. If not move the contents to a central table and drop the individual table. + +Once the backend is taken care of, recode the website to save uploads to a central table. You may need two tables. An UploadHeader table to track the upload batch: who uploaded, when, etc. and link to a detail table with the individual records from the excel upload.","I will suggest you to store these data in a single table. At the server side you can create a console from where user/operator could manually start the task of freeing up the table entries. You can ask them for range of dates whose data is no longer needed and the same will be deleted from the db. + +You can take a step ahead and set a database trigger to wipe the entries/records after a specified time period. You can again add the UI from where the User/Operator/Admin could set these data validity limit + +Thus you could create the system such that the junk data will be auto deleted after specified time which could again be set by the Admin, as well as provide them with a console using which they can manually delete additional unwanted data." +14541090,"So far I have this working properly for the error message only. However, I would like this to work for success message as well. This should happen when the submit button is pressed in the contact form. Click contact at the top right of the page to scroll to it. + +You can test it [here](http://new.syntheticmedia.net). + +Here is the jQuery I'm using for the error message: + +``` + $(document).ready(function() { + $("".error:first"").attr(""id"",""errors""); + $(""#errors"").each(function (){ + $(""html,body"").animate({scrollTop:$('#errors').offset().top-175}, 1000); + }); + }); + +``` + +Any way to modify it to work with scrolling to #success and #errors with the same offset().top-175 ? + +Thanks in advance!",2013/01/26,"['https://Stackoverflow.com/questions/14541090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1254063/']","You could do : + +``` + $(document).ready(function() { + var pos = null; + if($(""#contact-form #errors.visible"").length > 0) + pos = $('#errors').offset().top; + + if($(""#contact-form #success.visible"").length > 0) + pos = $('#success').offset().top; + + if(pos != null) + $(""html,body"").animate({scrollTop:pos-175}, 1000); + }); + +``` + +**And fix the fact that your script ""js/contact\_script.js"" must be declared after JQuery lib**","``` +$(document).ready(function () { + var $elementToScrollTo; + var $firstError = $("".error:first""); + if ($firstError.length > 0) { + $firstError.attr(""id"", ""errors""); + $elementToScrollTo = $firstError; + } + else { + $elementToScrollTo = $(""#success""); + } + $(""html,body"").animate({ + scrollTop: $elementToScrollTo.offset().top - 175 + }, 1000); +}); + +```" +14541090,"So far I have this working properly for the error message only. However, I would like this to work for success message as well. This should happen when the submit button is pressed in the contact form. Click contact at the top right of the page to scroll to it. + +You can test it [here](http://new.syntheticmedia.net). + +Here is the jQuery I'm using for the error message: + +``` + $(document).ready(function() { + $("".error:first"").attr(""id"",""errors""); + $(""#errors"").each(function (){ + $(""html,body"").animate({scrollTop:$('#errors').offset().top-175}, 1000); + }); + }); + +``` + +Any way to modify it to work with scrolling to #success and #errors with the same offset().top-175 ? + +Thanks in advance!",2013/01/26,"['https://Stackoverflow.com/questions/14541090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1254063/']","this solution make the same job for Contact Form 7 (popular form plugin for WordPress). I found this page during the search by Google of my problem, so I added the solution below to help others who ended also at this page. + +``` +jQuery(function ($) { + $(document).ready(function () + { + var wpcf7Elm = document.querySelector( '.wpcf7' ); + wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) { + setTimeout(function() { + $([document.documentElement, document.body]).animate({ + scrollTop: $("".wpcf7-response-output"").offset().top - 100 + }, 500); + }, 500); + //console.log(""Submited""); + }, false ); + }); +}); + +```","``` +$(document).ready(function () { + var $elementToScrollTo; + var $firstError = $("".error:first""); + if ($firstError.length > 0) { + $firstError.attr(""id"", ""errors""); + $elementToScrollTo = $firstError; + } + else { + $elementToScrollTo = $(""#success""); + } + $(""html,body"").animate({ + scrollTop: $elementToScrollTo.offset().top - 175 + }, 1000); +}); + +```" +14541090,"So far I have this working properly for the error message only. However, I would like this to work for success message as well. This should happen when the submit button is pressed in the contact form. Click contact at the top right of the page to scroll to it. + +You can test it [here](http://new.syntheticmedia.net). + +Here is the jQuery I'm using for the error message: + +``` + $(document).ready(function() { + $("".error:first"").attr(""id"",""errors""); + $(""#errors"").each(function (){ + $(""html,body"").animate({scrollTop:$('#errors').offset().top-175}, 1000); + }); + }); + +``` + +Any way to modify it to work with scrolling to #success and #errors with the same offset().top-175 ? + +Thanks in advance!",2013/01/26,"['https://Stackoverflow.com/questions/14541090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1254063/']","You could do : + +``` + $(document).ready(function() { + var pos = null; + if($(""#contact-form #errors.visible"").length > 0) + pos = $('#errors').offset().top; + + if($(""#contact-form #success.visible"").length > 0) + pos = $('#success').offset().top; + + if(pos != null) + $(""html,body"").animate({scrollTop:pos-175}, 1000); + }); + +``` + +**And fix the fact that your script ""js/contact\_script.js"" must be declared after JQuery lib**","this solution make the same job for Contact Form 7 (popular form plugin for WordPress). I found this page during the search by Google of my problem, so I added the solution below to help others who ended also at this page. + +``` +jQuery(function ($) { + $(document).ready(function () + { + var wpcf7Elm = document.querySelector( '.wpcf7' ); + wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) { + setTimeout(function() { + $([document.documentElement, document.body]).animate({ + scrollTop: $("".wpcf7-response-output"").offset().top - 100 + }, 500); + }, 500); + //console.log(""Submited""); + }, false ); + }); +}); + +```" +19313,"What is the difference between the words ""inquiry"" and ""query?"" I tend to associate the latter with technology (e.g., search engine queries), but I'm not sure what the actual meaning is.",2011/04/03,"['https://english.stackexchange.com/questions/19313', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/2852/']","> +> **inquiry** describes an act of asking for information or an official investigation +> +> +> **query** is simply a question, especially one addressed to an official or an organization. In writing or speaking it is used to question the accuracy of a following statement or to introduce a question. +> +> +> + +[NOAD]","Query is asking a simple question that does not require more than basic knowledge. +Inquiry is asking a question that requires further research or an investigation." +18042485,"Via GDI/GDI+ get the text pixels or glyph, how to convert to 3d mesh? Does any exists library or source code can be used? + +PS: I know D3DXCreateText, but Im using opengl...",2013/08/04,"['https://Stackoverflow.com/questions/18042485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1716020/']","If you works on OpenGL, you can try FTGL, it allows you to generate different polygon meshes from fonts, including extrudes meshes as well as render them: + + + +but I am not sure how portable is this library specially for OpenGL ES...","Using GDI is definitely not among the best ways to go if you need to obtain glyphs for the text, you could use FreeType library instead (), which is open-source and portable. It can produce both bitmaps and vectorized representation for the glyphs. You will have to initialize single instance of class FT\_Library in your program that is later used to work with multiple fonts. After loading font form file (TrueType, OpenType, PostScript and some other formats) you'll be able to obtain geometrical parameters of specific characters and use it appropriately to create texture or build primitives using your preferred rendering API, OpenGL let it be." +501,"An extreme form of constructivism is called *finitisim*. In this form, unlike the standard axiom system, infinite sets are not allowed. There are important mathematicians, such as Kronecker, who supported such a system. I can see that the natural numbers and rational numbers can easily defined in a finitist system, by easy adaptations of the standard definitions. But in order to do any significant mathematics, we need to have definitions for the irrational numbers that one is likely to encounter in practice, such as $e$ or $\sqrt{2}$. In the standard constructions, real numbers are defined as Dedekind cuts or Cauchy sequences, which are actually sets of infinite cardinality, so they are of no use here. My question is, how would a real number like those be defined in a finitist axiom system (Of course we have no hope to construct the entire set of real numbers, since that set is uncountably infinite). + +After doing a little research I found a constructivist definition in Wikipedia , but we need a finitist definition of a function for this definition to work (Because in the standard system, a function over the set of natural numbers is actually an infinite set). + +So my question boils down to this: How can we define a function f over the natural numbers in a finitist axiom system? + +*Original version of this question, [which had been closed during private beta](http://meta.math.stackexchange.com/questions/172/why-did-you-close-my-question-if-all-sets-were-finite), is as follows:* + +> +> **If all sets were finite, how would mathematics be like?** +> +> +> If we replace the axiom that 'there +> exists an infinite set' with 'all sets +> are finite', how would mathematics be +> like? My guess is that, all the theory +> that has practical importance would +> still show up, but everything would be +> very very unreadable for humans. Is +> that true? +> +> +> We would have the natural numbers, +> athough the class of all natural +> numbers would not be a set. In the +> same sense, we could have the rational +> numbers. But could we have the real +> numbers? Can the standard +> constructions be adapted to this +> setting? +> +> +>",2010/07/22,"['https://math.stackexchange.com/questions/501', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/145/']","Disclaimer: I am not a finitist --- but as a theoretical computer scientist, I have a certain sympathy for finitism. The following is the result of me openly speculating what an ""official"" finitist response would be, based on grounds of computability. + +The short version is this: **(a)** It depends on what you mean by a 'number', but there's a reasonable approach which makes it reasonable to talk about finitistic approaches to real numbers; **(b)** What you can do finitisitically with numbers, real, rational, or otherwise, depends on how you represent those numbers. + +1. **What is a number?** Is −1 a number? Is sqrt(2) a number? Is *i* = sqrt(−1) a number? What about quaternions? --- I'm going to completely ignore this question and suggest a pragmatic, formalist approach: a ""number"" is an element of a ""number system""; and a ""number system"" is a collection of expressions which you can transform or describe properties of in some given ways (*i.e.* certain given arithmetic operations) and test certain properties (*e.g.* tests for equality, ordering, *etc.*) These expressions don't have to have a meaningful interpretation in terms of quantities or magnitudes as far as I'm concerned; *you* get to choose which operations/tests you care about. + + A finitist would demand that any operation or property be described by an algorithm which provably terminates. That is, it isn't sufficient to prove existence or universality *a la* classical logic; existence proofs must be finite constructions --- of a ""number"", that is a representation in some ""number system"" --- and univserality must be shown by a computable test. +2. **Representation of numbers:** How we represent the numbers matters. A finitist should have no qualms about rational numbers: ratios which ultimately boil down to ordered pairs. Despite this, the decimal expansions of these numbers may be infinitely long: 1/3 = 0.33333... what's going on here? + + Well, the issue is that we have two representations for the same number, one of which is finite in length (and allows us to perform computations) and another which is not finite in length. However, the decimal expansion can be easily expressed as a function: for all *k*, the *k*th decimal place after the point is '3'; so you can still characterize it precisely in terms of a finite rule. + + What's important is that there exists **some** finite way to express the number. But the way in which we choose to *define* the number (as a part of system or numbers, using some way of expressing numbers) will affect what we can do with it... +there is now a question about what operations we can perform. + +--- For rationals-as-ratios, we can add/subtract, multiply/divide, and test order/equality. So this representation is a very good one for rationals. + +--- For rationals-as-decimal-expansions, we can still add/subtract and multiply/divide, by defining a new digit-function which describes how to compute the result from the decimal expansions; these will be messier than the representations as ratios. Order comparisons are still possible for *distinct* rationals; but you cannot test equality for arbitrary decimal-expansion representations, because you cannot necessarily verify that all decimal places of the difference |*a*−*b*| are 0. The best you can do in general is testing ""equality up to precision ε"", wherein you show that |*a*−*b*| < ε, for some desired precision ε. This is a number system which informally we may say has certain amount of ""vagueness""; but it is in principle completely specified --- there's nothing wrong with this in principle. It's just a matter of how you wish to define your system of arithmetic. +3. **What representation of reals?** Obviously, because there are uncountably many real numbers, you cannot represent all real numbers even if you *aren't* a finitist. But we can still express some of them. The same is true if you're a finitist: you just don't have access to as many, and/or you're restricted in what you can do with them, according to what your representation can handle. + +--- Algebraic irrational numbers such as sqrt(2) can be expressed simply like that: ""sqrt(2)"". There's nothing wrong with the expressions ""sqrt(2) − 1"" or ""[1 + sqrt(5)]/2"" --- they express quantities perfectly well. You can perform arithmetic operations on them perfectly well; and you can also perform ordering/equality tests by transforming them into a normal form of the type ""[sum of integers and roots of integers]/[positive integer]""; if the difference of two quantities is zero, the normal form of the difference will just end up being '0'. For order comparisons, we can compute enough decimal places of each term in the sum to determine whether the result is positive or negative, a process which is guaranteed to terminate. + +--- Numbers such as π and e can be represented by decimal expansions, and computed with in this form, as with the rational numbers. The decimal expansions can be gotten from classical equalities (*e.g.* ""infinite"" series, except computing only *partial* sums; a number such as e may be expressed by some finite representation of such an 'exact' formula, together with a computable function which describes how many terms of the series are required to get a correct evaluation of the first *k* decimal places.) Of course, what you can do finitistically with these representations is limited in the same way as described above with the rationals; specifically, you cannot always test equality.","There is a fragment of mathematics that is given by a set of axioms known as the [Peano axioms](http://en.wikipedia.org/wiki/Peano_axioms). Using these rules you can carry out a vast amount of mathematics relating to natural numbers. For example you can prove lots of theorems in number theory using these axioms. The Peano axioms make no reference to sets at all, whether finite or infinite. The only things that exist in this theory are naturals. You can't even form the set of all integers. You can only talk about the naturals themselves. So a vast amount of mathematics would work absolutely fine. + +Even though Peano's axioms are about naturals, you can already use them to talk about finite sets. The idea is that any finite set could be encoded as a finite sequence of symbols which in turn could be represented as naturals using [Godel numbering](http://en.wikipedia.org/wiki/G%C3%B6del_numbering). So questions like ""is this set a subset of that one?"" could be turned into purely arithmetical statements about Godel numbers. + +So I'm pretty sure that declaring that there is no infinite set would make little difference to people working within the system defined by Peano's axioms. We'd still have all of the natural numbers to work with, we just wouldn't be able to assemble them into a single entity, the set of all natural numbers. + +On the other hand, there are theorems that make essential use of an infinite set. Like [Goodstein's theorem](http://en.wikipedia.org/wiki/Goodstein%27s_theorem). Without infinite sets (or a substitute of some sort) it would be impossible to prove this result. + +So the overall result would be, I think, that you could still do lots of mathematics fine. The mathematics you could do wouldn't be all that weird. And you'd simply be depriving yourself of a useful proof technique. + +By the way, you'd still be able to say many things about real numbers. A real number can be thought of as a Cauchy sequence. A [Cauchy sequence](http://en.wikipedia.org/wiki/Cauchy_sequence) is a certain type of sequence of rational numbers. So many statements about real numbers, when unpacked, are really statements about rational, and hence naturals, but in disguise. + +Update: Uncovering precisely what parts of mathematics you need in order to prove things is a field known as [reverse mathematics](http://en.wikipedia.org/wiki/Reverse_mathematics). Hilbert, and others mathematicians, were interested in trying to prove as much mathematics as possible using finite methods. Although it was ultimately shown that you can't carry out all mathematics using finite methods, it's surprising how much you can. [Here](http://www.andrew.cmu.edu/user/avigad/Papers/elementary.pdf)'s a paper that talks about a system called EA which has no infinite sets. Amazingly we can use results from [analytic number theory](http://en.wikipedia.org/wiki/Analytic_number_theory) in EA. This is because propositions about analytic functions can be interpreted as statements about natural numbers." +501,"An extreme form of constructivism is called *finitisim*. In this form, unlike the standard axiom system, infinite sets are not allowed. There are important mathematicians, such as Kronecker, who supported such a system. I can see that the natural numbers and rational numbers can easily defined in a finitist system, by easy adaptations of the standard definitions. But in order to do any significant mathematics, we need to have definitions for the irrational numbers that one is likely to encounter in practice, such as $e$ or $\sqrt{2}$. In the standard constructions, real numbers are defined as Dedekind cuts or Cauchy sequences, which are actually sets of infinite cardinality, so they are of no use here. My question is, how would a real number like those be defined in a finitist axiom system (Of course we have no hope to construct the entire set of real numbers, since that set is uncountably infinite). + +After doing a little research I found a constructivist definition in Wikipedia , but we need a finitist definition of a function for this definition to work (Because in the standard system, a function over the set of natural numbers is actually an infinite set). + +So my question boils down to this: How can we define a function f over the natural numbers in a finitist axiom system? + +*Original version of this question, [which had been closed during private beta](http://meta.math.stackexchange.com/questions/172/why-did-you-close-my-question-if-all-sets-were-finite), is as follows:* + +> +> **If all sets were finite, how would mathematics be like?** +> +> +> If we replace the axiom that 'there +> exists an infinite set' with 'all sets +> are finite', how would mathematics be +> like? My guess is that, all the theory +> that has practical importance would +> still show up, but everything would be +> very very unreadable for humans. Is +> that true? +> +> +> We would have the natural numbers, +> athough the class of all natural +> numbers would not be a set. In the +> same sense, we could have the rational +> numbers. But could we have the real +> numbers? Can the standard +> constructions be adapted to this +> setting? +> +> +>",2010/07/22,"['https://math.stackexchange.com/questions/501', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/145/']","Set theory with all sets finite has been studied, is a familiar theory in disguise, and is enough for most/all concrete real analysis. + +Specifically, Zermelo-Fraenkel set theory with the Axiom of Infinity replaced by its negation (informally, ""there is no infinite set"") is equivalent to first-order Peano Arithmetic. Call this system *finite ZF*, the theory of hereditarily finite sets. Then under the Goedel arithmetic encoding of finite sets, Peano Arithmetic can prove all the theorems of Finite ZF, and under any of the standard constructions of integers from finite sets, Finite ZF proves all the theorems of Peano Arithmetic. + +The implication is that theorems unprovable in PA involve intrinsically infinitary reasoning. Notably, finite ZF was used as an equivalent of PA in the Paris-Harrington paper ""A Mathematical Incompleteness in Peano Arithmetic"" which proved that their modification of the finite Ramsey theorem can't be proved in PA. + +Real numbers and infinite sequences are not directly objects of the finite ZF universe, but there is a clear sense in which real (and complex, and functional) analysis can be performed in finite ZF or in PA. One can make statements about $\pi$ or any other explicitly defined real number, as theorems about a specific sequence of rational approximations ($\forall n P(n)$) and these can be formulated and proved using a theory of finite sets. PA can perform very complicated induction proofs, i.e., transfinite induction below $\epsilon\_0$. In practice this means any concrete real number calculation in ordinary mathematics. For the example of the prime number theorem, using complex analysis and the Riemann zeta function, see Gaisi Takeuti's *Two Applications of Logic to Mathematics*. More discussion of this in a MO thread and my posting there: + + + + + +Proof theory in general and reverse mathematics in particular contain analyses of the logical strength of various theorems in mathematics (when made suitably concrete as statements about sequences of integers), and from this point of view PA, and its avatar finite set theory, are very powerful systems.","There is a fragment of mathematics that is given by a set of axioms known as the [Peano axioms](http://en.wikipedia.org/wiki/Peano_axioms). Using these rules you can carry out a vast amount of mathematics relating to natural numbers. For example you can prove lots of theorems in number theory using these axioms. The Peano axioms make no reference to sets at all, whether finite or infinite. The only things that exist in this theory are naturals. You can't even form the set of all integers. You can only talk about the naturals themselves. So a vast amount of mathematics would work absolutely fine. + +Even though Peano's axioms are about naturals, you can already use them to talk about finite sets. The idea is that any finite set could be encoded as a finite sequence of symbols which in turn could be represented as naturals using [Godel numbering](http://en.wikipedia.org/wiki/G%C3%B6del_numbering). So questions like ""is this set a subset of that one?"" could be turned into purely arithmetical statements about Godel numbers. + +So I'm pretty sure that declaring that there is no infinite set would make little difference to people working within the system defined by Peano's axioms. We'd still have all of the natural numbers to work with, we just wouldn't be able to assemble them into a single entity, the set of all natural numbers. + +On the other hand, there are theorems that make essential use of an infinite set. Like [Goodstein's theorem](http://en.wikipedia.org/wiki/Goodstein%27s_theorem). Without infinite sets (or a substitute of some sort) it would be impossible to prove this result. + +So the overall result would be, I think, that you could still do lots of mathematics fine. The mathematics you could do wouldn't be all that weird. And you'd simply be depriving yourself of a useful proof technique. + +By the way, you'd still be able to say many things about real numbers. A real number can be thought of as a Cauchy sequence. A [Cauchy sequence](http://en.wikipedia.org/wiki/Cauchy_sequence) is a certain type of sequence of rational numbers. So many statements about real numbers, when unpacked, are really statements about rational, and hence naturals, but in disguise. + +Update: Uncovering precisely what parts of mathematics you need in order to prove things is a field known as [reverse mathematics](http://en.wikipedia.org/wiki/Reverse_mathematics). Hilbert, and others mathematicians, were interested in trying to prove as much mathematics as possible using finite methods. Although it was ultimately shown that you can't carry out all mathematics using finite methods, it's surprising how much you can. [Here](http://www.andrew.cmu.edu/user/avigad/Papers/elementary.pdf)'s a paper that talks about a system called EA which has no infinite sets. Amazingly we can use results from [analytic number theory](http://en.wikipedia.org/wiki/Analytic_number_theory) in EA. This is because propositions about analytic functions can be interpreted as statements about natural numbers." +501,"An extreme form of constructivism is called *finitisim*. In this form, unlike the standard axiom system, infinite sets are not allowed. There are important mathematicians, such as Kronecker, who supported such a system. I can see that the natural numbers and rational numbers can easily defined in a finitist system, by easy adaptations of the standard definitions. But in order to do any significant mathematics, we need to have definitions for the irrational numbers that one is likely to encounter in practice, such as $e$ or $\sqrt{2}$. In the standard constructions, real numbers are defined as Dedekind cuts or Cauchy sequences, which are actually sets of infinite cardinality, so they are of no use here. My question is, how would a real number like those be defined in a finitist axiom system (Of course we have no hope to construct the entire set of real numbers, since that set is uncountably infinite). + +After doing a little research I found a constructivist definition in Wikipedia , but we need a finitist definition of a function for this definition to work (Because in the standard system, a function over the set of natural numbers is actually an infinite set). + +So my question boils down to this: How can we define a function f over the natural numbers in a finitist axiom system? + +*Original version of this question, [which had been closed during private beta](http://meta.math.stackexchange.com/questions/172/why-did-you-close-my-question-if-all-sets-were-finite), is as follows:* + +> +> **If all sets were finite, how would mathematics be like?** +> +> +> If we replace the axiom that 'there +> exists an infinite set' with 'all sets +> are finite', how would mathematics be +> like? My guess is that, all the theory +> that has practical importance would +> still show up, but everything would be +> very very unreadable for humans. Is +> that true? +> +> +> We would have the natural numbers, +> athough the class of all natural +> numbers would not be a set. In the +> same sense, we could have the rational +> numbers. But could we have the real +> numbers? Can the standard +> constructions be adapted to this +> setting? +> +> +>",2010/07/22,"['https://math.stackexchange.com/questions/501', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/145/']","There is a fragment of mathematics that is given by a set of axioms known as the [Peano axioms](http://en.wikipedia.org/wiki/Peano_axioms). Using these rules you can carry out a vast amount of mathematics relating to natural numbers. For example you can prove lots of theorems in number theory using these axioms. The Peano axioms make no reference to sets at all, whether finite or infinite. The only things that exist in this theory are naturals. You can't even form the set of all integers. You can only talk about the naturals themselves. So a vast amount of mathematics would work absolutely fine. + +Even though Peano's axioms are about naturals, you can already use them to talk about finite sets. The idea is that any finite set could be encoded as a finite sequence of symbols which in turn could be represented as naturals using [Godel numbering](http://en.wikipedia.org/wiki/G%C3%B6del_numbering). So questions like ""is this set a subset of that one?"" could be turned into purely arithmetical statements about Godel numbers. + +So I'm pretty sure that declaring that there is no infinite set would make little difference to people working within the system defined by Peano's axioms. We'd still have all of the natural numbers to work with, we just wouldn't be able to assemble them into a single entity, the set of all natural numbers. + +On the other hand, there are theorems that make essential use of an infinite set. Like [Goodstein's theorem](http://en.wikipedia.org/wiki/Goodstein%27s_theorem). Without infinite sets (or a substitute of some sort) it would be impossible to prove this result. + +So the overall result would be, I think, that you could still do lots of mathematics fine. The mathematics you could do wouldn't be all that weird. And you'd simply be depriving yourself of a useful proof technique. + +By the way, you'd still be able to say many things about real numbers. A real number can be thought of as a Cauchy sequence. A [Cauchy sequence](http://en.wikipedia.org/wiki/Cauchy_sequence) is a certain type of sequence of rational numbers. So many statements about real numbers, when unpacked, are really statements about rational, and hence naturals, but in disguise. + +Update: Uncovering precisely what parts of mathematics you need in order to prove things is a field known as [reverse mathematics](http://en.wikipedia.org/wiki/Reverse_mathematics). Hilbert, and others mathematicians, were interested in trying to prove as much mathematics as possible using finite methods. Although it was ultimately shown that you can't carry out all mathematics using finite methods, it's surprising how much you can. [Here](http://www.andrew.cmu.edu/user/avigad/Papers/elementary.pdf)'s a paper that talks about a system called EA which has no infinite sets. Amazingly we can use results from [analytic number theory](http://en.wikipedia.org/wiki/Analytic_number_theory) in EA. This is because propositions about analytic functions can be interpreted as statements about natural numbers.","Finitism still allows you to use infinitary definitions of real numbers, because a finitist is content with finite *proofs* even if the concepts mentioned by those proofs would seem to require infinite sets. For example, a finitist would still recognize that ""ZFC proves that every bounded nonempty set of reals has a least upper bound"" even if the finitist does not accept that infinite sets exist. + +Proofs in various infinitary systems are of interest to finitists because of conservation results. In this setting, a conservation result would show that if a sentence about the natural numbers of a certain form is provable in some infinitary system, the sentence is actually provable in a finitistic system. For example, there are finitistic proofs that if any $\Pi^0\_2$ sentence about the natural numbers is provable in the infinitary system $\text{WKL}\_0$ of second order arithmetic, that sentence is also provable in the finitistic system $\text{PRA}$ of primitive-recursive arithmetic. + +Many consistency results are proven finitistically. For example, there is a finitistic proof that if ZF set theory without the axiom of choice is consistent, then ZFC set theory with the axiom of choice is also consistent. This proof studies infinitary systems of set theory, but the objects actually handled are finite formal proofs rather than infinite sets." +501,"An extreme form of constructivism is called *finitisim*. In this form, unlike the standard axiom system, infinite sets are not allowed. There are important mathematicians, such as Kronecker, who supported such a system. I can see that the natural numbers and rational numbers can easily defined in a finitist system, by easy adaptations of the standard definitions. But in order to do any significant mathematics, we need to have definitions for the irrational numbers that one is likely to encounter in practice, such as $e$ or $\sqrt{2}$. In the standard constructions, real numbers are defined as Dedekind cuts or Cauchy sequences, which are actually sets of infinite cardinality, so they are of no use here. My question is, how would a real number like those be defined in a finitist axiom system (Of course we have no hope to construct the entire set of real numbers, since that set is uncountably infinite). + +After doing a little research I found a constructivist definition in Wikipedia , but we need a finitist definition of a function for this definition to work (Because in the standard system, a function over the set of natural numbers is actually an infinite set). + +So my question boils down to this: How can we define a function f over the natural numbers in a finitist axiom system? + +*Original version of this question, [which had been closed during private beta](http://meta.math.stackexchange.com/questions/172/why-did-you-close-my-question-if-all-sets-were-finite), is as follows:* + +> +> **If all sets were finite, how would mathematics be like?** +> +> +> If we replace the axiom that 'there +> exists an infinite set' with 'all sets +> are finite', how would mathematics be +> like? My guess is that, all the theory +> that has practical importance would +> still show up, but everything would be +> very very unreadable for humans. Is +> that true? +> +> +> We would have the natural numbers, +> athough the class of all natural +> numbers would not be a set. In the +> same sense, we could have the rational +> numbers. But could we have the real +> numbers? Can the standard +> constructions be adapted to this +> setting? +> +> +>",2010/07/22,"['https://math.stackexchange.com/questions/501', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/145/']","Set theory with all sets finite has been studied, is a familiar theory in disguise, and is enough for most/all concrete real analysis. + +Specifically, Zermelo-Fraenkel set theory with the Axiom of Infinity replaced by its negation (informally, ""there is no infinite set"") is equivalent to first-order Peano Arithmetic. Call this system *finite ZF*, the theory of hereditarily finite sets. Then under the Goedel arithmetic encoding of finite sets, Peano Arithmetic can prove all the theorems of Finite ZF, and under any of the standard constructions of integers from finite sets, Finite ZF proves all the theorems of Peano Arithmetic. + +The implication is that theorems unprovable in PA involve intrinsically infinitary reasoning. Notably, finite ZF was used as an equivalent of PA in the Paris-Harrington paper ""A Mathematical Incompleteness in Peano Arithmetic"" which proved that their modification of the finite Ramsey theorem can't be proved in PA. + +Real numbers and infinite sequences are not directly objects of the finite ZF universe, but there is a clear sense in which real (and complex, and functional) analysis can be performed in finite ZF or in PA. One can make statements about $\pi$ or any other explicitly defined real number, as theorems about a specific sequence of rational approximations ($\forall n P(n)$) and these can be formulated and proved using a theory of finite sets. PA can perform very complicated induction proofs, i.e., transfinite induction below $\epsilon\_0$. In practice this means any concrete real number calculation in ordinary mathematics. For the example of the prime number theorem, using complex analysis and the Riemann zeta function, see Gaisi Takeuti's *Two Applications of Logic to Mathematics*. More discussion of this in a MO thread and my posting there: + + + + + +Proof theory in general and reverse mathematics in particular contain analyses of the logical strength of various theorems in mathematics (when made suitably concrete as statements about sequences of integers), and from this point of view PA, and its avatar finite set theory, are very powerful systems.","Disclaimer: I am not a finitist --- but as a theoretical computer scientist, I have a certain sympathy for finitism. The following is the result of me openly speculating what an ""official"" finitist response would be, based on grounds of computability. + +The short version is this: **(a)** It depends on what you mean by a 'number', but there's a reasonable approach which makes it reasonable to talk about finitistic approaches to real numbers; **(b)** What you can do finitisitically with numbers, real, rational, or otherwise, depends on how you represent those numbers. + +1. **What is a number?** Is −1 a number? Is sqrt(2) a number? Is *i* = sqrt(−1) a number? What about quaternions? --- I'm going to completely ignore this question and suggest a pragmatic, formalist approach: a ""number"" is an element of a ""number system""; and a ""number system"" is a collection of expressions which you can transform or describe properties of in some given ways (*i.e.* certain given arithmetic operations) and test certain properties (*e.g.* tests for equality, ordering, *etc.*) These expressions don't have to have a meaningful interpretation in terms of quantities or magnitudes as far as I'm concerned; *you* get to choose which operations/tests you care about. + + A finitist would demand that any operation or property be described by an algorithm which provably terminates. That is, it isn't sufficient to prove existence or universality *a la* classical logic; existence proofs must be finite constructions --- of a ""number"", that is a representation in some ""number system"" --- and univserality must be shown by a computable test. +2. **Representation of numbers:** How we represent the numbers matters. A finitist should have no qualms about rational numbers: ratios which ultimately boil down to ordered pairs. Despite this, the decimal expansions of these numbers may be infinitely long: 1/3 = 0.33333... what's going on here? + + Well, the issue is that we have two representations for the same number, one of which is finite in length (and allows us to perform computations) and another which is not finite in length. However, the decimal expansion can be easily expressed as a function: for all *k*, the *k*th decimal place after the point is '3'; so you can still characterize it precisely in terms of a finite rule. + + What's important is that there exists **some** finite way to express the number. But the way in which we choose to *define* the number (as a part of system or numbers, using some way of expressing numbers) will affect what we can do with it... +there is now a question about what operations we can perform. + +--- For rationals-as-ratios, we can add/subtract, multiply/divide, and test order/equality. So this representation is a very good one for rationals. + +--- For rationals-as-decimal-expansions, we can still add/subtract and multiply/divide, by defining a new digit-function which describes how to compute the result from the decimal expansions; these will be messier than the representations as ratios. Order comparisons are still possible for *distinct* rationals; but you cannot test equality for arbitrary decimal-expansion representations, because you cannot necessarily verify that all decimal places of the difference |*a*−*b*| are 0. The best you can do in general is testing ""equality up to precision ε"", wherein you show that |*a*−*b*| < ε, for some desired precision ε. This is a number system which informally we may say has certain amount of ""vagueness""; but it is in principle completely specified --- there's nothing wrong with this in principle. It's just a matter of how you wish to define your system of arithmetic. +3. **What representation of reals?** Obviously, because there are uncountably many real numbers, you cannot represent all real numbers even if you *aren't* a finitist. But we can still express some of them. The same is true if you're a finitist: you just don't have access to as many, and/or you're restricted in what you can do with them, according to what your representation can handle. + +--- Algebraic irrational numbers such as sqrt(2) can be expressed simply like that: ""sqrt(2)"". There's nothing wrong with the expressions ""sqrt(2) − 1"" or ""[1 + sqrt(5)]/2"" --- they express quantities perfectly well. You can perform arithmetic operations on them perfectly well; and you can also perform ordering/equality tests by transforming them into a normal form of the type ""[sum of integers and roots of integers]/[positive integer]""; if the difference of two quantities is zero, the normal form of the difference will just end up being '0'. For order comparisons, we can compute enough decimal places of each term in the sum to determine whether the result is positive or negative, a process which is guaranteed to terminate. + +--- Numbers such as π and e can be represented by decimal expansions, and computed with in this form, as with the rational numbers. The decimal expansions can be gotten from classical equalities (*e.g.* ""infinite"" series, except computing only *partial* sums; a number such as e may be expressed by some finite representation of such an 'exact' formula, together with a computable function which describes how many terms of the series are required to get a correct evaluation of the first *k* decimal places.) Of course, what you can do finitistically with these representations is limited in the same way as described above with the rationals; specifically, you cannot always test equality." +501,"An extreme form of constructivism is called *finitisim*. In this form, unlike the standard axiom system, infinite sets are not allowed. There are important mathematicians, such as Kronecker, who supported such a system. I can see that the natural numbers and rational numbers can easily defined in a finitist system, by easy adaptations of the standard definitions. But in order to do any significant mathematics, we need to have definitions for the irrational numbers that one is likely to encounter in practice, such as $e$ or $\sqrt{2}$. In the standard constructions, real numbers are defined as Dedekind cuts or Cauchy sequences, which are actually sets of infinite cardinality, so they are of no use here. My question is, how would a real number like those be defined in a finitist axiom system (Of course we have no hope to construct the entire set of real numbers, since that set is uncountably infinite). + +After doing a little research I found a constructivist definition in Wikipedia , but we need a finitist definition of a function for this definition to work (Because in the standard system, a function over the set of natural numbers is actually an infinite set). + +So my question boils down to this: How can we define a function f over the natural numbers in a finitist axiom system? + +*Original version of this question, [which had been closed during private beta](http://meta.math.stackexchange.com/questions/172/why-did-you-close-my-question-if-all-sets-were-finite), is as follows:* + +> +> **If all sets were finite, how would mathematics be like?** +> +> +> If we replace the axiom that 'there +> exists an infinite set' with 'all sets +> are finite', how would mathematics be +> like? My guess is that, all the theory +> that has practical importance would +> still show up, but everything would be +> very very unreadable for humans. Is +> that true? +> +> +> We would have the natural numbers, +> athough the class of all natural +> numbers would not be a set. In the +> same sense, we could have the rational +> numbers. But could we have the real +> numbers? Can the standard +> constructions be adapted to this +> setting? +> +> +>",2010/07/22,"['https://math.stackexchange.com/questions/501', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/145/']","Disclaimer: I am not a finitist --- but as a theoretical computer scientist, I have a certain sympathy for finitism. The following is the result of me openly speculating what an ""official"" finitist response would be, based on grounds of computability. + +The short version is this: **(a)** It depends on what you mean by a 'number', but there's a reasonable approach which makes it reasonable to talk about finitistic approaches to real numbers; **(b)** What you can do finitisitically with numbers, real, rational, or otherwise, depends on how you represent those numbers. + +1. **What is a number?** Is −1 a number? Is sqrt(2) a number? Is *i* = sqrt(−1) a number? What about quaternions? --- I'm going to completely ignore this question and suggest a pragmatic, formalist approach: a ""number"" is an element of a ""number system""; and a ""number system"" is a collection of expressions which you can transform or describe properties of in some given ways (*i.e.* certain given arithmetic operations) and test certain properties (*e.g.* tests for equality, ordering, *etc.*) These expressions don't have to have a meaningful interpretation in terms of quantities or magnitudes as far as I'm concerned; *you* get to choose which operations/tests you care about. + + A finitist would demand that any operation or property be described by an algorithm which provably terminates. That is, it isn't sufficient to prove existence or universality *a la* classical logic; existence proofs must be finite constructions --- of a ""number"", that is a representation in some ""number system"" --- and univserality must be shown by a computable test. +2. **Representation of numbers:** How we represent the numbers matters. A finitist should have no qualms about rational numbers: ratios which ultimately boil down to ordered pairs. Despite this, the decimal expansions of these numbers may be infinitely long: 1/3 = 0.33333... what's going on here? + + Well, the issue is that we have two representations for the same number, one of which is finite in length (and allows us to perform computations) and another which is not finite in length. However, the decimal expansion can be easily expressed as a function: for all *k*, the *k*th decimal place after the point is '3'; so you can still characterize it precisely in terms of a finite rule. + + What's important is that there exists **some** finite way to express the number. But the way in which we choose to *define* the number (as a part of system or numbers, using some way of expressing numbers) will affect what we can do with it... +there is now a question about what operations we can perform. + +--- For rationals-as-ratios, we can add/subtract, multiply/divide, and test order/equality. So this representation is a very good one for rationals. + +--- For rationals-as-decimal-expansions, we can still add/subtract and multiply/divide, by defining a new digit-function which describes how to compute the result from the decimal expansions; these will be messier than the representations as ratios. Order comparisons are still possible for *distinct* rationals; but you cannot test equality for arbitrary decimal-expansion representations, because you cannot necessarily verify that all decimal places of the difference |*a*−*b*| are 0. The best you can do in general is testing ""equality up to precision ε"", wherein you show that |*a*−*b*| < ε, for some desired precision ε. This is a number system which informally we may say has certain amount of ""vagueness""; but it is in principle completely specified --- there's nothing wrong with this in principle. It's just a matter of how you wish to define your system of arithmetic. +3. **What representation of reals?** Obviously, because there are uncountably many real numbers, you cannot represent all real numbers even if you *aren't* a finitist. But we can still express some of them. The same is true if you're a finitist: you just don't have access to as many, and/or you're restricted in what you can do with them, according to what your representation can handle. + +--- Algebraic irrational numbers such as sqrt(2) can be expressed simply like that: ""sqrt(2)"". There's nothing wrong with the expressions ""sqrt(2) − 1"" or ""[1 + sqrt(5)]/2"" --- they express quantities perfectly well. You can perform arithmetic operations on them perfectly well; and you can also perform ordering/equality tests by transforming them into a normal form of the type ""[sum of integers and roots of integers]/[positive integer]""; if the difference of two quantities is zero, the normal form of the difference will just end up being '0'. For order comparisons, we can compute enough decimal places of each term in the sum to determine whether the result is positive or negative, a process which is guaranteed to terminate. + +--- Numbers such as π and e can be represented by decimal expansions, and computed with in this form, as with the rational numbers. The decimal expansions can be gotten from classical equalities (*e.g.* ""infinite"" series, except computing only *partial* sums; a number such as e may be expressed by some finite representation of such an 'exact' formula, together with a computable function which describes how many terms of the series are required to get a correct evaluation of the first *k* decimal places.) Of course, what you can do finitistically with these representations is limited in the same way as described above with the rationals; specifically, you cannot always test equality.","Finitism still allows you to use infinitary definitions of real numbers, because a finitist is content with finite *proofs* even if the concepts mentioned by those proofs would seem to require infinite sets. For example, a finitist would still recognize that ""ZFC proves that every bounded nonempty set of reals has a least upper bound"" even if the finitist does not accept that infinite sets exist. + +Proofs in various infinitary systems are of interest to finitists because of conservation results. In this setting, a conservation result would show that if a sentence about the natural numbers of a certain form is provable in some infinitary system, the sentence is actually provable in a finitistic system. For example, there are finitistic proofs that if any $\Pi^0\_2$ sentence about the natural numbers is provable in the infinitary system $\text{WKL}\_0$ of second order arithmetic, that sentence is also provable in the finitistic system $\text{PRA}$ of primitive-recursive arithmetic. + +Many consistency results are proven finitistically. For example, there is a finitistic proof that if ZF set theory without the axiom of choice is consistent, then ZFC set theory with the axiom of choice is also consistent. This proof studies infinitary systems of set theory, but the objects actually handled are finite formal proofs rather than infinite sets." +501,"An extreme form of constructivism is called *finitisim*. In this form, unlike the standard axiom system, infinite sets are not allowed. There are important mathematicians, such as Kronecker, who supported such a system. I can see that the natural numbers and rational numbers can easily defined in a finitist system, by easy adaptations of the standard definitions. But in order to do any significant mathematics, we need to have definitions for the irrational numbers that one is likely to encounter in practice, such as $e$ or $\sqrt{2}$. In the standard constructions, real numbers are defined as Dedekind cuts or Cauchy sequences, which are actually sets of infinite cardinality, so they are of no use here. My question is, how would a real number like those be defined in a finitist axiom system (Of course we have no hope to construct the entire set of real numbers, since that set is uncountably infinite). + +After doing a little research I found a constructivist definition in Wikipedia , but we need a finitist definition of a function for this definition to work (Because in the standard system, a function over the set of natural numbers is actually an infinite set). + +So my question boils down to this: How can we define a function f over the natural numbers in a finitist axiom system? + +*Original version of this question, [which had been closed during private beta](http://meta.math.stackexchange.com/questions/172/why-did-you-close-my-question-if-all-sets-were-finite), is as follows:* + +> +> **If all sets were finite, how would mathematics be like?** +> +> +> If we replace the axiom that 'there +> exists an infinite set' with 'all sets +> are finite', how would mathematics be +> like? My guess is that, all the theory +> that has practical importance would +> still show up, but everything would be +> very very unreadable for humans. Is +> that true? +> +> +> We would have the natural numbers, +> athough the class of all natural +> numbers would not be a set. In the +> same sense, we could have the rational +> numbers. But could we have the real +> numbers? Can the standard +> constructions be adapted to this +> setting? +> +> +>",2010/07/22,"['https://math.stackexchange.com/questions/501', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/145/']","Set theory with all sets finite has been studied, is a familiar theory in disguise, and is enough for most/all concrete real analysis. + +Specifically, Zermelo-Fraenkel set theory with the Axiom of Infinity replaced by its negation (informally, ""there is no infinite set"") is equivalent to first-order Peano Arithmetic. Call this system *finite ZF*, the theory of hereditarily finite sets. Then under the Goedel arithmetic encoding of finite sets, Peano Arithmetic can prove all the theorems of Finite ZF, and under any of the standard constructions of integers from finite sets, Finite ZF proves all the theorems of Peano Arithmetic. + +The implication is that theorems unprovable in PA involve intrinsically infinitary reasoning. Notably, finite ZF was used as an equivalent of PA in the Paris-Harrington paper ""A Mathematical Incompleteness in Peano Arithmetic"" which proved that their modification of the finite Ramsey theorem can't be proved in PA. + +Real numbers and infinite sequences are not directly objects of the finite ZF universe, but there is a clear sense in which real (and complex, and functional) analysis can be performed in finite ZF or in PA. One can make statements about $\pi$ or any other explicitly defined real number, as theorems about a specific sequence of rational approximations ($\forall n P(n)$) and these can be formulated and proved using a theory of finite sets. PA can perform very complicated induction proofs, i.e., transfinite induction below $\epsilon\_0$. In practice this means any concrete real number calculation in ordinary mathematics. For the example of the prime number theorem, using complex analysis and the Riemann zeta function, see Gaisi Takeuti's *Two Applications of Logic to Mathematics*. More discussion of this in a MO thread and my posting there: + + + + + +Proof theory in general and reverse mathematics in particular contain analyses of the logical strength of various theorems in mathematics (when made suitably concrete as statements about sequences of integers), and from this point of view PA, and its avatar finite set theory, are very powerful systems.","Finitism still allows you to use infinitary definitions of real numbers, because a finitist is content with finite *proofs* even if the concepts mentioned by those proofs would seem to require infinite sets. For example, a finitist would still recognize that ""ZFC proves that every bounded nonempty set of reals has a least upper bound"" even if the finitist does not accept that infinite sets exist. + +Proofs in various infinitary systems are of interest to finitists because of conservation results. In this setting, a conservation result would show that if a sentence about the natural numbers of a certain form is provable in some infinitary system, the sentence is actually provable in a finitistic system. For example, there are finitistic proofs that if any $\Pi^0\_2$ sentence about the natural numbers is provable in the infinitary system $\text{WKL}\_0$ of second order arithmetic, that sentence is also provable in the finitistic system $\text{PRA}$ of primitive-recursive arithmetic. + +Many consistency results are proven finitistically. For example, there is a finitistic proof that if ZF set theory without the axiom of choice is consistent, then ZFC set theory with the axiom of choice is also consistent. This proof studies infinitary systems of set theory, but the objects actually handled are finite formal proofs rather than infinite sets." +87839,I have this image.I want to crop just triangle not its white background for logo im creating.How can i do it in illustrator or photoshop?[![enter image description here](https://i.stack.imgur.com/gLx3w.jpg)](https://i.stack.imgur.com/gLx3w.jpg),2017/04/01,"['https://graphicdesign.stackexchange.com/questions/87839', 'https://graphicdesign.stackexchange.com', 'https://graphicdesign.stackexchange.com/users/70543/']","If you want my opinion why your design doesn't work so well, I think it's because more of the contents lie outside the natural circle shape made by the original design - especially that bold ""GAYPRIL"" text. + +You can see it here if I overlay a circle on both designs. + +[![enter image description here](https://i.stack.imgur.com/r5wjD.png)](https://i.stack.imgur.com/r5wjD.png) + +I think this could be improved if you ensure most of the design elements are within within the bounds of the circle, basically to improve the composition. + +Something like this perhaps + +[![enter image description here](https://i.stack.imgur.com/1vei2.jpg)](https://i.stack.imgur.com/1vei2.jpg) + +Also you might want to rethink that slight wavy warp on the GAYPRIL text. Might be better if it was unwarped. Also the R and A are very similar - from a distance it might look like GAYPAIL. Perhaps consider changing the font.","You have addressed the biggest issue in your design with the changes to your fonts, and it looks so much better. Regarding your further question about the images, the hearts aren't completely working with the feel of your design. The sun, the new fonts, and the contained circular shape give the logo a flat look. While the hearts are out of sync with the rest of the image. Possibly because they are overlapping, or perhaps they're just stylistically different. I suggest that you try a star (or two stars representing a couple???) or another simplistic and flat looking image in place of the hearts." +87839,I have this image.I want to crop just triangle not its white background for logo im creating.How can i do it in illustrator or photoshop?[![enter image description here](https://i.stack.imgur.com/gLx3w.jpg)](https://i.stack.imgur.com/gLx3w.jpg),2017/04/01,"['https://graphicdesign.stackexchange.com/questions/87839', 'https://graphicdesign.stackexchange.com', 'https://graphicdesign.stackexchange.com/users/70543/']","If you want my opinion why your design doesn't work so well, I think it's because more of the contents lie outside the natural circle shape made by the original design - especially that bold ""GAYPRIL"" text. + +You can see it here if I overlay a circle on both designs. + +[![enter image description here](https://i.stack.imgur.com/r5wjD.png)](https://i.stack.imgur.com/r5wjD.png) + +I think this could be improved if you ensure most of the design elements are within within the bounds of the circle, basically to improve the composition. + +Something like this perhaps + +[![enter image description here](https://i.stack.imgur.com/1vei2.jpg)](https://i.stack.imgur.com/1vei2.jpg) + +Also you might want to rethink that slight wavy warp on the GAYPRIL text. Might be better if it was unwarped. Also the R and A are very similar - from a distance it might look like GAYPAIL. Perhaps consider changing the font.","*I’ve already been working on this answer in my spare time and I wouldn’t want to see the effort go to waste, although it’s not strictly on-topic, anymore. Nevertheless I’m posting it here in the hope that it might by useful, both for others and for the OP in the more general case. I’m adressing the first version of the Gaypril logo.* + +There are few hard and fast rules in design, if any, and to my knowledge none that hasn't been successfully broken by designers. So, if the question is “How to make my logo better?”, then I’d have to ask back: “Well, what do you want to achieve? What means do you want to employ?” Leading to a back and forth exchange that quickly starts to feel like working with a client. + +However, if the question is: “Here’s the model logo whose effect I tried to emulate. Here’s my own logo attempt, where, as far as I can see, I did everything like in the model. Why is it still not working?” That’s easier to answer, because I can point to the features of the Canada Road Trip logo and explain why these make the logo “work.” And I can explain how those features are in fact *not* present in the Gaypril logo. The Gaypril logo could employ very different means to achieve visual cohesion. + +**Nothing that I’m presenting here is in any way mandatory! I’m discussing the options realised in the Canada Road Trip logo that you took as your model. There are also numerous other options.** + +Because that’s what this is about: visual cohesion. Or in other words: composition. In design, you have to establish the rules by which your design works. I recently wrote in another context that design is about creating problems for yourself and then solving them. It’s in some ways like solving a puzzle, except that while solving you also invent the rules by which the puzzle has to be solved. That makes it actually harder! + +The impression of boredom doesn't generally come from a lack of “interesting” elements. Rather it stems more often than not from the fact that those element are put together in a manner that appears to the eye as arbitrary. Interest stems from the expectation of surprise, yes, but randomness isn't surprising. To take an extreme example: No two white noise patterns are exactly the same. And still nobody would look at them with any expectation to see an interesting placement of white or black pixels. If you want your work to be interesting you have to compose it in a way that the elements fit together meaningfully and provide a sense of unity in an interesting way. + +This is harder to do the more heterogeneous the elements are that you want to compose. This is why beginners are often advised to keep it simple. + +Please note that I’m not trying to discourage you! Or making the task seem exceptionally hard. On the contrary, I think you are on a good way and noticing that something’s not working is the first step towards improvement. The rest comes with practise and experience. + +I should also point out that I don’t expect that my analysis of the Canada Road Trip is what its designer consciously had in mind, at least not everything. Many decisions in design are made intuitively. I’ll come back to that at the end. + +Shape +----- + +[![](https://i.stack.imgur.com/M5l9O.png)](https://i.stack.imgur.com/M5l9O.png) + +This logo has a clear circular form. Note how the mountains at the top protude. This is, because we perceive pictorial elements like these as a unity: The top line of the mountains (without the sunrise) are perceived as continuing the line of the circle. But since we perceive the mountains as unity, our eyes average their height. If the mountains where placed more towards the centre of the circle, they would appear as too low. + +Note also how the “C” of “Canada” supports and continues the circle line. It, too, sticks out and has to, for the very same reason. The same is true, though to a lesser extent, for the letters “da”. In short, the form of the logo unambiguously evokes a circle and has little to counter that notion. The only element effectively going beyond the circular shape is the sunrise behind the mountains. But its lines carry much less visual emphasis, especially since the lines of the mountains are so much more dominant. And *because the logo is generally well composed* the slight disturbance of the circular shape appears as intentional and meaningful: It’s a well placed accent, so to say, the sunrise behind the logo itself. + +[![enter image description here](https://i.stack.imgur.com/MLD9A.png)](https://i.stack.imgur.com/MLD9A.png) + +Here the circle is fully supported only by the text at the bottom, which, in addition, is de-emphasized with a comparatively thin and wide-spaced font. The sun at the top has much more emphasis. Its vaguely star shaped at its upper outline (the rays) and the half circle of the sun doesn’t support the circle shape of the logo itself, but competes with it. In effect, the sun doesn’t just protude, it counters and escapes from the attempted circularity. The same, more importantly, goes for “Gaypril”: It clearly stands out as the most important visual feature. But not only does it not support the circle, and not only does it protude, it introduces a shape of its own: a parallelogram slightly warped to a wave form. + +Nothing of these are a “problem” per se. You *can* have a counter shape in rhythmical contrast to the main shape. You *can* have elements “escaping” from the structure you are trying to create. You are creating your own rules and you are breaking your own rules. + +> +> Breaking the rules is good. **But** before you can break the rules, you have to establish the rules. +> +> +> + +Here, the logo doesn’t successfully establish the circle. + +Grey Values and negative space +------------------------------ + +[![enter image description here](https://i.stack.imgur.com/ixGsB.png)](https://i.stack.imgur.com/ixGsB.png) + +Look at the grey values. (I hope “grey values” is the correct English word.) The average of black and white in the various elements is evenly distributed. If I added more blur, the logo would eventually become evenly grey. Only the bear stands out as a blacker area. As does, to a lesser extend, the mountain at the top, thus acting as a counter weight to the bear. + +White space between the elements is roughly evenly distributed. Meaning: White space is neutral and not intended as a dominant element of the composition. There are works where white space (better dubbed “negative space”, then) and its shape is just as much important as the foreground elements itself, for instance in traditional Japanese woodcut printing. This is not one of those works. + +[![enter image description here](https://i.stack.imgur.com/QSkws.png)](https://i.stack.imgur.com/QSkws.png) + +As you can see, all the weight is at the top, with “Gaypril” having the most weight by a large margin and the sun coming second. Note in particular how little weight the bottom text in a half circle has. This contributes largely to the logo not establishing its intended circle shape. + +I have a gut feeling that maybe you intuitively were aiming for this: A circle with the upper half being darker and the lower half lighter. If that’s the case, then it’s a good instinct. If the logo were clearer, were successful in establishing the circular shape, if it would give the overall impression of being thoroughly composed, then this could work very well. As it stands, there’s too much visual noise for this to take effect. + +Repeating Distances +------------------- + +[![enter image description here](https://i.stack.imgur.com/WEGRb.png)](https://i.stack.imgur.com/WEGRb.png) + +To some degree, this is an elaboration on white space, but with a different twist. The distance between various elements is *roughly* equal, in some cases very roughly. But that’s alright. The eye as little for comparison. If there were mostly straight lines, then more precision might have been necessary. + +Note how the designer tilted the bear in order to have its back and front paw in equal distance to the circle: + +[![enter image description here](https://i.stack.imgur.com/5LZCz.png)](https://i.stack.imgur.com/5LZCz.png) + +(The dotted line is the line through the circle’s centre, orthogonal to the baseline of “Canada Road Trip”.) Often you have to cheat a little. And you may! What matters is the naked eye of the spectator, not what you can measure with a ruler. It’s a judgement call with how much you can get away. Here, if you draw a line from the top of the mountain through the centre of circle, then the bear is *roughly* orthogonal to it. Maybe that contributes to the bear’s tilt looking good. Maybe it even establishes a secondary axis. I honestly don’t now. This is a matter of interpretation. + +[![enter image description here](https://i.stack.imgur.com/GC7qw.png)](https://i.stack.imgur.com/GC7qw.png) + +Here the various distances differ widely. Why am I measuring the radial distance? And not, for instance along the tilted vertical axis and perpendicular to it? Because of the comparison to the Canada logo, which works as a circle. Here it’s actually unclear, which leads to my second iteration over shape: + +Shape, the second +----------------- + +[![enter image description here](https://i.stack.imgur.com/RHeRb.png)](https://i.stack.imgur.com/RHeRb.png) + +The Gaypril logo hints at a rectangular shape inside the attempted circle. Again I have a gut feeling that this might have been what you wanted on an intuitive level. And, again, a decision like that could very well work, if it were actually both clear by itself and not countered by conflicting visual clues. + +Proportions +----------- + +[![enter image description here](https://i.stack.imgur.com/BJOX3.png)](https://i.stack.imgur.com/BJOX3.png) + +There’s a rhythm to the Canada logo: The heights measured a long the baseline of “Canada Road Trip” are *roughly* repeating. I have the golden ratio proportions overlayed in red and blue. Again, there are no straight lines, so a rough correspondence is more than enough to establish a sense of rhythm to the naked eye. + +The fact that it’s *roughly* the golden ratio matters less than the fact that it’s a repeating proportion. For instance, 1:2 or 1:3 would work just as well in terms of composition, though in a sense the golden ratio is probably more “neutral” in this context. + +> +> To my surprise, I learned from the internet that some people find the golden ratio dubious. There’s nothing magical about it, though: If you need a proportion that is smaller than 1:1 and larger than 1:2, yet is still distinguished enough from either to look intentional, then you cannot but end up at with what for all practical purposes is a “naked eye golden ratio”. +> +> +> For the most basic purposes the golden ratio is *roughly* 2:3. Like here where there are no straight lines providing a clear reference. Or, for instance, if you just want to divide a page into two parts. In such contexts, a more precise division isn’t discernible. Finer precisions like 1:1.618 become meaningful only when building up visual relations spanning multiple golden ratio divisions, since only then the golden ratio’s unique mathematical properties might come into play. The target audience might be relevant, though: If, for instance, you design a poster for an exhibition on Mies van der Rohe or for an auction of renaissance paintings or some such, then your target audience might be more sensitive. +> +> +> + +This proportion is also present on a larger scale: + +[![enter image description here](https://i.stack.imgur.com/SR6wb.png)](https://i.stack.imgur.com/SR6wb.png) + +Again, you don’t *have* to use repeating proportions. But in the Canada logo it’s one aspect that provides a sense of intentionality in its composition. + +Practising your Sense of Composition +------------------------------------ + +I mentioned that most designers probably make this kind of decision intuitively, often not consciously aware of it. But there is nothing mysterious about intuition. It comes with experience and it can be educated. + +One very good exercise is what you just did: Trying to recreate something that you like. As you probably know, that takes time, though, and quantity does matter somewhat. Another good way to educate your sense for composition is to *draw* works that you like. Here’s an example from my sketch book: + +[![enter image description here](https://i.stack.imgur.com/YSoVz.jpg)](https://i.stack.imgur.com/YSoVz.jpg) +[![enter image description here](https://i.stack.imgur.com/r3CNZ.jpg)](https://i.stack.imgur.com/r3CNZ.jpg) + +As you can see, I’m not really good at drawing, but it serves my purpose. I try to make a habit of drawing one work that I regard as masterful every day. Well, in reality it’s just every other day, or every third day, but I’m trying to be more disciplined. That drawing doesn’t have to be good. More importantly, the aim is not to *copy* the original. Nothing would be gained, if you just put tracing paper on the original. The goal is to *reconstruct* the work on your paper. It’s best to think of it as “thinking with your pencil”. It’s about discovering what visual relations matter for the composition. It’s also about committing options for composition to your subconsciousness." +87839,I have this image.I want to crop just triangle not its white background for logo im creating.How can i do it in illustrator or photoshop?[![enter image description here](https://i.stack.imgur.com/gLx3w.jpg)](https://i.stack.imgur.com/gLx3w.jpg),2017/04/01,"['https://graphicdesign.stackexchange.com/questions/87839', 'https://graphicdesign.stackexchange.com', 'https://graphicdesign.stackexchange.com/users/70543/']","*I’ve already been working on this answer in my spare time and I wouldn’t want to see the effort go to waste, although it’s not strictly on-topic, anymore. Nevertheless I’m posting it here in the hope that it might by useful, both for others and for the OP in the more general case. I’m adressing the first version of the Gaypril logo.* + +There are few hard and fast rules in design, if any, and to my knowledge none that hasn't been successfully broken by designers. So, if the question is “How to make my logo better?”, then I’d have to ask back: “Well, what do you want to achieve? What means do you want to employ?” Leading to a back and forth exchange that quickly starts to feel like working with a client. + +However, if the question is: “Here’s the model logo whose effect I tried to emulate. Here’s my own logo attempt, where, as far as I can see, I did everything like in the model. Why is it still not working?” That’s easier to answer, because I can point to the features of the Canada Road Trip logo and explain why these make the logo “work.” And I can explain how those features are in fact *not* present in the Gaypril logo. The Gaypril logo could employ very different means to achieve visual cohesion. + +**Nothing that I’m presenting here is in any way mandatory! I’m discussing the options realised in the Canada Road Trip logo that you took as your model. There are also numerous other options.** + +Because that’s what this is about: visual cohesion. Or in other words: composition. In design, you have to establish the rules by which your design works. I recently wrote in another context that design is about creating problems for yourself and then solving them. It’s in some ways like solving a puzzle, except that while solving you also invent the rules by which the puzzle has to be solved. That makes it actually harder! + +The impression of boredom doesn't generally come from a lack of “interesting” elements. Rather it stems more often than not from the fact that those element are put together in a manner that appears to the eye as arbitrary. Interest stems from the expectation of surprise, yes, but randomness isn't surprising. To take an extreme example: No two white noise patterns are exactly the same. And still nobody would look at them with any expectation to see an interesting placement of white or black pixels. If you want your work to be interesting you have to compose it in a way that the elements fit together meaningfully and provide a sense of unity in an interesting way. + +This is harder to do the more heterogeneous the elements are that you want to compose. This is why beginners are often advised to keep it simple. + +Please note that I’m not trying to discourage you! Or making the task seem exceptionally hard. On the contrary, I think you are on a good way and noticing that something’s not working is the first step towards improvement. The rest comes with practise and experience. + +I should also point out that I don’t expect that my analysis of the Canada Road Trip is what its designer consciously had in mind, at least not everything. Many decisions in design are made intuitively. I’ll come back to that at the end. + +Shape +----- + +[![](https://i.stack.imgur.com/M5l9O.png)](https://i.stack.imgur.com/M5l9O.png) + +This logo has a clear circular form. Note how the mountains at the top protude. This is, because we perceive pictorial elements like these as a unity: The top line of the mountains (without the sunrise) are perceived as continuing the line of the circle. But since we perceive the mountains as unity, our eyes average their height. If the mountains where placed more towards the centre of the circle, they would appear as too low. + +Note also how the “C” of “Canada” supports and continues the circle line. It, too, sticks out and has to, for the very same reason. The same is true, though to a lesser extent, for the letters “da”. In short, the form of the logo unambiguously evokes a circle and has little to counter that notion. The only element effectively going beyond the circular shape is the sunrise behind the mountains. But its lines carry much less visual emphasis, especially since the lines of the mountains are so much more dominant. And *because the logo is generally well composed* the slight disturbance of the circular shape appears as intentional and meaningful: It’s a well placed accent, so to say, the sunrise behind the logo itself. + +[![enter image description here](https://i.stack.imgur.com/MLD9A.png)](https://i.stack.imgur.com/MLD9A.png) + +Here the circle is fully supported only by the text at the bottom, which, in addition, is de-emphasized with a comparatively thin and wide-spaced font. The sun at the top has much more emphasis. Its vaguely star shaped at its upper outline (the rays) and the half circle of the sun doesn’t support the circle shape of the logo itself, but competes with it. In effect, the sun doesn’t just protude, it counters and escapes from the attempted circularity. The same, more importantly, goes for “Gaypril”: It clearly stands out as the most important visual feature. But not only does it not support the circle, and not only does it protude, it introduces a shape of its own: a parallelogram slightly warped to a wave form. + +Nothing of these are a “problem” per se. You *can* have a counter shape in rhythmical contrast to the main shape. You *can* have elements “escaping” from the structure you are trying to create. You are creating your own rules and you are breaking your own rules. + +> +> Breaking the rules is good. **But** before you can break the rules, you have to establish the rules. +> +> +> + +Here, the logo doesn’t successfully establish the circle. + +Grey Values and negative space +------------------------------ + +[![enter image description here](https://i.stack.imgur.com/ixGsB.png)](https://i.stack.imgur.com/ixGsB.png) + +Look at the grey values. (I hope “grey values” is the correct English word.) The average of black and white in the various elements is evenly distributed. If I added more blur, the logo would eventually become evenly grey. Only the bear stands out as a blacker area. As does, to a lesser extend, the mountain at the top, thus acting as a counter weight to the bear. + +White space between the elements is roughly evenly distributed. Meaning: White space is neutral and not intended as a dominant element of the composition. There are works where white space (better dubbed “negative space”, then) and its shape is just as much important as the foreground elements itself, for instance in traditional Japanese woodcut printing. This is not one of those works. + +[![enter image description here](https://i.stack.imgur.com/QSkws.png)](https://i.stack.imgur.com/QSkws.png) + +As you can see, all the weight is at the top, with “Gaypril” having the most weight by a large margin and the sun coming second. Note in particular how little weight the bottom text in a half circle has. This contributes largely to the logo not establishing its intended circle shape. + +I have a gut feeling that maybe you intuitively were aiming for this: A circle with the upper half being darker and the lower half lighter. If that’s the case, then it’s a good instinct. If the logo were clearer, were successful in establishing the circular shape, if it would give the overall impression of being thoroughly composed, then this could work very well. As it stands, there’s too much visual noise for this to take effect. + +Repeating Distances +------------------- + +[![enter image description here](https://i.stack.imgur.com/WEGRb.png)](https://i.stack.imgur.com/WEGRb.png) + +To some degree, this is an elaboration on white space, but with a different twist. The distance between various elements is *roughly* equal, in some cases very roughly. But that’s alright. The eye as little for comparison. If there were mostly straight lines, then more precision might have been necessary. + +Note how the designer tilted the bear in order to have its back and front paw in equal distance to the circle: + +[![enter image description here](https://i.stack.imgur.com/5LZCz.png)](https://i.stack.imgur.com/5LZCz.png) + +(The dotted line is the line through the circle’s centre, orthogonal to the baseline of “Canada Road Trip”.) Often you have to cheat a little. And you may! What matters is the naked eye of the spectator, not what you can measure with a ruler. It’s a judgement call with how much you can get away. Here, if you draw a line from the top of the mountain through the centre of circle, then the bear is *roughly* orthogonal to it. Maybe that contributes to the bear’s tilt looking good. Maybe it even establishes a secondary axis. I honestly don’t now. This is a matter of interpretation. + +[![enter image description here](https://i.stack.imgur.com/GC7qw.png)](https://i.stack.imgur.com/GC7qw.png) + +Here the various distances differ widely. Why am I measuring the radial distance? And not, for instance along the tilted vertical axis and perpendicular to it? Because of the comparison to the Canada logo, which works as a circle. Here it’s actually unclear, which leads to my second iteration over shape: + +Shape, the second +----------------- + +[![enter image description here](https://i.stack.imgur.com/RHeRb.png)](https://i.stack.imgur.com/RHeRb.png) + +The Gaypril logo hints at a rectangular shape inside the attempted circle. Again I have a gut feeling that this might have been what you wanted on an intuitive level. And, again, a decision like that could very well work, if it were actually both clear by itself and not countered by conflicting visual clues. + +Proportions +----------- + +[![enter image description here](https://i.stack.imgur.com/BJOX3.png)](https://i.stack.imgur.com/BJOX3.png) + +There’s a rhythm to the Canada logo: The heights measured a long the baseline of “Canada Road Trip” are *roughly* repeating. I have the golden ratio proportions overlayed in red and blue. Again, there are no straight lines, so a rough correspondence is more than enough to establish a sense of rhythm to the naked eye. + +The fact that it’s *roughly* the golden ratio matters less than the fact that it’s a repeating proportion. For instance, 1:2 or 1:3 would work just as well in terms of composition, though in a sense the golden ratio is probably more “neutral” in this context. + +> +> To my surprise, I learned from the internet that some people find the golden ratio dubious. There’s nothing magical about it, though: If you need a proportion that is smaller than 1:1 and larger than 1:2, yet is still distinguished enough from either to look intentional, then you cannot but end up at with what for all practical purposes is a “naked eye golden ratio”. +> +> +> For the most basic purposes the golden ratio is *roughly* 2:3. Like here where there are no straight lines providing a clear reference. Or, for instance, if you just want to divide a page into two parts. In such contexts, a more precise division isn’t discernible. Finer precisions like 1:1.618 become meaningful only when building up visual relations spanning multiple golden ratio divisions, since only then the golden ratio’s unique mathematical properties might come into play. The target audience might be relevant, though: If, for instance, you design a poster for an exhibition on Mies van der Rohe or for an auction of renaissance paintings or some such, then your target audience might be more sensitive. +> +> +> + +This proportion is also present on a larger scale: + +[![enter image description here](https://i.stack.imgur.com/SR6wb.png)](https://i.stack.imgur.com/SR6wb.png) + +Again, you don’t *have* to use repeating proportions. But in the Canada logo it’s one aspect that provides a sense of intentionality in its composition. + +Practising your Sense of Composition +------------------------------------ + +I mentioned that most designers probably make this kind of decision intuitively, often not consciously aware of it. But there is nothing mysterious about intuition. It comes with experience and it can be educated. + +One very good exercise is what you just did: Trying to recreate something that you like. As you probably know, that takes time, though, and quantity does matter somewhat. Another good way to educate your sense for composition is to *draw* works that you like. Here’s an example from my sketch book: + +[![enter image description here](https://i.stack.imgur.com/YSoVz.jpg)](https://i.stack.imgur.com/YSoVz.jpg) +[![enter image description here](https://i.stack.imgur.com/r3CNZ.jpg)](https://i.stack.imgur.com/r3CNZ.jpg) + +As you can see, I’m not really good at drawing, but it serves my purpose. I try to make a habit of drawing one work that I regard as masterful every day. Well, in reality it’s just every other day, or every third day, but I’m trying to be more disciplined. That drawing doesn’t have to be good. More importantly, the aim is not to *copy* the original. Nothing would be gained, if you just put tracing paper on the original. The goal is to *reconstruct* the work on your paper. It’s best to think of it as “thinking with your pencil”. It’s about discovering what visual relations matter for the composition. It’s also about committing options for composition to your subconsciousness.","You have addressed the biggest issue in your design with the changes to your fonts, and it looks so much better. Regarding your further question about the images, the hearts aren't completely working with the feel of your design. The sun, the new fonts, and the contained circular shape give the logo a flat look. While the hearts are out of sync with the rest of the image. Possibly because they are overlapping, or perhaps they're just stylistically different. I suggest that you try a star (or two stars representing a couple???) or another simplistic and flat looking image in place of the hearts." +27553515,"I am currently working on a project which will use Entity Framework 6.1.1 and an Oracle 11g database backend. I will be accessing tables across multiple schemas some of which have foreign key relationships across schemas as well (look-up tables, enterprise data, etc...). + +Traditionally we have used synonyms as a means of exposing these cross-schema tables to a particular login. My question is... how can I map these synonyms in EF6 using code first mapping? I have no problems mapping to tables directly within a single schema, but this of course won't be sufficient since my tables cross several schemas. So far my code first mappings do not recognize synonyms. + +Has anyone been able to do code-first mappings to Oracle synonyms?",2014/12/18,"['https://Stackoverflow.com/questions/27553515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2701219/']","To have each column be a different color, all you have to do is set the `colorByPoint` property to `true`. + +Reference: + +* + +Alternatively you can make each column a separate series, which gives you additional levels of control. + +*OTOH, in the majority of cases, having each column a separate color serves no purpose except to clutter and confuse the data, and make the user work harder cognitively to interpret the chart.* + +If you want to highlight a single column for a particular reason, you can do that by adding the fillColor property to the data array: + +Something like: + +``` +data:[2,4,5,{y:9,fillColor:'rgba(204,0,0,.75)',note:'Wow, look at this one'},4,5,6] + +```","I finally found a way to show more than 1 color for each column: + +``` + var charts1 = []; + var $containers1 = $('#container1'); + var datasets1 = [{ + name: 'Dalias', + data: [29] + }, + { + name: 'Lilas', + data: [1] + }, + { + name: 'Tulipanes', + data: [15] + }]; + $('#container1').highcharts({ + chart: { + type: 'column', + backgroundColor: 'transparent' + }, + title: { + text: 'Montos pedidos por división' + }, + tooltip: { + pointFormat: '{series.name} :{point.y}', + useHTML: true + }, + plotOptions: { + column: { + pointPadding: 0.2, + borderWidth: 0 + }, + series : { + cursor: 'pointer', + point: { + events: { + /*click: function() { + verDetalle(""Especialidades,""+ this.series.name); + }*/ + } + } + } + }, + credits:{ + enabled: false + }, + yAxis: { + min: 0, + title: { + text: '' + } + }, + xAxis: { + categories: ['División'] + }, + series: datasets1 + }); + +```" +32201,"I am making a simple voltage regulator. The whole idea is to just use ADC to read voltage on output side and based on the result, adjust PWM power. I am using PWM on physical pin 5. That's the same pin as the one connected to Arduino pin 10 on this image below: + +![image description](https://i.stack.imgur.com/ggIkw.png) + +This means that if I try to flash the program, ATTiny will start to put PWM power into my Arduino. I don't want that to happen. How can I flash the program safely? Can I do something to prevent it from starting?",2016/12/12,"['https://arduino.stackexchange.com/questions/32201', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/2955/']","> +> This means that if I try to flash the program, ATTiny will start to put PWM power into my Arduino. I don't want that to happen. +> +> +> + +Why do you think that is a problem? The ""PWM power"" cannot be any higher than the supply voltage, and that is 5V. The Arduino has no problem with you providing a 5V PWM signal to an input pin. + +The only time it could be a problem is if the pin you are sending the PWM to is set to an output, in which case you could risk overloading the pin. To get around that you just need to insert a small resistor between the ATTiny's pin and the Arduino's pin. 330Ω or so should do it. Just enough to limit the current to a safe value (< 20mA) but small enough that it won't interfere with the programming communication. + +A well design schematic for an Arduino ICSP programmer would have had these resistors in all the data communication lines anyway.","That isn't a problem but if you **really** want to prevent ATtiny generating the PWM signal right after flashing the firmware, then you might add a jumper to some free µC input and put the while loop at the beginning of the program which reads that input and waits until you remove the jumper. For example, you could enable internall pull-up on some free input and put the jumper from that pin to GND. Then in the code you can just wait for the input to become high and then proceed with the rest of the code. Then you can just insert the jumper, flash the firmware, remove the connections between ATtiny and Arduino and then remove the jumper." +32201,"I am making a simple voltage regulator. The whole idea is to just use ADC to read voltage on output side and based on the result, adjust PWM power. I am using PWM on physical pin 5. That's the same pin as the one connected to Arduino pin 10 on this image below: + +![image description](https://i.stack.imgur.com/ggIkw.png) + +This means that if I try to flash the program, ATTiny will start to put PWM power into my Arduino. I don't want that to happen. How can I flash the program safely? Can I do something to prevent it from starting?",2016/12/12,"['https://arduino.stackexchange.com/questions/32201', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/2955/']","> +> This means that if I try to flash the program, ATTiny will start to put PWM power into my Arduino. I don't want that to happen. +> +> +> + +Why do you think that is a problem? The ""PWM power"" cannot be any higher than the supply voltage, and that is 5V. The Arduino has no problem with you providing a 5V PWM signal to an input pin. + +The only time it could be a problem is if the pin you are sending the PWM to is set to an output, in which case you could risk overloading the pin. To get around that you just need to insert a small resistor between the ATTiny's pin and the Arduino's pin. 330Ω or so should do it. Just enough to limit the current to a safe value (< 20mA) but small enough that it won't interfere with the programming communication. + +A well design schematic for an Arduino ICSP programmer would have had these resistors in all the data communication lines anyway.","The Arduino-as-ISP sketch will turn all the OUTPUT pins, connected to the ATTiny, [back to **INPUT**](https://github.com/arduino/Arduino/blob/2bfe164b9a5835e8cb6e194b928538a9093be333/build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino#L433-L439). That way nothing bad can happen, when the ATTiny drives those pins HIGH of LOW." +5213670,"I have three files; index.php, searchbar.php and search.php + +now when i have search.php show its results on its own page its fine but when i try to include the search page in index.php i get nothing. + +so i include the searchbox.php in index.php so i have a search bar, i then search for something and include the search.php page by using the $\_GET['p'] on the index.php but the search always come up blank, if i just leave search.php as its own page and dont try to include it then i get my results but id like for them to be included on the page they were searched from. + +index.php + +``` +
'; + +} + +} else { + +@include ('news.php'); + +} + +?> + +``` + +searchbox.php + +``` +
+ + + +
+ +``` + +search.php + +``` +""; +echo "" Item Name Desc.""; +// keeps getting the next row until there are no more to get + +while($row = mysql_fetch_array( $query )) { + + // Print out the contents of each row into a table + echo """"; + echo $row['image']; + echo """"; + echo $row['itemname']; + echo """"; + echo $row['desc']; + echo """"; +} + +echo """";; +} +if (mysql_num_rows($query) == 0) +{ + echo 'No Results'; +} +?> + +```",2011/03/06,"['https://Stackoverflow.com/questions/5213670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/647328/']","I think that I would probably prefer an approach like + +``` +In[1]:= Physics[find_, have_:{}] := Solve[ + {d == vf*t - (a*t^2)/2 (* , etc *)} /. have, find] + +In[2]:= Physics[d] +Out[2]= {{d -> 1/2 (-a t^2 + 2 t vf)}} + +In[2]:= Physics[d, {t -> 9.7, vf -> -104.98, a -> -9.8}] +Out[2]= {{d -> -557.265}} + +``` + +Where the `have` variables are given as a list of replacement rules. + +As an aside, in these types of physics problems, a nice thing to do is define your physical constants like + +``` +N[g] = -9.8; + +``` + +which produces a `NValues` for `g`. Then + +``` +N[tf] = 9.7;N[vf] = -104.98; +Physics[d, {t -> tf, vf -> vf, a -> g}] +%//N + +``` + +produces + +``` +{{d->1/2 (-g tf^2+2 tf vf)}} +{{d->-557.265}} + +```","You are at least approaching this problem reasonably. I see a fine general purpose function and I see you're getting results, which is what matters primarily. There is no 'correct' solution, since there might be a large range of acceptable solutions. In some scenario's some solutions may be preferred over others, for instance because of performance, while that might be the other way around in other scenarios. + +The only slight problem I have with your example is the dubious parametername 'have'. +Why do you think this would be a wrong approach?" +5213670,"I have three files; index.php, searchbar.php and search.php + +now when i have search.php show its results on its own page its fine but when i try to include the search page in index.php i get nothing. + +so i include the searchbox.php in index.php so i have a search bar, i then search for something and include the search.php page by using the $\_GET['p'] on the index.php but the search always come up blank, if i just leave search.php as its own page and dont try to include it then i get my results but id like for them to be included on the page they were searched from. + +index.php + +``` +
'; + +} + +} else { + +@include ('news.php'); + +} + +?> + +``` + +searchbox.php + +``` +
+ + +
+
+ +``` + +search.php + +``` +""; +echo "" Item Name Desc.""; +// keeps getting the next row until there are no more to get + +while($row = mysql_fetch_array( $query )) { + + // Print out the contents of each row into a table + echo """"; + echo $row['image']; + echo """"; + echo $row['itemname']; + echo """"; + echo $row['desc']; + echo """"; +} + +echo """";; +} +if (mysql_num_rows($query) == 0) +{ + echo 'No Results'; +} +?> + +```",2011/03/06,"['https://Stackoverflow.com/questions/5213670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/647328/']","Let me show some advanges of Simon's approach: + +![enter image description here](https://i.stack.imgur.com/pyBS7.png)","You are at least approaching this problem reasonably. I see a fine general purpose function and I see you're getting results, which is what matters primarily. There is no 'correct' solution, since there might be a large range of acceptable solutions. In some scenario's some solutions may be preferred over others, for instance because of performance, while that might be the other way around in other scenarios. + +The only slight problem I have with your example is the dubious parametername 'have'. +Why do you think this would be a wrong approach?" +5213670,"I have three files; index.php, searchbar.php and search.php + +now when i have search.php show its results on its own page its fine but when i try to include the search page in index.php i get nothing. + +so i include the searchbox.php in index.php so i have a search bar, i then search for something and include the search.php page by using the $\_GET['p'] on the index.php but the search always come up blank, if i just leave search.php as its own page and dont try to include it then i get my results but id like for them to be included on the page they were searched from. + +index.php + +``` +
'; + +} + +} else { + +@include ('news.php'); + +} + +?> + +``` + +searchbox.php + +``` +
+ + +
+
+ +``` + +search.php + +``` +""; +echo "" Item Name Desc.""; +// keeps getting the next row until there are no more to get + +while($row = mysql_fetch_array( $query )) { + + // Print out the contents of each row into a table + echo """"; + echo $row['image']; + echo """"; + echo $row['itemname']; + echo """"; + echo $row['desc']; + echo """"; +} + +echo """";; +} +if (mysql_num_rows($query) == 0) +{ + echo 'No Results'; +} +?> + +```",2011/03/06,"['https://Stackoverflow.com/questions/5213670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/647328/']","I think that I would probably prefer an approach like + +``` +In[1]:= Physics[find_, have_:{}] := Solve[ + {d == vf*t - (a*t^2)/2 (* , etc *)} /. have, find] + +In[2]:= Physics[d] +Out[2]= {{d -> 1/2 (-a t^2 + 2 t vf)}} + +In[2]:= Physics[d, {t -> 9.7, vf -> -104.98, a -> -9.8}] +Out[2]= {{d -> -557.265}} + +``` + +Where the `have` variables are given as a list of replacement rules. + +As an aside, in these types of physics problems, a nice thing to do is define your physical constants like + +``` +N[g] = -9.8; + +``` + +which produces a `NValues` for `g`. Then + +``` +N[tf] = 9.7;N[vf] = -104.98; +Physics[d, {t -> tf, vf -> vf, a -> g}] +%//N + +``` + +produces + +``` +{{d->1/2 (-g tf^2+2 tf vf)}} +{{d->-557.265}} + +```","Let me show some advanges of Simon's approach: + +![enter image description here](https://i.stack.imgur.com/pyBS7.png)" +37163656,"You have a big list and the goal is to retrieve this new list below + +Today: + +``` +number color brand size tiresize +----------------------------------------- +1 blue d 5 6 +2 blue d 5 6 +3 red b 3 3 +4 red b 3 3 +etc.... + +``` + +Goal: + +``` +number color brand size tiresize +----------------------------------------- + blue d 5 6 + red b 3 3 + +``` + +The goal is to retrieve a list that is distincted and you remove the ""number"". + +THis sample is a smal one and in reality the list has about 26 datamember. + +I was thinking about distinct() but it takes account to all datamember and I dont want to take account to the column ""number"" + +WHen you retrieve the new list, the request is to use the same class before with the distincted list. + +``` +public Car +{ + public int number + public string color + public string brand + public string size + public string tiresize +} + +``` + +Thank you!",2016/05/11,"['https://Stackoverflow.com/questions/37163656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/484390/']","I think you can use [`groupby`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html) with [`transform`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html): + +``` +import pandas as pd +import numpy as np + +df = pd.DataFrame([[1,1,3], + [1,1,9], + [1,1,np.nan], + [2,2,8], + [2,1,4], + [2,2,np.nan], + [2,2,5]] + , columns=list('ABC')) +print df + A B C +0 1 1 3.0 +1 1 1 9.0 +2 1 1 NaN +3 2 2 8.0 +4 2 1 4.0 +5 2 2 NaN +6 2 2 5.0 + +df['C'] = df.groupby(['A', 'B'])['C'].transform(lambda x: x.fillna( x.mean() )) +print df + A B C +0 1 1 3.0 +1 1 1 9.0 +2 1 1 6.0 +3 2 2 8.0 +4 2 1 4.0 +5 2 2 6.5 +6 2 2 5.0 + +```","``` +[df[i].fillna(df[i].mean(),inplace=True) for i in df.columns ] + +``` + +This fills then NAN from column C with 5.8 which is the mean of columns 'C' + +``` +Output + print df + A B C + 0 1 1 3.0 + 1 1 1 9.0 + 2 1 1 5.8 + 3 2 2 8.0 + 4 2 1 4.0 + 5 2 2 5.8 + 6 2 2 5.0 + +```" +39326512,"I have the following two calculation using Math.round(...): + +``` +double x = 0.57145732; +x = x * 100; +x = Math.round(x * 10); +x = x / 10; + +``` + +If I now print the value of x it will show me: 57.1. + +``` +double x = 0.57145732; +x = (Math.round((x * 100) * 10)) / 10; +// x = (Math.round(x * 1000)) / 10; //Also gives me 57.0. + +``` + +If I now print the value of x it will show me: 57.0. + +Why is there this difference in the outcome?",2016/09/05,"['https://Stackoverflow.com/questions/39326512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587261/']","The `Math.round()` method returns an **integer** (of type `long` - as pointed out by [Ole V.V](https://stackoverflow.com/users/5772882/ole-v-v)). It's usually thought to return a `float` or `double` which gives rise to confusions as these. + +In the second calculation, + +``` +Math.round((x * 100) * 10) + +``` + +returns `571`. Now, this value and `10` both are integers (571 is long, 10 is int). So when the calculation takes the form + +``` +x = 571 / 10 + +``` + +where x is double, `571/10` returns `57` instead of `57.1` since it is `int`. Then, `57` is converted to double and it becomes `57.0` + +If you do + +``` +x = (double)Math.round((x * 100) * 10) / 10.0; + +``` + +its value becomes `57.1`. + +--- + +**Edit**: There are two versions of the `Math.round()` function. The one you used accepts a double (since x is double) and returns `long`. In your case, **implicit type casting** spares you the trouble of considering the precise little details.","This because Math.round() returns an int. If you do this step-by-step (as in the first example), you assign the result of Math.round() to a float value. The following calculation uses then a float division. + +In the second example, you let the JVM decide which types to use (and it uses an integer division as the intermediate step). This is why the precision gets lost." +39326512,"I have the following two calculation using Math.round(...): + +``` +double x = 0.57145732; +x = x * 100; +x = Math.round(x * 10); +x = x / 10; + +``` + +If I now print the value of x it will show me: 57.1. + +``` +double x = 0.57145732; +x = (Math.round((x * 100) * 10)) / 10; +// x = (Math.round(x * 1000)) / 10; //Also gives me 57.0. + +``` + +If I now print the value of x it will show me: 57.0. + +Why is there this difference in the outcome?",2016/09/05,"['https://Stackoverflow.com/questions/39326512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587261/']","The reason of the difference is that in the second formula you're making a division of two integer. in order to have the same result you have to add a cast to double: + +``` +double x = 0.57145732; +x = (double)(Math.round((x * 100) * 10)) / 10; + +```","This because Math.round() returns an int. If you do this step-by-step (as in the first example), you assign the result of Math.round() to a float value. The following calculation uses then a float division. + +In the second example, you let the JVM decide which types to use (and it uses an integer division as the intermediate step). This is why the precision gets lost." +39326512,"I have the following two calculation using Math.round(...): + +``` +double x = 0.57145732; +x = x * 100; +x = Math.round(x * 10); +x = x / 10; + +``` + +If I now print the value of x it will show me: 57.1. + +``` +double x = 0.57145732; +x = (Math.round((x * 100) * 10)) / 10; +// x = (Math.round(x * 1000)) / 10; //Also gives me 57.0. + +``` + +If I now print the value of x it will show me: 57.0. + +Why is there this difference in the outcome?",2016/09/05,"['https://Stackoverflow.com/questions/39326512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587261/']","The difference is between + +``` +x = Math.round(571.45732) / 10; + +``` + +and + +``` +x = Math.round(571.45732); +x = x / 10; + +``` + +Since `round(double)` returns a long, in the first case you divide a long by an int, giving the long 57. Converting back to double leads to 57.0. The second case is equivalent to + +``` +x = ((double)Math.round(571.45732)) / 10; + +``` + +where a double is divided by an int, resulting in 57.1.","This because Math.round() returns an int. If you do this step-by-step (as in the first example), you assign the result of Math.round() to a float value. The following calculation uses then a float division. + +In the second example, you let the JVM decide which types to use (and it uses an integer division as the intermediate step). This is why the precision gets lost." +39326512,"I have the following two calculation using Math.round(...): + +``` +double x = 0.57145732; +x = x * 100; +x = Math.round(x * 10); +x = x / 10; + +``` + +If I now print the value of x it will show me: 57.1. + +``` +double x = 0.57145732; +x = (Math.round((x * 100) * 10)) / 10; +// x = (Math.round(x * 1000)) / 10; //Also gives me 57.0. + +``` + +If I now print the value of x it will show me: 57.0. + +Why is there this difference in the outcome?",2016/09/05,"['https://Stackoverflow.com/questions/39326512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587261/']","The `Math.round()` method returns an **integer** (of type `long` - as pointed out by [Ole V.V](https://stackoverflow.com/users/5772882/ole-v-v)). It's usually thought to return a `float` or `double` which gives rise to confusions as these. + +In the second calculation, + +``` +Math.round((x * 100) * 10) + +``` + +returns `571`. Now, this value and `10` both are integers (571 is long, 10 is int). So when the calculation takes the form + +``` +x = 571 / 10 + +``` + +where x is double, `571/10` returns `57` instead of `57.1` since it is `int`. Then, `57` is converted to double and it becomes `57.0` + +If you do + +``` +x = (double)Math.round((x * 100) * 10) / 10.0; + +``` + +its value becomes `57.1`. + +--- + +**Edit**: There are two versions of the `Math.round()` function. The one you used accepts a double (since x is double) and returns `long`. In your case, **implicit type casting** spares you the trouble of considering the precise little details.","The reason of the difference is that in the second formula you're making a division of two integer. in order to have the same result you have to add a cast to double: + +``` +double x = 0.57145732; +x = (double)(Math.round((x * 100) * 10)) / 10; + +```" +39326512,"I have the following two calculation using Math.round(...): + +``` +double x = 0.57145732; +x = x * 100; +x = Math.round(x * 10); +x = x / 10; + +``` + +If I now print the value of x it will show me: 57.1. + +``` +double x = 0.57145732; +x = (Math.round((x * 100) * 10)) / 10; +// x = (Math.round(x * 1000)) / 10; //Also gives me 57.0. + +``` + +If I now print the value of x it will show me: 57.0. + +Why is there this difference in the outcome?",2016/09/05,"['https://Stackoverflow.com/questions/39326512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587261/']","The `Math.round()` method returns an **integer** (of type `long` - as pointed out by [Ole V.V](https://stackoverflow.com/users/5772882/ole-v-v)). It's usually thought to return a `float` or `double` which gives rise to confusions as these. + +In the second calculation, + +``` +Math.round((x * 100) * 10) + +``` + +returns `571`. Now, this value and `10` both are integers (571 is long, 10 is int). So when the calculation takes the form + +``` +x = 571 / 10 + +``` + +where x is double, `571/10` returns `57` instead of `57.1` since it is `int`. Then, `57` is converted to double and it becomes `57.0` + +If you do + +``` +x = (double)Math.round((x * 100) * 10) / 10.0; + +``` + +its value becomes `57.1`. + +--- + +**Edit**: There are two versions of the `Math.round()` function. The one you used accepts a double (since x is double) and returns `long`. In your case, **implicit type casting** spares you the trouble of considering the precise little details.","The difference is between + +``` +x = Math.round(571.45732) / 10; + +``` + +and + +``` +x = Math.round(571.45732); +x = x / 10; + +``` + +Since `round(double)` returns a long, in the first case you divide a long by an int, giving the long 57. Converting back to double leads to 57.0. The second case is equivalent to + +``` +x = ((double)Math.round(571.45732)) / 10; + +``` + +where a double is divided by an int, resulting in 57.1." +39326512,"I have the following two calculation using Math.round(...): + +``` +double x = 0.57145732; +x = x * 100; +x = Math.round(x * 10); +x = x / 10; + +``` + +If I now print the value of x it will show me: 57.1. + +``` +double x = 0.57145732; +x = (Math.round((x * 100) * 10)) / 10; +// x = (Math.round(x * 1000)) / 10; //Also gives me 57.0. + +``` + +If I now print the value of x it will show me: 57.0. + +Why is there this difference in the outcome?",2016/09/05,"['https://Stackoverflow.com/questions/39326512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587261/']","The reason of the difference is that in the second formula you're making a division of two integer. in order to have the same result you have to add a cast to double: + +``` +double x = 0.57145732; +x = (double)(Math.round((x * 100) * 10)) / 10; + +```","The difference is between + +``` +x = Math.round(571.45732) / 10; + +``` + +and + +``` +x = Math.round(571.45732); +x = x / 10; + +``` + +Since `round(double)` returns a long, in the first case you divide a long by an int, giving the long 57. Converting back to double leads to 57.0. The second case is equivalent to + +``` +x = ((double)Math.round(571.45732)) / 10; + +``` + +where a double is divided by an int, resulting in 57.1." +66111346,"I have an observable that has objects coming into it. I want to get a property from each object that matches a filter and create a single comma separate string over all the emissions that has the single property I want. How can I accomplish this? + +What I've tried: + +``` +data.pipe( + map(item => item.map(d => d.source === ""SomeSource"").join("","") +)) + +``` + +> +> Data is of the following type: Observable +> +> +> + +> +> Data = [{id:2,name:'MyName1',sourc:'SomeSource1'},{id:2,name:'MyName2',sourc:'SomeSource2'},{id:3,name:'MyName3',sourc:'SomeSource3'}] +> +> +> + +However, this results in an observable string, but I just want a string in this format: `MyName1,MyName2,MyName3`.",2021/02/09,"['https://Stackoverflow.com/questions/66111346', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1991118/']","Consider two points, `a` and `b`. + +```py +a = [1,2] +b = [3,4] + +``` + +When we zip them we get: + +```py +print(list(zip(a, b))) # [[1,3], [2,4]] + +``` + +We can see that the first element of each are paired together, and similarly for the second element of each. This is just how zip works; I suspect this makes sense for you. If those are (x,y) points, then we've just grouped the x's and y's together. + +Now; consider the signature of `plt.plot(x, y, ...)`. It expects the first argument to be all the x's, and the second argument to be all the y's. Well, the zip just grouped those together for us! We can use the `*` operator to spread those over the first two arguments. Notice that these are equivalent operations: + +```py +p = list(zip(a, b)) +plt.plot(*p) +plt.plot(p[0], p[1]) + +``` + +Side note: to expand to more points we just add the extra points into the zip: + +```py +a = [1, 2] +b = [3, 4] +c = [5, 6] +print(list(zip(a, b, c))) # [[1, 3, 5], [2, 4, 6]] +plt.plot(*zip(a, b, c)) # plots the 3 points + +```","`*` inside a function call converts a list (or other iterable) into a `*args` kind of argument. + +`zip` with several lists iterates through them pairing up elements: + +``` +In [1]: list(zip([1,2,3],[4,5,6])) +Out[1]: [(1, 4), (2, 5), (3, 6)] + +``` + +If we define a list: + +``` +In [2]: alist = [[1,2,3],[4,5,6]] +In [3]: list(zip(alist)) +Out[3]: [([1, 2, 3],), ([4, 5, 6],)] + +``` + +That `zip` didn't do much. But if we star it: + +``` +In [4]: list(zip(*alist)) +Out[4]: [(1, 4), (2, 5), (3, 6)] + +``` + +Check the `zip` docs - see the `*args`: + +``` +In [5]: zip? +Init signature: zip(self, /, *args, **kwargs) +Docstring: +zip(*iterables) --> A zip object yielding tuples until an input is exhausted. + + >>> list(zip('abcdefg', range(3), range(4))) + [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)] + +The zip object yields n-length tuples, where n is the number of iterables +passed as positional arguments to zip(). The i-th element in every tuple +comes from the i-th iterable argument to zip(). This continues until the +shortest argument is exhausted. +Type: type +Subclasses: + +``` + +`*` could also be used with a function like `def foo(arg1, arg2, arg3):...` + +In `plt.plot(*zip(X[j], X[i]), color='black')`, `plot` has signature like `plot(x, y, kwargs)`. I don't think this is any different from + +``` +plt.plot(X[j], X[i], color='black') + +``` + +but I'd have to actually test some code. + +edit +---- + +``` +def foo(x,y): + print(x,y) + +In [11]: X = np.arange(10).reshape(5,2) +In [12]: foo(X[1],X[0]) +[2 3] [0 1] +In [13]: foo(*zip(X[1],X[0])) +(2, 0) (3, 1) + +``` + +`list(*zip(...))` is a list version of a matrix transpose." +37214,"Is there any formal notation for dealing with lists, rather than sets? + +e.g. if I have a set $X=\{x\_1,\dots,x\_n\}$ and I want to add a new item to the set, say $x\_{n+1}$, I can say ""Let $X = X \cup \{x\_{n+1}\}$"" and it is clearly understood that I want to add $x\_{n+1}$ to my set. + +However, if $X$ is not a set but rather a list, or tuple (i.e. the elements are ordered and duplicates are allowed), is there any way of indicating that I am adding an element to the end of the list? + +e.g. given $X=(x\_1,\dots,x\_n)$, how do I say add an element to $X$ such that $X=(x\_1,\dots,x\_n,x\_{n+1})$? i.e. how do I formally denote appending an element to $X$?",2011/05/05,"['https://math.stackexchange.com/questions/37214', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13/']","I don't think there is any standard notation. + +One alternative would be to not use $(a,b)$ for ordered pairs but $a \times b$, which is the notation suggested by category theory. The $\times$ allows you to sweep lots of assocativity isomorphisms under the rug: it looks perfectly natural to write $(a \times b) \times c = a \times (b \times c) = a \times b \times c$, but not $((a,b),c) = (a,(b,c)) = (a,b,c)$. + +Then if you have an $n$-tuple $x$ in $X^n$, you can write $x \times a$ for the $(n+1)$-tuple in $X^{n+1}$ obtained by appending $a$.","In addition to the answers mentioned above, I would like to stress that any list can be expressed as a set. + +Formally, we can define a list to be a function, where the domain is a subset of the natural numbers. We can then express the function as a set of ordered pairs $(x,y)$, where $x$ is the input and $y$ is the output of the function. + +Using this approach has the upshot that you retain *all* of the neat set notation and the reader will be familiar with the notation used in your work. On the other hand, the notation is a little (but not overwhelmingly) clunky. + +As an example, if we have a list $$ of real numbers, this corresponds to a function $$f:\{1,...,n\}\rightarrow\mathbb{R},$$ where $f(1) = y\_{1}$, etc. We could then represent this list as the set $$Y =\{\hspace{3pt}(x,f(x)):x\in \{1,...,n\} \hspace{3pt}\}.$$ + +Consequently, to append an element to $Y$, we could consider $$Y\cup \{(n+1,y\_{n+1})\}$$ + +To remove the clutter from this approach, we can then slightly abuse notation by defining + +$$S\cup \{y\_{n+1}\} = S\cup \{(n+1,y\_{n+1})\}.$$" +37214,"Is there any formal notation for dealing with lists, rather than sets? + +e.g. if I have a set $X=\{x\_1,\dots,x\_n\}$ and I want to add a new item to the set, say $x\_{n+1}$, I can say ""Let $X = X \cup \{x\_{n+1}\}$"" and it is clearly understood that I want to add $x\_{n+1}$ to my set. + +However, if $X$ is not a set but rather a list, or tuple (i.e. the elements are ordered and duplicates are allowed), is there any way of indicating that I am adding an element to the end of the list? + +e.g. given $X=(x\_1,\dots,x\_n)$, how do I say add an element to $X$ such that $X=(x\_1,\dots,x\_n,x\_{n+1})$? i.e. how do I formally denote appending an element to $X$?",2011/05/05,"['https://math.stackexchange.com/questions/37214', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13/']","What you call a list is formally known as sequence. There was a question [which symbol is for sequence concatenation](https://math.stackexchange.com/questions/298648/is-there-a-common-symbol-for-concatenating-two-finite-sequences). Unfortunately there is no accepted answer. Symbols `⋅`, `⌒` (commentator actually used u2322, ""frown"" symbol but it's resisting my attempt to copy it) and `∥` are mentioned in comments. + +According the [Wikipedia article](http://en.wikipedia.org/wiki/Concatenation_%28mathematics%29) `∥` is an operator for concatenation of numbers (doesn't specify which set of numbers, probably ℕ) but doesn't say much about sequences. The same symbol is in my opinion more commonly used for parallelism so it may confuse the reader. + +I haven't seen `⌒`symbol before but commentators agree about it.","In addition to the answers mentioned above, I would like to stress that any list can be expressed as a set. + +Formally, we can define a list to be a function, where the domain is a subset of the natural numbers. We can then express the function as a set of ordered pairs $(x,y)$, where $x$ is the input and $y$ is the output of the function. + +Using this approach has the upshot that you retain *all* of the neat set notation and the reader will be familiar with the notation used in your work. On the other hand, the notation is a little (but not overwhelmingly) clunky. + +As an example, if we have a list $$ of real numbers, this corresponds to a function $$f:\{1,...,n\}\rightarrow\mathbb{R},$$ where $f(1) = y\_{1}$, etc. We could then represent this list as the set $$Y =\{\hspace{3pt}(x,f(x)):x\in \{1,...,n\} \hspace{3pt}\}.$$ + +Consequently, to append an element to $Y$, we could consider $$Y\cup \{(n+1,y\_{n+1})\}$$ + +To remove the clutter from this approach, we can then slightly abuse notation by defining + +$$S\cup \{y\_{n+1}\} = S\cup \{(n+1,y\_{n+1})\}.$$" +24750593,"I try to use `panoramaGL` framework and try to add it to my static library. So I've imported it to the project, add `CoreGraphics` framework but have an issue `Unknown type name 'CGFloat'` in PLStructs.h. When I Cmd+click on the `CGFloat` in Xcode - I go to the `CGBase.h` in `CoreGraphics` framework. Try to clean the project and replace the frameworks - the result is the same. Waiting for your help.",2014/07/15,"['https://Stackoverflow.com/questions/24750593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2042311/']","The solution is simple: + +``` +#import + +```","The same problem came for me in Cocos2D. + +The solution is + +1. Go to build settings. In **Architectures** field you might have ""Standard architectures (armv7, armv7s, arm64). +2. The main cause for the problem is arm64. So the best way is to use ""**armv7**"" in the field. +3. We keep the standard architecture as is n ""**valid architectures**"" + +Hope it helps." +24750593,"I try to use `panoramaGL` framework and try to add it to my static library. So I've imported it to the project, add `CoreGraphics` framework but have an issue `Unknown type name 'CGFloat'` in PLStructs.h. When I Cmd+click on the `CGFloat` in Xcode - I go to the `CGBase.h` in `CoreGraphics` framework. Try to clean the project and replace the frameworks - the result is the same. Waiting for your help.",2014/07/15,"['https://Stackoverflow.com/questions/24750593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2042311/']","The solution is simple: + +``` +#import + +```","You actually don't need to import the full `UIKit`. This is enough: + +``` +#import + +```" +24750593,"I try to use `panoramaGL` framework and try to add it to my static library. So I've imported it to the project, add `CoreGraphics` framework but have an issue `Unknown type name 'CGFloat'` in PLStructs.h. When I Cmd+click on the `CGFloat` in Xcode - I go to the `CGBase.h` in `CoreGraphics` framework. Try to clean the project and replace the frameworks - the result is the same. Waiting for your help.",2014/07/15,"['https://Stackoverflow.com/questions/24750593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2042311/']","The solution is simple: + +``` +#import + +```","Also don't need a full CoreGraphics.h. This is enough: + +``` +#import + +```" +24750593,"I try to use `panoramaGL` framework and try to add it to my static library. So I've imported it to the project, add `CoreGraphics` framework but have an issue `Unknown type name 'CGFloat'` in PLStructs.h. When I Cmd+click on the `CGFloat` in Xcode - I go to the `CGBase.h` in `CoreGraphics` framework. Try to clean the project and replace the frameworks - the result is the same. Waiting for your help.",2014/07/15,"['https://Stackoverflow.com/questions/24750593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2042311/']","You actually don't need to import the full `UIKit`. This is enough: + +``` +#import + +```","The same problem came for me in Cocos2D. + +The solution is + +1. Go to build settings. In **Architectures** field you might have ""Standard architectures (armv7, armv7s, arm64). +2. The main cause for the problem is arm64. So the best way is to use ""**armv7**"" in the field. +3. We keep the standard architecture as is n ""**valid architectures**"" + +Hope it helps." +24750593,"I try to use `panoramaGL` framework and try to add it to my static library. So I've imported it to the project, add `CoreGraphics` framework but have an issue `Unknown type name 'CGFloat'` in PLStructs.h. When I Cmd+click on the `CGFloat` in Xcode - I go to the `CGBase.h` in `CoreGraphics` framework. Try to clean the project and replace the frameworks - the result is the same. Waiting for your help.",2014/07/15,"['https://Stackoverflow.com/questions/24750593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2042311/']","Also don't need a full CoreGraphics.h. This is enough: + +``` +#import + +```","The same problem came for me in Cocos2D. + +The solution is + +1. Go to build settings. In **Architectures** field you might have ""Standard architectures (armv7, armv7s, arm64). +2. The main cause for the problem is arm64. So the best way is to use ""**armv7**"" in the field. +3. We keep the standard architecture as is n ""**valid architectures**"" + +Hope it helps." +24750593,"I try to use `panoramaGL` framework and try to add it to my static library. So I've imported it to the project, add `CoreGraphics` framework but have an issue `Unknown type name 'CGFloat'` in PLStructs.h. When I Cmd+click on the `CGFloat` in Xcode - I go to the `CGBase.h` in `CoreGraphics` framework. Try to clean the project and replace the frameworks - the result is the same. Waiting for your help.",2014/07/15,"['https://Stackoverflow.com/questions/24750593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2042311/']","Also don't need a full CoreGraphics.h. This is enough: + +``` +#import + +```","You actually don't need to import the full `UIKit`. This is enough: + +``` +#import + +```" +73724,I have a lot of computers in my network and i need to get info about the software and hardware installed on all of them Is there any software to make such network inventory and audit?,2009/11/21,"['https://superuser.com/questions/73724', 'https://superuser.com', 'https://superuser.com/users/-1/']","If you want to gather inventory/audit information **programmatically**, then use [WMI](http://msdn.microsoft.com/en-us/library/aa394582(VS.85).aspx). + +WMI has a good .NET interface that is readibly available from within Visual Studio 2008 as a collection of library classes. PowerShell also exposes this interface for scripting.","You can try Spiceworks, it is free software with promo, also I’ve heard that the network inventory software by Clearapps is wide spread among sysadmins. It’s not free, but has more wide functionality. Or you can just google search and find everything here: + +" +73724,I have a lot of computers in my network and i need to get info about the software and hardware installed on all of them Is there any software to make such network inventory and audit?,2009/11/21,"['https://superuser.com/questions/73724', 'https://superuser.com', 'https://superuser.com/users/-1/']","If you want to gather inventory/audit information **programmatically**, then use [WMI](http://msdn.microsoft.com/en-us/library/aa394582(VS.85).aspx). + +WMI has a good .NET interface that is readibly available from within Visual Studio 2008 as a collection of library classes. PowerShell also exposes this interface for scripting.",you can try [OCS Inventory](http://www.ocsinventory-ng.org/) which is an open source software which allows to do that. +67794186,"I'm looking to create a custom, reusable Angular Material component for a slide toggle. I want to be able to pass different click functions into it and get the MatSlideToggleChange object back. Instead I get 'undefined'. + +Here is my custom component ts and html files: + +``` +{{toggleText}} + +export class CustomSlideToggleComponent { + + @Input() public toolTip: string = ''; + @Input() public isDisabled: boolean = false; + @Input() public isRequired: boolean = false; + @Input() public toggleText: string = ''; + @Input() public tabNumber: number = null; + @Input() public toggleId: string; + @Input() public controlName: string = ''; + + @Output() public readonly toggleClick = new EventEmitter(); + + public constructor() { } +} + +``` + +I've tried to implement it this way using this html: + +``` + + +``` + +and this in the typescript: + +``` +public toggleEvent: MatSlideToggleChange; + +public onEnableUser($event: MatSlideToggleChange) { + console.log('toggle was clicked' + $event); +} + +``` + +When I click on the slide toggle $event always comes back 'undefined'. How can I use different click functions with this custom component?",2021/06/01,"['https://Stackoverflow.com/questions/67794186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2026659/']","I see two potential issues with your usage of the `custom-slide-toggle`: + +1. `toggleClick` should be binded with `(toggleClick)` as it's only an `Output`: + +```html + (toggleClick)=""onEnableUser(toggleEvent)"" + +``` + +2. `toggleEvent` is not the event variable, it should be `$event`: + +```html + (toggleClick)=""onEnableUser($event)"" + +```","Event binding is with parentheses so i think that + +``` +(toggleClick)=""onEnableUser(toggleEvent)"" + +``` + +should work." +1590623,"Reading This Article: [Digital Trends CMD Commands](https://www.digitaltrends.com/computing/how-to-use-command-prompt/). + +I Found A command Called Finger. +Trying it out on My System, Windows 10 + +Why won't it let me Finger anyone.. + +Says `Connect: Connection Refused?` +[![enter image description here](https://i.stack.imgur.com/tRIqP.jpg)](https://i.stack.imgur.com/tRIqP.jpg) +Not Sure If i'm entering the Commands right but just thought it was a funny command. + +If anyone else has an update or full comprehensive list of CMD commands please could you add it in the comments. + +[everything you need to know about tcp ips finger utility](https://www.techrepublic.com/article/everything-you-need-to-know-about-tcp-ips-finger-utility/) + +Partially Related Questions found here on StackOverflow with the keywords: CMD & finger.. + +[Capturing Username from Grunt Shell Command](https://stackoverflow.com/questions/26682312/capturing-username-from-grunt-shell-command) + +[Get only name and login from cmd finger -s](https://stackoverflow.com/questions/3893190/how-to-get-only-name-and-login-from-cmd-finger-s) + +[Implement an interactive shell over SSH in Python](https://stackoverflow.com/questions/35821184/implement-an-interactive-shell-over-ssh-in-python-using-paramiko/36948840#36948840) + +Will update the question in a minute with some more resources.",2020/10/04,"['https://superuser.com/questions/1590623', 'https://superuser.com', 'https://superuser.com/users/1018010/']","The funny name is not Windows-specific – the same program has existed under the same name in many operating systems of the past. ""Finger"" is one of the earliest ARPAnet services (along with Telnet, FTP, SMTP &c). + +* [History of the Finger protocol](http://www.rajivshah.com/Case_Studies/Finger/Finger.htm) +* [RFC 742](https://www.rfc-editor.org/rfc/rfc742) containing a few usage examples from 1977 + +### Invocation + +Your first problem is that the program expects a username and/or an Internet address (hostname or IP address) but you're giving it random numbers instead. Pay attention to the help text that it shows: + +``` +finger [-l] [user]@host + +``` + +This means that `-l` and the username are optional, but the ""@host"" is mandatory and it actually has to indicate a host (much like ping or telnet also expect a host). + +Note that the `-l` option is a lowercase L (indicating ""long output""), *not* the number one. + +On some other operating systems, `finger` also has a local mode where you can run it without any hostname and it'll directly collect information about local users. However, the Windows version will not do that – it will always try to connect to the 'fingerd' service running on localhost:79, which Windows systems simply don't have (hence the ""Connection refused"" message). + +(Yes, this actually contradicts the help text somewhat – if Windows *had* a finger service listening on port 79, then the '@host' would really be optional.) + +You can instead try the Windows-specific `quser` or `qwinsta` commands to get a general idea of how it would work. (They can even query a remote Windows system kinda like finger, although this too is disabled by default on non-server Windows versions.) + +### Practical use + +The second problem is that nearly all systems on the internet *no longer provide* the ""finger"" service, due to reasons of security (it reveals usernames) and privacy (it shows when a user is active and even which IP address they're connecting from). Basically it's a relic from the 1980s Internet. + +But a few public systems (mainly ""retro computing"" sites) still deliberately provide this service, so you can still try it out: + +* `finger @ssh.tilde.club` (basic Linux machine at the ""tilde.club"" social network) +* `finger @athena.dialup.mit.edu` (MIT's Linux cluster) +* `finger @samba.acc.umu.se` (Linux cluster at Umeå University) +* `finger @up.update.uu.se` (1970s [ITS](https://en.m.wikipedia.org/wiki/Incompatible_Timesharing_System) running in an emulator – you should use the `-l` option with this one) +* `finger @telehack.com` ([a game](http://telehack.com/telehack.html) that simulates 80s networks) +* `finger @nullroute.eu.org` (an entirely custom ""cluster"" fingerd) + +In all of those commands, the @host can be prefixed with someone's username if you know it, e.g. `finger operator@telehack.com`. The initial output will show you which usernames are currently logged in. + +Some systems will automatically activate ""long"" mode whenever a username is given, but with some other systems you still need the `-l` option to get detailed output. + +--- + +> +> The other system also has to be running Unix. +> +> +> + +The remote system is not required to be Unix – OpenVMS, ITS, Cisco IOS also had this service, and it's possible to write one for Windows as well *(which I have done)*. + +Because the protocol is very simple (just ASCII over TCP), some systems host a custom finger service that provides other kinds of data, such as weather information – e.g. CMU had a vending machine and MIT used to have a ""bathroom occupancy"" service ([see also](https://www.ucc.asn.au/services/drink.ucc)). Among new or surviving services, `finger [location]@graph.no` will give you a weather forecast.","That articles information on finger is a bit if a nonsense. Finger is a fairly simple command that is disabled pretty much everywhere because it is more a security threat then a benefit. It was commonly deployed in the early Internet (prior to mass users and security concerns) and does not use encryption or security. + +In order for system to work the remote system needs to be running a finger daemon (normally fingerd) - As systems are not running this you get a message when you try use the command. + +Likewise the syntax requires a hostname - not a number, so your client is trying to connect to a nonexistent device which is the specific cause of the failure you are seeing." +22224840,"I want to use mechanize to log into a page and retrieve some information. But however I try to authenticate It just fails with Error code **HTTP 401**, as you can see below: + +``` +r = br.open('http://intra') +File ""bui...e\_mechanize.py"", line 203, in open +File ""bui...g\mechanize\_mechanize.py"", line 255, +in _mech_openmechanize._response.httperror_seek_wrapper: HTTP Error 401: Unauthorized + +``` + +This is my code so far: + +``` +import mechanize +import cookielib + +# Browser +br = mechanize.Browser() + +# Cookie Jar +cj = cookielib.LWPCookieJar() +br.set_cookiejar(cj) + +# Browser options +br.set_handle_equiv(True) +# br.set_handle_gzip(True) +br.set_handle_redirect(True) +br.set_handle_referer(True) +br.set_handle_robots(False) + +# Follows refresh 0 but not hangs on refresh > 0 +br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) + +# If the protected site didn't receive the authentication data you would +# end up with a 410 error in your face +br.add_password('http://intra', 'myusername', 'mypassword') + +# User-Agent (this is cheating, ok?) +br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] +# Open some site, let's pick a random one, the first that pops in mind: +# r = br.open('http://google.com') +r = br.open('http://intra') +html = r.read() + +# Show the source +print html + +``` + +What am I doing wrong? visiting `http://intra` (internal page) with e.g. chrome, it pops open a windows and asks for username/password once and then all is good. + +The dialogue which pops open looks like this: + +![enter image description here](https://i.stack.imgur.com/JTb7M.png)",2014/03/06,"['https://Stackoverflow.com/questions/22224840', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/576671/']","After tons of reaserch I managed to find out the reason behind this. + +Find of all the site uses a so called [NTLM authentication](http://hc.apache.org/httpclient-legacy/authentication.html#Authentication_Schemes), which is not supported by mechanize. +This can help to find out the authentication mechanism of a site: + +``` +wget -O /dev/null -S http://www.the-site.com/ + +``` + +So the code was modified a little bit: + +``` +import sys +import urllib2 +import mechanize +from ntlm import HTTPNtlmAuthHandler + +print(""LOGIN..."") +user = sys.argv[1] +password = sys.argv[2] +url = sys.argv[3] + +passman = urllib2.HTTPPasswordMgrWithDefaultRealm() +passman.add_password(None, url, user, password) +# create the NTLM authentication handler +auth_NTLM = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(passman) + +browser = mechanize.Browser() +handlersToKeep = [] + +for handler in browser.handlers: + if not isinstance(handler, + (mechanize._http.HTTPRobotRulesProcessor)): + handlersToKeep.append(handler) + +browser.handlers = handlersToKeep +browser.add_handler(auth_NTLM) + +response = browser.open(url) +response = browser.open(""http://www.the-site.com"") +print(response.read()) + +``` + +and finally mechanize needs to be patched, as mentioned [here](https://stackoverflow.com/questions/13649964/python-mechanize-with-ntlm-getting-attributeerror-httpresponse-instance-has-no): + +``` +--- _response.py.old 2013-02-06 11:14:33.208385467 +0100 ++++ _response.py 2013-02-06 11:21:41.884081708 +0100 +@@ -350,8 +350,13 @@ + self.fileno = self.fp.fileno + else: + self.fileno = lambda: None +- self.__iter__ = self.fp.__iter__ +- self.next = self.fp.next ++ ++ if hasattr(self.fp, ""__iter__""): ++ self.__iter__ = self.fp.__iter__ ++ self.next = self.fp.next ++ else: ++ self.__iter__ = lambda self: self ++ self.next = lambda self: self.fp.readline() + + def __repr__(self): + return '<%s at %s whose fp = %r>' % ( + +```","@theAlse : did you need to separately handle session cookies? I used your approach to authenticate against the SSO server but when I access the main site (ServiceNow) on the second ""browser.open"" call I still get a 401:Unauthorized error. + +I tacked on a debug message on the mechanize \_response.py file to show the URL being visited and I was surprised that there is a secondary SSO server. + +``` +$ python s3.py +LOGIN... +[_DEBUG] Visiting https://sso.intra.client.com +[_DEBUG] Got past the first open statement. +[_DEBUG] Visiting https://clienteleitsm.service-now.com +[_DEBUG] Visiting +[_DEBUG] Visiting +[_DEBUG] Visiting +[_DEBUG] Visiting +[_DEBUG] Visiting + +[Client-specific page about invalid username and password credential combination follows] + +... + + +``` + +I already snipped a lot of the redirect URLS after the third debug line. The random strings are actually unique as when I put them in a browser I get an error page. However if I do it in an IE browser I dont even see the redirect pages. + +Thanks." +23517225,"I have an MVC 5 / Bootstrap application. On one of the pages, I have a number of fields all bound to the model associated with the page. However, I also have a simple unordered list which always starts out empty and the user can then add items to it. They do this by entering some text into a type ahead field. Once the user finds what he/she is looking for, he/she can click a button and have it added to the unordered list. Any number of items can be added to the list. All of this works fine. + +My question is how I can get the contents of the unordered list posted back to the server along with the rest of the form contents, since the unordered list isn't part of the model?",2014/05/07,"['https://Stackoverflow.com/questions/23517225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/163534/']","Here is one way to skin this cat: + +A) Add a collection to your model (which really should be a ViewModel, and not a domain model) to hold those items + +B) In your button's click handler, create a hidden input field that conforms to the ASP.Net Wire Format: + +If you had a collection of orders, you should end up generating controls like this: + +``` + + + +``` + +Note sequential ordering is important, if you start removing items, you'll need to re-sequence your name values.","There couple of ways to work it out. + If you don't want to add to model, what I would prefer to do you can: + +1. Directly access item that were posted via `Controller.Request` property; +2. You can post this items separately via Ajax request, and handle them in different controller action." +40522008,"Note: This is an opinionated question. I m asking this as I was unable to find proper articles covering my concern. + +PHP (alone or with a framework like laravel) can be used for both backend and frontend (with templating engines like Blade,Smarty,etc) development. + +My concern is: + +1. Is it good to use templating engine and create views in PHP? +2. Use PHP just as a backend tech and create APIs, let the frontend be built in any other language (like Angular,React,etc) chosen by the front end developer. +3. If I use templating-engine, is my application getting too tightly coupled between frontend tech choices and backend tech choices? + +PS: I hope my concern is clear, if not I will explain it in an elaborated way.",2016/11/10,"['https://Stackoverflow.com/questions/40522008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5193722/']","Your response is proper but your parsing is not proper. So first of all add GSON in your gradle file. + +`compile 'com.google.code.gson:gson:2.4'` + +Now use below your code for parsing your response + +``` +try { + JSONArray array = new JSONArray(""put your response here""); + Gson gson = new Gson(); + for (int i = 0 ; i `compile 'com.google.code.gson:gson:2.8.0'` + +``` +List survivorZAMQuestionnaires; +... + +Gson gson = new Gson(); +Type listType = new TypeToken>(){}.getType(); +survivorZAMQuestionnaires = gson.fromJson(jsonString, listType); + +``` + +`Type` is instance of `java.lang.reflect.Type;`" +40522008,"Note: This is an opinionated question. I m asking this as I was unable to find proper articles covering my concern. + +PHP (alone or with a framework like laravel) can be used for both backend and frontend (with templating engines like Blade,Smarty,etc) development. + +My concern is: + +1. Is it good to use templating engine and create views in PHP? +2. Use PHP just as a backend tech and create APIs, let the frontend be built in any other language (like Angular,React,etc) chosen by the front end developer. +3. If I use templating-engine, is my application getting too tightly coupled between frontend tech choices and backend tech choices? + +PS: I hope my concern is clear, if not I will explain it in an elaborated way.",2016/11/10,"['https://Stackoverflow.com/questions/40522008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5193722/']","Your response is proper but your parsing is not proper. So first of all add GSON in your gradle file. + +`compile 'com.google.code.gson:gson:2.4'` + +Now use below your code for parsing your response + +``` +try { + JSONArray array = new JSONArray(""put your response here""); + Gson gson = new Gson(); + for (int i = 0 ; i survivorZAMQuestionnaires = new Gson().fromJson(json, new TypeToken>() { + }.getType()); + +```" +40522008,"Note: This is an opinionated question. I m asking this as I was unable to find proper articles covering my concern. + +PHP (alone or with a framework like laravel) can be used for both backend and frontend (with templating engines like Blade,Smarty,etc) development. + +My concern is: + +1. Is it good to use templating engine and create views in PHP? +2. Use PHP just as a backend tech and create APIs, let the frontend be built in any other language (like Angular,React,etc) chosen by the front end developer. +3. If I use templating-engine, is my application getting too tightly coupled between frontend tech choices and backend tech choices? + +PS: I hope my concern is clear, if not I will explain it in an elaborated way.",2016/11/10,"['https://Stackoverflow.com/questions/40522008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5193722/']","Your response is proper but your parsing is not proper. So first of all add GSON in your gradle file. + +`compile 'com.google.code.gson:gson:2.4'` + +Now use below your code for parsing your response + +``` +try { + JSONArray array = new JSONArray(""put your response here""); + Gson gson = new Gson(); + for (int i = 0 ; i >() + }.getType(); + List survivorZAMQuestionnaireList =new Gson().fromJson + (jsonMessage, type); + Log.d(""Print List"",survivorZAMQuestionnaireList.toString()); + } + + } + +```" +40522008,"Note: This is an opinionated question. I m asking this as I was unable to find proper articles covering my concern. + +PHP (alone or with a framework like laravel) can be used for both backend and frontend (with templating engines like Blade,Smarty,etc) development. + +My concern is: + +1. Is it good to use templating engine and create views in PHP? +2. Use PHP just as a backend tech and create APIs, let the frontend be built in any other language (like Angular,React,etc) chosen by the front end developer. +3. If I use templating-engine, is my application getting too tightly coupled between frontend tech choices and backend tech choices? + +PS: I hope my concern is clear, if not I will explain it in an elaborated way.",2016/11/10,"['https://Stackoverflow.com/questions/40522008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5193722/']","Your response is proper but your parsing is not proper. So first of all add GSON in your gradle file. + +`compile 'com.google.code.gson:gson:2.4'` + +Now use below your code for parsing your response + +``` +try { + JSONArray array = new JSONArray(""put your response here""); + Gson gson = new Gson(); + for (int i = 0 ; i `compile 'com.google.code.gson:gson:2.8.0'` + +``` +List survivorZAMQuestionnaires; +... + +Gson gson = new Gson(); +Type listType = new TypeToken>(){}.getType(); +survivorZAMQuestionnaires = gson.fromJson(jsonString, listType); + +``` + +`Type` is instance of `java.lang.reflect.Type;`" +40522008,"Note: This is an opinionated question. I m asking this as I was unable to find proper articles covering my concern. + +PHP (alone or with a framework like laravel) can be used for both backend and frontend (with templating engines like Blade,Smarty,etc) development. + +My concern is: + +1. Is it good to use templating engine and create views in PHP? +2. Use PHP just as a backend tech and create APIs, let the frontend be built in any other language (like Angular,React,etc) chosen by the front end developer. +3. If I use templating-engine, is my application getting too tightly coupled between frontend tech choices and backend tech choices? + +PS: I hope my concern is clear, if not I will explain it in an elaborated way.",2016/11/10,"['https://Stackoverflow.com/questions/40522008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5193722/']","The Error clearly states that the Gson accepts `JsonObject` not `JsonArray`. In your case you can put the response `JsonArray` into a `JsonObject` with a key for that `JsonArray` and give that key as `annotation` in `SurvivorZAMQuestionList`. By this way you can easily sort this problem. + +Hope this is Helpful :)","Parse Your Json this way, + +``` +List survivorZAMQuestionnaires = new Gson().fromJson(json, new TypeToken>() { + }.getType()); + +```" +40522008,"Note: This is an opinionated question. I m asking this as I was unable to find proper articles covering my concern. + +PHP (alone or with a framework like laravel) can be used for both backend and frontend (with templating engines like Blade,Smarty,etc) development. + +My concern is: + +1. Is it good to use templating engine and create views in PHP? +2. Use PHP just as a backend tech and create APIs, let the frontend be built in any other language (like Angular,React,etc) chosen by the front end developer. +3. If I use templating-engine, is my application getting too tightly coupled between frontend tech choices and backend tech choices? + +PS: I hope my concern is clear, if not I will explain it in an elaborated way.",2016/11/10,"['https://Stackoverflow.com/questions/40522008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5193722/']","The Error clearly states that the Gson accepts `JsonObject` not `JsonArray`. In your case you can put the response `JsonArray` into a `JsonObject` with a key for that `JsonArray` and give that key as `annotation` in `SurvivorZAMQuestionList`. By this way you can easily sort this problem. + +Hope this is Helpful :)","Do a gradle dependency of gson. + +``` +compile 'com.google.code.gson:gson:2.4' + +``` + +Update code like this; + +``` + private void parseJSON(String jsonMessage) throws JSONException { + if (jsonMessage.startsWith(""["")) { + Type type = new TypeToken>() + }.getType(); + List survivorZAMQuestionnaireList =new Gson().fromJson + (jsonMessage, type); + Log.d(""Print List"",survivorZAMQuestionnaireList.toString()); + } + + } + +```" +40522008,"Note: This is an opinionated question. I m asking this as I was unable to find proper articles covering my concern. + +PHP (alone or with a framework like laravel) can be used for both backend and frontend (with templating engines like Blade,Smarty,etc) development. + +My concern is: + +1. Is it good to use templating engine and create views in PHP? +2. Use PHP just as a backend tech and create APIs, let the frontend be built in any other language (like Angular,React,etc) chosen by the front end developer. +3. If I use templating-engine, is my application getting too tightly coupled between frontend tech choices and backend tech choices? + +PS: I hope my concern is clear, if not I will explain it in an elaborated way.",2016/11/10,"['https://Stackoverflow.com/questions/40522008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5193722/']","The Error clearly states that the Gson accepts `JsonObject` not `JsonArray`. In your case you can put the response `JsonArray` into a `JsonObject` with a key for that `JsonArray` and give that key as `annotation` in `SurvivorZAMQuestionList`. By this way you can easily sort this problem. + +Hope this is Helpful :)","You need List of objects not only object, because your JSON contain list of objects. [How to Parse JSON Array in Android with Gson](https://stackoverflow.com/a/8371455/3529309)" +13803059,"I need to run `knit2html` on the command line using `Rscript`. I tried the following code and it works + +``` +Rscript -e ""(knitr::knit2html(text = '## good', fragment.only = TRUE))"" + +``` + +However, when I introduce R code chunks (or anything involving backticks), the process hangs. So the following does NOT work + +``` +Rscript -e ""(knitr::knit2html(text = '## good\n `r 1 + 1`',fragment.only = T))"" + +``` + +For the purpose of my use, I only have access to the contents and hence can NOT pass a file to `knit2html`, which I know will work. + +My question is how do I make this work. I know the problem is the backticks and I have tried looking at escaping them, but nothing seems to be working.",2012/12/10,"['https://Stackoverflow.com/questions/13803059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/235349/']","Android 2.3 + +``` + // display the data + + String baseUrl = """"; + String mimeType = ""text/html""; + String encoding = ""UTF-8""; + html = sb.toString(); + String historyUrl = """"; + + webViewDataViewer.loadDataWithBaseURL(baseUrl, html, mimeType, encoding, historyUrl); + +```","The % symbol does not load in Android 2.2 webview +It has to be encoded." +63768,"Fluids exert hydrostatic pressure because their molecules hit each other or the immersed body, but why is that at a greater depth pressure is higher when molecules are the same ? + +Assume density of fluid is uniform throughout the liquid.",2013/05/08,"['https://physics.stackexchange.com/questions/63768', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']","Your statement: + +> +> Assume density of fluid is same throughout. +> +> +> + +conflicts with your actual question + +> +> But why is that at a greater depth pressure is higher when molecules are the same? +> +> +> + +If we imposed the very strict and non-physical constraint that the density of the fluid was uniform and isotropic, then we would have not variance in pressure what so ever - but as I have said this is non-physical. + +What happens in reality is as follows... Each molecule in a given fluid has a mass. Gravity acts on this mass (lets assume vertically, and a column of perfectly stacked molecules) to produce a weight for each molecule. If we take the limiting case where all molecules are stationary then it should be easy to convince yourself that at some depth within the fluid a given molecule has a force acting upon it purely from gravity $Mg$ [$M$ is the molecules mass] plus the weight of all those molecules above it $\Sigma\_{i}m\_{i}g$ [where $m\_{i}$ is the mass of the ith molecule], but also a reaction force provided by the contact with the molecule directly below it $R$, where + +$$R = Mg + \Sigma\_{i}m\_{i}g,$$ + +for some arbitrary stationary molecule. From this it should be clear that the absolute force acting on this molecule (in the vertical direction, for our ideal column) increases with the depth of the molecule. This is essentially what causes pressure in a fluid, in increases the fluid density with depth. + +*Note. Of course the above is very much simplified as there will be much more going on at the molecular level, but this example should provide you with a basic Newtonian view with which to build from.* + +I hope this helps.","In short: because the weight does it so. + +Imagine a situation where several people are walking on each other in a small room: those that are at the top don't feel any discomfort whereas those at the bottom are crunched by the weight of the one above them. It's quite the same for the molecules." +63768,"Fluids exert hydrostatic pressure because their molecules hit each other or the immersed body, but why is that at a greater depth pressure is higher when molecules are the same ? + +Assume density of fluid is uniform throughout the liquid.",2013/05/08,"['https://physics.stackexchange.com/questions/63768', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/-1/']","Your statement: + +> +> Assume density of fluid is same throughout. +> +> +> + +conflicts with your actual question + +> +> But why is that at a greater depth pressure is higher when molecules are the same? +> +> +> + +If we imposed the very strict and non-physical constraint that the density of the fluid was uniform and isotropic, then we would have not variance in pressure what so ever - but as I have said this is non-physical. + +What happens in reality is as follows... Each molecule in a given fluid has a mass. Gravity acts on this mass (lets assume vertically, and a column of perfectly stacked molecules) to produce a weight for each molecule. If we take the limiting case where all molecules are stationary then it should be easy to convince yourself that at some depth within the fluid a given molecule has a force acting upon it purely from gravity $Mg$ [$M$ is the molecules mass] plus the weight of all those molecules above it $\Sigma\_{i}m\_{i}g$ [where $m\_{i}$ is the mass of the ith molecule], but also a reaction force provided by the contact with the molecule directly below it $R$, where + +$$R = Mg + \Sigma\_{i}m\_{i}g,$$ + +for some arbitrary stationary molecule. From this it should be clear that the absolute force acting on this molecule (in the vertical direction, for our ideal column) increases with the depth of the molecule. This is essentially what causes pressure in a fluid, in increases the fluid density with depth. + +*Note. Of course the above is very much simplified as there will be much more going on at the molecular level, but this example should provide you with a basic Newtonian view with which to build from.* + +I hope this helps.","First, think of this in terms of psi: + +This is a bit simplified, but: When you are standing at sea level, under S.T.P (Standard Temperature and Pressure), you have a column of air some 120,000 feet high pushing on you. That weighs 14.7 pounds. (for a column that has a cross-section of one square inch.) + +That is the pressure we feel, every day. It is what our bodies are accustomed to. + +Now, think in the same terms, when you are under the water. In addition to that column of air, you also have a column of water--however deep you are-pushing down on you. If you are 33 feet deep, a square-inch cross-section of water will weigh as much as the column of air above it... Which is why at 33 feet, you are now experiencing 2 Atmospheres of pressure. (Atmosphere being the equivalent of what you feel at sea level at STP)" +119756,"I am on a wireless network trying to play CS go with my friends. They all are in the same room with me. How can I create a server so I can play with my friends? In CS 1.6 we launch a hlds file which is in the cs 1.6 directory. We create a server through launching this hlds file. But in Counter Strike: Global Offensive I can't find hlds file, so now I don't know how to setup or create a server.",2013/06/09,"['https://gaming.stackexchange.com/questions/119756', 'https://gaming.stackexchange.com', 'https://gaming.stackexchange.com/users/49842/']","Valve keeps the documentation for installing CS:GO servers on the [Valve Developer Wiki](https://developer.valvesoftware.com/wiki/Counter-Strike:_Global_Offensive_Dedicated_Servers). The docs don't present a direct step-by-step procedure, though, so I'll try to assist. + +1. Download [SteamCMD](https://developer.valvesoftware.com/wiki/SteamCMD) (look for the ""Windows zip file"" link) +2. Unzip SteamCMD into a folder on your computer. +3. Double click steamcmd.exe +4. Wait while steamcmd gets the latest patches +5. At the `Steam>` prompt, type `login anonymous` to get connected to Steam +6. At the `Steam>` prompt, type `force_install_dir cs_go` to set the directory where CS:GO will be installed to. In this case, it's the folder cs\_go in the SteamCMD folder +7. At the `Steam>` prompt, type `app_update 740 validate` to initiate the dedicated server download. +8. Wait for the files to download (the time depends on Steam server load and your internet connection) + +Once the download is complete, you can close SteamCMD. + +To launch the server: + +1. Open a command prompt (On Win7, you can open the Windows menu and type cmd.exe) +2. Get to the directory where you installed the dedicated server (ie, `cd C:\Users\YOUR USERNAME\Downloads\steamcmd_win32\cs_go`) +3. Launch the server exe with a command like: `srcds -game csgo -console -usercon +game_type 0 +game_mode 0 +mapgroup mg_bomb +map de_dust` + +The actual server options will vary depending on what type of CS:GO game server you want to run. More examples are [here](https://developer.valvesoftware.com/wiki/Counter-Strike:_Global_Offensive_Dedicated_Servers) and complete srcds docs are [here](https://developer.valvesoftware.com/wiki/Command_Line_Options#Source_Games). + +Running the server consumes some resources, so if you've got a PC that won't be playing the game, you can use that to run the server. If your PC is powerful enough, you might be able to run both the server and the game on the same machine. However, that will depend on a number of factors that are specific to your setup.","have you tried adding the -ip command line parameter with the LAN ip of the server? +If you activated the gamemodes\_server, are you sure it does not have any syntax error in there? + +I've been setting up csgo servers since May 2013 and those were the most common issues." +9434,"I'm completely new to this, so I don't know if I'm doing something dumb or my regulator is broken. Here's what I'm doing: + +Here's what I'm doing: + +1. I connected [this regulator](http://www.beveragefactory.com/draftbeer/regulator/double/premium_double_gauge_542.html) to a 5 lb. CO2 cylinder. +2. Closed the blue output valve. +3. Turned the regulator knob all the way down (left, i.e. counter-clockwise, i.e. out, i.e. towards the minus sign). +4. Opened the valve on the CO2 cylinder. +5. As expected, at this point the input (high-pressure) guage quickly goes up to about 600 psi. +6. NOT expected: the output (low-pressure) guage quickly goes up to 50-60 PSI (the upper limit), and the relief valve starts sputtering and releasing CO2 quickly. +7. Finally, as expected, when I shut off the cylinder, the input pressure slowly drops to zero (and then, if I hold open the relief valve or open the output, so does the output pressure.) + +I can't find any configuration of knobs and valves that doesn't result in the output pressure spiking and the relief valve opening. Am I missing something? Is the regulator broken? Something else entirely? + +NOTE: If I open the output, and open the regulator a little bit (so it's just releasing CO2 into the room) then the regulator knob does control the flow rate, as expected. Turning the knob to the left reduces the flow to a fairly low rate. If I then block the flow by closing the output valve, the output pressure builds to 60 PSI in about a second and the relief valve opens.",2013/02/21,"['https://homebrew.stackexchange.com/questions/9434', 'https://homebrew.stackexchange.com', 'https://homebrew.stackexchange.com/users/3159/']","It sounds like what you're doing is correct. (And I guess you've tried turning it all the way to the right - clockwise?) + +The relief valve can be quite sensitive on some regulators, causing it to fire a little prematurely, so it might have been that, but for the fact that you say the dial jumps to 60 psi. + +I would double check that the relief lock isn't engaged - this will cause the relief valve to be open all the time. Try turning the ring fastened at the end of the relief valve. + +If you still can't regulate the pressure with the knob, then the regulator isn't living up to it's name! Sounds like you have a broken regulator.","CO2 Regulator knobs are counter intuitive for 1st time users. +When you ""close it"" like a faucet clockwise in fact you are adjusting a screw/pushing a pin that allow more CO2 flow. +Short: Try twisting all the way counter clockwise. +If it still fails, have your reg checked." +4658963,"Is this a right code from the point of view of memory management? + +``` +NSEntityDescription *description = [NSEntityDescription + entityForName:@""Event"" inManagedObjectContext:managedObjectContext]; +NSFetchRequest *eventRequest = [[[NSFetchRequest alloc] init] autorelease]; +[eventRequest setEntity:description]; +[description release]; + +NSPredicate *eventPredicate = [NSPredicate predicateWithFormat: + @""(event == %@)"", [item objectForKey:@""event""]]; +[eventRequest setPredicate:eventPredicate]; + +``` + +Or i need to release description and eventPredicate? + +Thanks",2011/01/11,"['https://Stackoverflow.com/questions/4658963', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/258863/']","Looking at that code, the only object you own is the `eventRequest`. It is being autoreleased so you don't need to release it again. + +From what I can see, based on naming convention, all the other objects aren't owned, so you don't need to release them. + +The line `[description release];` will likely cause a crash for you somewhere down the line.",You dont't need any releases for that code. You should read [Apple's documentation](http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/MemoryMgmt/MemoryMgmt.html) to find out why. +11906750,"I want to scroll to the bottom of my tableview that contains custom cells. + +Here is the code I am using to scroll: + +``` +NSIndexPath *lastMessage = [NSIndexPath indexPathForRow:[self.conversation.messages count]-1 inSection:0]; +[self.messageTable scrollToRowAtIndexPath:lastMessage atScrollPosition:UITableViewScrollPositionTop animated:YES]; + +``` + +This scrolls the view; however only the very top of the last cell is visible with ~3/4 of the cell still below the fold that I have to manually scroll down to. Any ideas on how to fix this?",2012/08/10,"['https://Stackoverflow.com/questions/11906750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/482255/']",Turned out to be a timing issue. The tableview hadn't fully rendered yet when I called that method from viewdidload (contentsize of 0). Calling this method in viewDidAppear works brilliantly though.,It seems like the UITableView is confused about how big your cells are. Set the `rowHeight` property on the UITableView to the height of your custom cell. +7917076,"I tried the `CONVERT(TIME,sample_datetime)`, but my software does not recognize TIME as a type. + +How do I take sample `datetime` and extract the time from it in one variable and the day of the week from it in another variable?",2011/10/27,"['https://Stackoverflow.com/questions/7917076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/971115/']","Using [DATEPART()](http://msdn.microsoft.com/en-us/library/ms174420.aspx) function: + +``` +// returns 4 +SELECT DATEPART(day, '2010-09-04 11:22:33') + +// returns 7 +SELECT DATEPART(dw, '2010-09-04 11:22:33') + +// returns 11:22:33 +SELECT CAST(DATEPART(HOUR, '2010-09-04 11:22:33') AS VARCHAR(2)) + ':' + + CAST(DATEPART(MINUTE, '2010-09-04 11:22:33') AS VARCHAR(2)) + ':' + + CAST(DATEPART(SECOND, '2010-09-04 11:22:33')AS VARCHAR(2)) + +``` + +Regarding TIME data type - it introduced since Sql Server 2008: + +``` +SELECT CAST('2010-09-04 11:22:33' as Time) + +```","you didnt specify sql server version but + +`select datepart(dw,yourdate)` should do it." +7917076,"I tried the `CONVERT(TIME,sample_datetime)`, but my software does not recognize TIME as a type. + +How do I take sample `datetime` and extract the time from it in one variable and the day of the week from it in another variable?",2011/10/27,"['https://Stackoverflow.com/questions/7917076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/971115/']","Using [DATEPART()](http://msdn.microsoft.com/en-us/library/ms174420.aspx) function: + +``` +// returns 4 +SELECT DATEPART(day, '2010-09-04 11:22:33') + +// returns 7 +SELECT DATEPART(dw, '2010-09-04 11:22:33') + +// returns 11:22:33 +SELECT CAST(DATEPART(HOUR, '2010-09-04 11:22:33') AS VARCHAR(2)) + ':' + + CAST(DATEPART(MINUTE, '2010-09-04 11:22:33') AS VARCHAR(2)) + ':' + + CAST(DATEPART(SECOND, '2010-09-04 11:22:33')AS VARCHAR(2)) + +``` + +Regarding TIME data type - it introduced since Sql Server 2008: + +``` +SELECT CAST('2010-09-04 11:22:33' as Time) + +```","DATEPART or DATENAME with DW will work for the day of the week depending on which format you need + +``` +SELECT DATEPART(DW, GETDATE()) +SELECT DATENAME(DW, GETDATE()) + +``` + +You can convert the datetime to a varchar with specific formatting to get just the time + +``` +SELECT CONVERT(VARCHAR, GETDATE(), 14) + +``` + +2008 has a TIME datatype, but it doesn't sound like you're running that" +74357690,"According to the Serverless [documentation](https://www.serverless.com/framework/docs/guides/parameters#), I should be able to define params within the dashboard/console. But when I navigate there, the inputs are disabled: +[![enter image description here](https://i.stack.imgur.com/gllCD.png)](https://i.stack.imgur.com/gllCD.png) + +I've tried following the [instructions](https://www.serverless.com/framework/docs/guides/parameters#cli-parameters) to update via CLI, with: `serverless deploy --param=""domain=myapp.com"" --param=""key=value""`. The deploy runs successfully (I get a `✔ Service deployed to...` message with no errors), but nothing appears in my dashboard. Likewise, when I run a command to check whether there are any params stored: `serverless param list`, I get + +``` +Running ""serverless"" from node_modules +No parameters stored + +```",2022/11/08,"['https://Stackoverflow.com/questions/74357690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11664580/']","Passing `param` flags will not upload the parameters to Dashboard/Console, it will only expose them in your configuration so you can access them with `${param:}`. To my best knowledge, it is not possible to set Dashboard parameters with CLI, you need to set them manually via UI.",It was a permissions problem. The owner of the account updated the permissions and I was able to update the inputs. +48646089,"I want to split this df into bins based on the variable Quality. However, it is extremely right skewed + +``` + TSI2 YRI Chromosome Quality +a1 0.03829518 0.050231431 22 0.860 +a2 0.03110103 0.010192455 22 0.938 +a3 0.03141379 0.060045625 22 0.848 + +``` + +This is a hist of Quality. + +[![enter image description here](https://i.stack.imgur.com/7yPPx.png)](https://i.stack.imgur.com/7yPPx.png) + +ll of the ways I have tried to bin the data so far have resulted in bins with very different numbers of samples in each. + +``` +totalResults$groups = cut(totalResults$Quality, 10) + +``` + +Is there a way to force the bins to have even numbers of samples in each? + +thanks",2018/02/06,"['https://Stackoverflow.com/questions/48646089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5784757/']","Applying the `FileStream` approach - as already mentioned - use the `FileStream` [constructor](https://learn.microsoft.com/en-us/dotnet/api/system.io.filestream.-ctor?view=netframework-4.8#System_IO_FileStream__ctor_System_String_System_IO_FileMode_System_IO_FileAccess_System_IO_FileShare_System_Int32_) that accepts a `bufferSize` argument, which specifies the amount of bytes being read into memory. + +*(You can overrule the default value (`4096`) to fit your environment.)* + +``` +public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize); + +``` + +> +> **bufferSize**: +> +> A positive System.Int32 value greater than 0 indicating +> the buffer size. +> +> The default buffer size is 4096. +> +> +> + +``` +public IActionResult GetFile() +{ + var filePath = @""c:\temp\file.mpg""; // Your path to the audio file. + var bufferSize = 1024; + var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize); + return File(fileStream, ""audio/mpeg""); +} + +``` + +Note that there's no need to dispose the `fileStream`; the `File` method takes care of this. + +--- + +To clarify: + +When passing in a `FileStream`, its content is being read in chunks (matching the configured buffersize). + +Concrete, this means that its `Read` method (`int Read (byte[] array, int offset, int count)`) gets executed repeatedly untill all bytes have been read, ensuring that no more than the given number of bytes are stored in memory. + +So the scalability is within the less memory usage, as memory is a resource that can come under pressure if the size of the file is high, especially in combination with a high read frequency (of this or of other files) +which might cause out of memory problems.","*Posting as a community wiki, since it doesn't technically answer the question, but suggested code won't work as a comment.* + +You can return a stream directly from `FileResult`, so there's no need to manually read from it. In fact, your code doesn't actually ""stream"", since you're basically reading the whole stream into memory, and then returning the `byte[]` at the end. Instead, just do: + +``` +using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) +{ + return File(fileStream, ""audio/mpeg""); +} + +``` + +Or even simpler, just return the file path, and let `FileResult` handle it completely: + +``` +return File(System.IO.File.OpenRead(filePath), ""audio/mpeg""); + +```" +2005378,Let $p$ be a prime number and $A$ be a commutative ring with unity. We say that $A$ has characteristic $p$ if $p\cdot 1\_A=0$. I would like to know if you could have a ring $A$ with all residue fields (= $\operatorname{Frac}(A/\mathfrak{p}$) with $\mathfrak{p}$ a prime ideal) of characteristic $p$ but $A$ itself not being of characteristic $p$.,2016/11/08,"['https://math.stackexchange.com/questions/2005378', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/217745/']","You can take $\mathbb{Z}/4\mathbb{Z}.$ This has characteristic $4$, the only prime is $(2)$ and the residue field $\mathbb{F}\_2$ is of characteristic $2$. + +EDIT: +You may also say something positive (but not really surprising either): + +> +> If $A$ is an integral domain such that all the residue fields are of equal characteristic $p$, then $\mathrm{char}(A)=p$. +> +> +> + +This is because of the prime ideal $(0)$: in this case, we have $A \subseteq \mathrm{Frac}(A)=\mathrm{Frac}(A/(0)),$ and the claim follows.","Have you think in $\mathbb{Z}\_{(p)}=\{\frac{a}{b}\mid p\nmid b\}$?. This ring has charateristic $0$. But it is a local ring, with unique maximal ideal $p\mathbb{Z}\_{(p)}$. So its residue field $\mathbb{Z}\_{(p)}/p\mathbb{Z}\_{(p)}$ is isomorphic to $\mathbb{Z}\_p$ the integeres modulo p." +236953,Can anyone tell me how to tell if the predictors I am using are collinear and can not be used in a `geeglm` model? What is the value and is calculating the correlation the correct way of determining it?,2016/09/26,"['https://stats.stackexchange.com/questions/236953', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/115530/']","You can start by looking at the Pearson pariwise correlations to get the strength and direction of the linear association between any two (continuous) predictors. This can give you some insights about the data. In R you can use: +`cor(dat[,names(dat)], use =""pairwise"", method = ""pearson"")` + +However, there is no exact threshold at which we can say that collinearity is too high (unless, of course, the Pearson correlation coefficient equals 1). If you try to fit a linear model, pairwise correlations are not the sole problem, we can have collinearity between more than two variables… We commonly evaluate multicollinearity through Variance Inflation Factors (VIFs). In R, after fitting the model we can use `vif(model)` from the package ‘car’. This gives the correlations between each predictor and all the other predictors used in the model. The rule of thumb is that VIF should not be larger than 10. If so, you remove the variable having the highest VIF, re-run the model and check again the VIF. + +It may be sometimes that the predictor that you need to remove (according to VIF) is your predictor of interest (this can happen when your aim is not prediction, but rather to identify how certain predictors affect the outcome variable). In that case, you keep your predictor and look at the Pearson pairwise correlation matrix to identify which predictors are highly correlated with your main predictor and remove them one by one while checking VIF.","If what you are after is a list of covariates that are not collinear, you can use `lm()` to do the job for you. +Here is an example (with simulated data): + +``` +# Simulate data +x1 <- runif(100) +x2 <- runif(100) +x3 <- x1 + x2 +y <- x1+x2+rnorm(100) +dat <- data.frame(y,x1,x2,x3) + +# Run lm() on your data +reg <- lm(y~.,dat) +# Here is the list! +intersect(names(dat),names(reg$coef[!is.na(reg$coef)])) + +```" +33487368,"Simple question that I have no idea of the answer to. + +Is there a way to use just one xaml page (at least one ""main"" page) to emulate multiple pages. i.e the same as: + +``` +this.Frame.Navigate(typeof(Page2), null); + +``` + +*but* using only one page? + +Thanks so much, any help is appreciated.",2015/11/02,"['https://Stackoverflow.com/questions/33487368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2463166/']","> +> Currently when creating a FormData object, a checked checkbox is added with a value of ""on"", and an unchecked checkbox is not passed at all. +> +> +> + +`on` is only used if the checkbox is missing a `value` attribute + +> +> Do I have to hack in some hidden inputs to properly set checkboxes +> +> +> + +No. That *is* properly handling checkboxes. It is how they have worked in forms since the form element was added to HTML. + +Test for the presence or absence of the checkbox in the code that handles it.","Try this: + +``` +var checkbox = $(""#myForm"").find(""input[type=checkbox]""); +$.each(checkbox, function(key, val) { + formData.append($(val).attr('name'), this.is(':checked')) +}); + +``` + +It always adds the field to `FormData` with either a value of `true` when checked, or `false` when unchecked." +33487368,"Simple question that I have no idea of the answer to. + +Is there a way to use just one xaml page (at least one ""main"" page) to emulate multiple pages. i.e the same as: + +``` +this.Frame.Navigate(typeof(Page2), null); + +``` + +*but* using only one page? + +Thanks so much, any help is appreciated.",2015/11/02,"['https://Stackoverflow.com/questions/33487368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2463166/']","> +> Currently when creating a FormData object, a checked checkbox is added with a value of ""on"", and an unchecked checkbox is not passed at all. +> +> +> + +`on` is only used if the checkbox is missing a `value` attribute + +> +> Do I have to hack in some hidden inputs to properly set checkboxes +> +> +> + +No. That *is* properly handling checkboxes. It is how they have worked in forms since the form element was added to HTML. + +Test for the presence or absence of the checkbox in the code that handles it.","I took a slightly different approach from the existing answers. I created my form data variable the standard jQuery way inside my form submit event handler: + +``` +var form = $(this).get(0); +var formData = new FormData(form); + +``` + +Based on [Quentin's answer](https://stackoverflow.com/a/33487482), saying that it is only set to 'on' when the `value` attribute is not available, I just added a document event on change to all checkboxes to set the value when the user checks or unchecks the input. + +``` +$(document).on(""change"", ""input[type='checkbox']"", function () { + var value = $(this).prop('checked'); + $(this).val(value); +}); + +``` + +When my form data object is created in the above way, all checked checkboxes now have the value of 'true' rather than 'on'. + +This worked quite nicely for my purposes and seems to me to be a pretty simple fix. Interestingly, having `value='false'` doesn't do anything as the input is just ignored and not added to the form data object if it is not checked. But obviously that still works." +33487368,"Simple question that I have no idea of the answer to. + +Is there a way to use just one xaml page (at least one ""main"" page) to emulate multiple pages. i.e the same as: + +``` +this.Frame.Navigate(typeof(Page2), null); + +``` + +*but* using only one page? + +Thanks so much, any help is appreciated.",2015/11/02,"['https://Stackoverflow.com/questions/33487368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2463166/']","Try this: + +``` +var checkbox = $(""#myForm"").find(""input[type=checkbox]""); +$.each(checkbox, function(key, val) { + formData.append($(val).attr('name'), this.is(':checked')) +}); + +``` + +It always adds the field to `FormData` with either a value of `true` when checked, or `false` when unchecked.","I took a slightly different approach from the existing answers. I created my form data variable the standard jQuery way inside my form submit event handler: + +``` +var form = $(this).get(0); +var formData = new FormData(form); + +``` + +Based on [Quentin's answer](https://stackoverflow.com/a/33487482), saying that it is only set to 'on' when the `value` attribute is not available, I just added a document event on change to all checkboxes to set the value when the user checks or unchecks the input. + +``` +$(document).on(""change"", ""input[type='checkbox']"", function () { + var value = $(this).prop('checked'); + $(this).val(value); +}); + +``` + +When my form data object is created in the above way, all checked checkboxes now have the value of 'true' rather than 'on'. + +This worked quite nicely for my purposes and seems to me to be a pretty simple fix. Interestingly, having `value='false'` doesn't do anything as the input is just ignored and not added to the form data object if it is not checked. But obviously that still works." +326104,"[![enter image description here](https://i.stack.imgur.com/Rdip2.jpg)](https://i.stack.imgur.com/Rdip2.jpg)Recently I got stuck witht the following problem. + +Imagine we have uniform a magnetic field which induction points upwards. The fields strength is steadily decreasing. If we put an iron coil perpendicular to the magnetic induction vector, then, obviously, there will be electric current induced in the coil. + +However, as I understand, the coil itself is only a 'marker' that displays the electric field lines that actually make the electrons move. It means that the elcetric field is there even when there is no coil. +Now the problem: +I can imagine some coils being close to each other. It will essentially mean, that it in one of them the current will go one way and in the other - the opposite. How can this possibly be? + +I looked at [this answer](https://physics.stackexchange.com/questions/8279/what-is-the-direction-of-the-induced-e-field-from-a-changing-uniform-magnetic-fi) as it is phrased very close to what I want and still I couldn't get the idea. Could the answer be presented in more layman terms .",2017/04/12,"['https://physics.stackexchange.com/questions/326104', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/89976/']","Since the Maxwell's equations are linear partial differential equations, you can compute the magnetic field due to multiple sources by superposition. + +A really important application relies on the superposition principle for magnetic fields is the Biot–Savart law i.e. the fact that the magnetic field is a vector sum of the field created by each infinitesimal section of the wire individually. + +                                              ![enter image description here](https://i.stack.imgur.com/j8HaR.png) + +$$\mathrm d\vec B = \frac{\mu\_0}{4\pi}\frac{I \; \mathrm d\vec l \times \vec R}{R^3}$$","You are correct, they follow superposition. The magnetic field is a vector field, and so they follow a vector sum when they are in a superposition. + +Maxwell's equations are linear ($\nabla \times$ and $\nabla \dot{}$ are linear operators) and it follows that solutions ($E$ and $B$) obey the superposition principle." +3200569,"**Short Version:** +How can it be geometrically shown that non-singular 2D linear transformations take circles to ellipses? + +*(Also, its probably important to state I'd prefer an explanation that doesn't use SVD, as I don't really understand it yet...although I see it everywhere)* + +**Long Version:** +Let's use the definition of an ellipse as being a circle stretched in two perpendicular directions. The two directions its stretched in will correspond to the two axes of the ellipse. + +We begin by defining the circle as the endpoints of all possible 2D unit vectors. The ellipse *(or at least I""m TOLD it's an ellipse)* is the shape drawn by the endpoints of all these vectors after they have all been transformed in the same way *(aka multiplied by the same nonsingular matrix $A$)*. + +1. For linear transformations represented by diagonal matrices, it's easy to see. We're just stretching the circle in the X and Y directions. +2. For linear transformations represented by symmetric matrices...its a little harder, but I can see the transformation because the eigenvectors of the symmetric matrix are perpendicular, and if we change to a basis where those eigenvectors are the basis vectors, the transformation can be represented by a diagonal matrix *(as for WHY symmetric matrices can be decomposed this way I don't yet really understand - but for the purpose of this question I'm just accepting that they can; I'm accepting that the eigenvectors of symmetric matrices are perpendicular to one another)*. + +So, just like diagonal matrices, symmetric matrices also correspond to stretching a unit circle in perpendicular directions - but unless the symmetric matrix is diagonal, these are perpendicular directions different from the X and Y directions. +3. Buuut...what about for nonsymmetric matrices? + +Thanks! + +--- + +**EDIT:** +--------- + +I've now learned of the polar decomposition of any real matrix, and that provides a beautiful explanation for why any real matrix takes a circle to an ellipse! + +$A=QS$, where $Q$ is an orthogonal matrix *(rotation)* and $S$ is a symmetric matrix *(stretching in the direction of the eigenvectors).* + +The symmetric matrix will definitely correspond to making an ellipse *(since it scales in orthogonal directions, although perhaps not our regular $x$ and $y$ directions)* and all the orthonormal matrix will do is rotate this ellipse. + +However, all the explanations I've seen so far that PROVE that polar decompositions of real matrices are **always** possible use an **algebraic** **explanation instead of a geometric one**...so they aren't really what I'm looking for. + +Thanks again!",2019/04/24,"['https://math.stackexchange.com/questions/3200569', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/493688/']","The equation of a circle is $x^2 + y^2 = r^2$, or in terms of vectors $(x,y) \pmatrix{x\cr y} = r^2$ An invertible linear transformation $T$ takes $\pmatrix{x\cr y}$ to $\pmatrix{X\cr Y} = T\pmatrix{x\cr y}$. Thus $\pmatrix{x\cr y\cr} = T^{-1} \pmatrix{X\cr Y}$, and $(x,y) = (X, Y) (T^{-1})^\top$. The equation becomes +$$(X, Y) (T^{-1})^\top T^{-1} \pmatrix{X\cr Y} = r^2 $$ +Note that $(T^{-1})^\top T^{-1}$ is a real symmetric matrix, so it can be diagonalized, and its eigenvalues are positive.","Every real square matrix has a [polar decomposition](https://en.wikipedia.org/wiki/Polar_decomposition) into the product of an orthogonal matrix $U$ and a positive-semidefinite (symmetric) matrix $P$. If the original matrix is nonsingular, then $P$ is positive-definite. In 2-D, orthogonal matrices represent either rotations or reflections, which are both isometries, so they don’t affect the shape of the transformed circle. As you’ve mentioned, $P$ can be orthogonally diagonalized, so it represents a stretch in some set of perpendicular directions. + +The existence of this decomposition is equivalent to the existence of the SVD, but can be shown without relying on the latter. In a similar vein, the SVD decomposes the matrix into the product of a rotation or reflection, a scaling, and another rotation or reflection. + +You might also have a look at the [Steiner generation of an ellipse](https://en.wikipedia.org/wiki/Ellipse#Steiner_generation). This uses intersecting line segments drawn between points on the sides of a parallelogram to generate ellipses, including circles. Affine transformations preserve incidence relationships (the image of the intersection of a pair of lines is the intersection of the lines’ images) and maps paralellograms to parallelograms, so the image of an ellipse under an affine transformation is another ellipse." +3200569,"**Short Version:** +How can it be geometrically shown that non-singular 2D linear transformations take circles to ellipses? + +*(Also, its probably important to state I'd prefer an explanation that doesn't use SVD, as I don't really understand it yet...although I see it everywhere)* + +**Long Version:** +Let's use the definition of an ellipse as being a circle stretched in two perpendicular directions. The two directions its stretched in will correspond to the two axes of the ellipse. + +We begin by defining the circle as the endpoints of all possible 2D unit vectors. The ellipse *(or at least I""m TOLD it's an ellipse)* is the shape drawn by the endpoints of all these vectors after they have all been transformed in the same way *(aka multiplied by the same nonsingular matrix $A$)*. + +1. For linear transformations represented by diagonal matrices, it's easy to see. We're just stretching the circle in the X and Y directions. +2. For linear transformations represented by symmetric matrices...its a little harder, but I can see the transformation because the eigenvectors of the symmetric matrix are perpendicular, and if we change to a basis where those eigenvectors are the basis vectors, the transformation can be represented by a diagonal matrix *(as for WHY symmetric matrices can be decomposed this way I don't yet really understand - but for the purpose of this question I'm just accepting that they can; I'm accepting that the eigenvectors of symmetric matrices are perpendicular to one another)*. + +So, just like diagonal matrices, symmetric matrices also correspond to stretching a unit circle in perpendicular directions - but unless the symmetric matrix is diagonal, these are perpendicular directions different from the X and Y directions. +3. Buuut...what about for nonsymmetric matrices? + +Thanks! + +--- + +**EDIT:** +--------- + +I've now learned of the polar decomposition of any real matrix, and that provides a beautiful explanation for why any real matrix takes a circle to an ellipse! + +$A=QS$, where $Q$ is an orthogonal matrix *(rotation)* and $S$ is a symmetric matrix *(stretching in the direction of the eigenvectors).* + +The symmetric matrix will definitely correspond to making an ellipse *(since it scales in orthogonal directions, although perhaps not our regular $x$ and $y$ directions)* and all the orthonormal matrix will do is rotate this ellipse. + +However, all the explanations I've seen so far that PROVE that polar decompositions of real matrices are **always** possible use an **algebraic** **explanation instead of a geometric one**...so they aren't really what I'm looking for. + +Thanks again!",2019/04/24,"['https://math.stackexchange.com/questions/3200569', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/493688/']","The equation of a circle is $x^2 + y^2 = r^2$, or in terms of vectors $(x,y) \pmatrix{x\cr y} = r^2$ An invertible linear transformation $T$ takes $\pmatrix{x\cr y}$ to $\pmatrix{X\cr Y} = T\pmatrix{x\cr y}$. Thus $\pmatrix{x\cr y\cr} = T^{-1} \pmatrix{X\cr Y}$, and $(x,y) = (X, Y) (T^{-1})^\top$. The equation becomes +$$(X, Y) (T^{-1})^\top T^{-1} \pmatrix{X\cr Y} = r^2 $$ +Note that $(T^{-1})^\top T^{-1}$ is a real symmetric matrix, so it can be diagonalized, and its eigenvalues are positive.","The answers on this thread are quite insightful but I am attempting here a rather very geometric answer, as the OP demanded so. For this I am going to use another interesting geometric interpretation of linear transformation (which is easier to imagine) + +An alternate geometric interpretation of (dimension-preserving) linear transformation is that it's a transformation such that *any line in original space is always transformed into a line* and origin is not shifted. + +Now imagine a freshly made pizza base/crust. Even more, let's make grids on it. + +Our job is now to transform it's shape such that all the grid lines (or any possible line) remain lines. So you see at best what we can do is \*stretch it with equal forces on opposite sides. You are free to choose where to stretch and Of course we can simply rotate it also after or before all the stretching. + +It's not difficult to imagine that we can only get an ellipse (or bigger circle if we stretched from all sides with equal force). + +Other interesting points: +(1): The direction of stretch is eigen vector and extent to which it is stretched is eigen value; +(2): Each rectangle from the gridlines is now parallelogram." +3200569,"**Short Version:** +How can it be geometrically shown that non-singular 2D linear transformations take circles to ellipses? + +*(Also, its probably important to state I'd prefer an explanation that doesn't use SVD, as I don't really understand it yet...although I see it everywhere)* + +**Long Version:** +Let's use the definition of an ellipse as being a circle stretched in two perpendicular directions. The two directions its stretched in will correspond to the two axes of the ellipse. + +We begin by defining the circle as the endpoints of all possible 2D unit vectors. The ellipse *(or at least I""m TOLD it's an ellipse)* is the shape drawn by the endpoints of all these vectors after they have all been transformed in the same way *(aka multiplied by the same nonsingular matrix $A$)*. + +1. For linear transformations represented by diagonal matrices, it's easy to see. We're just stretching the circle in the X and Y directions. +2. For linear transformations represented by symmetric matrices...its a little harder, but I can see the transformation because the eigenvectors of the symmetric matrix are perpendicular, and if we change to a basis where those eigenvectors are the basis vectors, the transformation can be represented by a diagonal matrix *(as for WHY symmetric matrices can be decomposed this way I don't yet really understand - but for the purpose of this question I'm just accepting that they can; I'm accepting that the eigenvectors of symmetric matrices are perpendicular to one another)*. + +So, just like diagonal matrices, symmetric matrices also correspond to stretching a unit circle in perpendicular directions - but unless the symmetric matrix is diagonal, these are perpendicular directions different from the X and Y directions. +3. Buuut...what about for nonsymmetric matrices? + +Thanks! + +--- + +**EDIT:** +--------- + +I've now learned of the polar decomposition of any real matrix, and that provides a beautiful explanation for why any real matrix takes a circle to an ellipse! + +$A=QS$, where $Q$ is an orthogonal matrix *(rotation)* and $S$ is a symmetric matrix *(stretching in the direction of the eigenvectors).* + +The symmetric matrix will definitely correspond to making an ellipse *(since it scales in orthogonal directions, although perhaps not our regular $x$ and $y$ directions)* and all the orthonormal matrix will do is rotate this ellipse. + +However, all the explanations I've seen so far that PROVE that polar decompositions of real matrices are **always** possible use an **algebraic** **explanation instead of a geometric one**...so they aren't really what I'm looking for. + +Thanks again!",2019/04/24,"['https://math.stackexchange.com/questions/3200569', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/493688/']","Every real square matrix has a [polar decomposition](https://en.wikipedia.org/wiki/Polar_decomposition) into the product of an orthogonal matrix $U$ and a positive-semidefinite (symmetric) matrix $P$. If the original matrix is nonsingular, then $P$ is positive-definite. In 2-D, orthogonal matrices represent either rotations or reflections, which are both isometries, so they don’t affect the shape of the transformed circle. As you’ve mentioned, $P$ can be orthogonally diagonalized, so it represents a stretch in some set of perpendicular directions. + +The existence of this decomposition is equivalent to the existence of the SVD, but can be shown without relying on the latter. In a similar vein, the SVD decomposes the matrix into the product of a rotation or reflection, a scaling, and another rotation or reflection. + +You might also have a look at the [Steiner generation of an ellipse](https://en.wikipedia.org/wiki/Ellipse#Steiner_generation). This uses intersecting line segments drawn between points on the sides of a parallelogram to generate ellipses, including circles. Affine transformations preserve incidence relationships (the image of the intersection of a pair of lines is the intersection of the lines’ images) and maps paralellograms to parallelograms, so the image of an ellipse under an affine transformation is another ellipse.","The answers on this thread are quite insightful but I am attempting here a rather very geometric answer, as the OP demanded so. For this I am going to use another interesting geometric interpretation of linear transformation (which is easier to imagine) + +An alternate geometric interpretation of (dimension-preserving) linear transformation is that it's a transformation such that *any line in original space is always transformed into a line* and origin is not shifted. + +Now imagine a freshly made pizza base/crust. Even more, let's make grids on it. + +Our job is now to transform it's shape such that all the grid lines (or any possible line) remain lines. So you see at best what we can do is \*stretch it with equal forces on opposite sides. You are free to choose where to stretch and Of course we can simply rotate it also after or before all the stretching. + +It's not difficult to imagine that we can only get an ellipse (or bigger circle if we stretched from all sides with equal force). + +Other interesting points: +(1): The direction of stretch is eigen vector and extent to which it is stretched is eigen value; +(2): Each rectangle from the gridlines is now parallelogram." +1726843,"When reading a PHP book I wanted to try my own (continue) example. +I made the following code but it doesn't work although everything seems to be ok + +``` +$num2 = 1; + + while ($num2 < 19) + { + if ($num2 == 15) { + continue; + } else { + echo ""Continue at 15 ("".$num2."").
""; + $num2++; + } + + } + +``` + +The output is + +``` +Continue at 15 (1). +Continue at 15 (2). +Continue at 15 (3). +Continue at 15 (4). +Continue at 15 (5). +Continue at 15 (6). +Continue at 15 (7). +Continue at 15 (8). +Continue at 15 (9). +Continue at 15 (10). +Continue at 15 (11). +Continue at 15 (12). +Continue at 15 (13). +Continue at 15 (14). + +Fatal error: Maximum execution time of 30 seconds exceeded in /var/www/php/continueandbreak.php on line 20 + +``` + +Line 20 is that line + +``` +if ($num2 == 15) { + +``` + +Would you please tell me what's wrong with my example ? +I am sorry for such a Noob question",2009/11/13,"['https://Stackoverflow.com/questions/1726843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/210142/']","if you don't increment `$num2` before the `continue` you will get into an infinite loop; + +``` +$num2 = 0; + +while ($num2 < 18) + { + $num2++; + if ($num2 == 15) { + continue; + } else { + echo ""Continue at 15 ("".$num2."").
""; + } + + } + +```","You don't even need continue there, your code equivalent to; + +``` +$num2 = 1; +while ($num2 < 19){ + if ($num2 != 15) { + echo ""Continue at 15 ("".$num2."").
""; + $num2++; + } +} + +``` + +If that's not what you're trying to achieve, you're using continue wrong." +1726843,"When reading a PHP book I wanted to try my own (continue) example. +I made the following code but it doesn't work although everything seems to be ok + +``` +$num2 = 1; + + while ($num2 < 19) + { + if ($num2 == 15) { + continue; + } else { + echo ""Continue at 15 ("".$num2."").
""; + $num2++; + } + + } + +``` + +The output is + +``` +Continue at 15 (1). +Continue at 15 (2). +Continue at 15 (3). +Continue at 15 (4). +Continue at 15 (5). +Continue at 15 (6). +Continue at 15 (7). +Continue at 15 (8). +Continue at 15 (9). +Continue at 15 (10). +Continue at 15 (11). +Continue at 15 (12). +Continue at 15 (13). +Continue at 15 (14). + +Fatal error: Maximum execution time of 30 seconds exceeded in /var/www/php/continueandbreak.php on line 20 + +``` + +Line 20 is that line + +``` +if ($num2 == 15) { + +``` + +Would you please tell me what's wrong with my example ? +I am sorry for such a Noob question",2009/11/13,"['https://Stackoverflow.com/questions/1726843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/210142/']","if you don't increment `$num2` before the `continue` you will get into an infinite loop; + +``` +$num2 = 0; + +while ($num2 < 18) + { + $num2++; + if ($num2 == 15) { + continue; + } else { + echo ""Continue at 15 ("".$num2."").
""; + } + + } + +```","in php, use **foreach** for arrays and **for** for looping + +``` +for($num = 1; $num < 19; $num++) { + if ($num != 15) { + echo ""Continue at 15 ("" . $num . "") .
""; + break; + } +} + +```" +1726843,"When reading a PHP book I wanted to try my own (continue) example. +I made the following code but it doesn't work although everything seems to be ok + +``` +$num2 = 1; + + while ($num2 < 19) + { + if ($num2 == 15) { + continue; + } else { + echo ""Continue at 15 ("".$num2."").
""; + $num2++; + } + + } + +``` + +The output is + +``` +Continue at 15 (1). +Continue at 15 (2). +Continue at 15 (3). +Continue at 15 (4). +Continue at 15 (5). +Continue at 15 (6). +Continue at 15 (7). +Continue at 15 (8). +Continue at 15 (9). +Continue at 15 (10). +Continue at 15 (11). +Continue at 15 (12). +Continue at 15 (13). +Continue at 15 (14). + +Fatal error: Maximum execution time of 30 seconds exceeded in /var/www/php/continueandbreak.php on line 20 + +``` + +Line 20 is that line + +``` +if ($num2 == 15) { + +``` + +Would you please tell me what's wrong with my example ? +I am sorry for such a Noob question",2009/11/13,"['https://Stackoverflow.com/questions/1726843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/210142/']","You don't even need continue there, your code equivalent to; + +``` +$num2 = 1; +while ($num2 < 19){ + if ($num2 != 15) { + echo ""Continue at 15 ("".$num2."").
""; + $num2++; + } +} + +``` + +If that's not what you're trying to achieve, you're using continue wrong.","in php, use **foreach** for arrays and **for** for looping + +``` +for($num = 1; $num < 19; $num++) { + if ($num != 15) { + echo ""Continue at 15 ("" . $num . "") .
""; + break; + } +} + +```" +14810602,"This is my code and it is not working correctly. I want to set `minDate` to the current date. How can I do it? + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } + +```",2013/02/11,"['https://Stackoverflow.com/questions/14810602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305280/']","You can use the `minDate` property, like this: + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + minDate: 0, // 0 days offset = today + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } +}); + +``` + +You can also specify a date, like this: + +``` +minDate: new Date(), // = today + +```","**Set minDate to current date in jQuery Datepicker :** + +``` +$(""input.DateFrom"").datepicker({ + minDate: new Date() +}); + +```" +14810602,"This is my code and it is not working correctly. I want to set `minDate` to the current date. How can I do it? + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } + +```",2013/02/11,"['https://Stackoverflow.com/questions/14810602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305280/']","You can specify minDate as today by adding `minDate: 0` to the options. + +``` +$(""input.DateFrom"").datepicker({ + minDate: 0, + ... +}); + +``` + +**Demo**: + +**Docs**: ","Use this one : + +``` + onSelect: function(dateText) { + $(""input#DateTo"").datepicker('option', 'minDate', dateText); + } + +``` + +This may be useful : +" +14810602,"This is my code and it is not working correctly. I want to set `minDate` to the current date. How can I do it? + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } + +```",2013/02/11,"['https://Stackoverflow.com/questions/14810602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305280/']","You can specify minDate as today by adding `minDate: 0` to the options. + +``` +$(""input.DateFrom"").datepicker({ + minDate: 0, + ... +}); + +``` + +**Demo**: + +**Docs**: ","You can use the `minDate` property, like this: + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + minDate: 0, // 0 days offset = today + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } +}); + +``` + +You can also specify a date, like this: + +``` +minDate: new Date(), // = today + +```" +14810602,"This is my code and it is not working correctly. I want to set `minDate` to the current date. How can I do it? + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } + +```",2013/02/11,"['https://Stackoverflow.com/questions/14810602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305280/']","You can use the `minDate` property, like this: + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + minDate: 0, // 0 days offset = today + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } +}); + +``` + +You can also specify a date, like this: + +``` +minDate: new Date(), // = today + +```","Use this one : + +``` + onSelect: function(dateText) { + $(""input#DateTo"").datepicker('option', 'minDate', dateText); + } + +``` + +This may be useful : +" +14810602,"This is my code and it is not working correctly. I want to set `minDate` to the current date. How can I do it? + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } + +```",2013/02/11,"['https://Stackoverflow.com/questions/14810602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305280/']","You can specify minDate as today by adding `minDate: 0` to the options. + +``` +$(""input.DateFrom"").datepicker({ + minDate: 0, + ... +}); + +``` + +**Demo**: + +**Docs**: ","**Set minDate to current date in jQuery Datepicker :** + +``` +$(""input.DateFrom"").datepicker({ + minDate: new Date() +}); + +```" +14810602,"This is my code and it is not working correctly. I want to set `minDate` to the current date. How can I do it? + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } + +```",2013/02/11,"['https://Stackoverflow.com/questions/14810602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305280/']","Use this one : + +``` + onSelect: function(dateText) { + $(""input#DateTo"").datepicker('option', 'minDate', dateText); + } + +``` + +This may be useful : +","minDate property for current date works on for both -> minDate:""yy-mm-dd"" or minDate:0" +14810602,"This is my code and it is not working correctly. I want to set `minDate` to the current date. How can I do it? + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } + +```",2013/02/11,"['https://Stackoverflow.com/questions/14810602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305280/']","You can specify minDate as today by adding `minDate: 0` to the options. + +``` +$(""input.DateFrom"").datepicker({ + minDate: 0, + ... +}); + +``` + +**Demo**: + +**Docs**: ","minDate property for current date works on for both -> minDate:""yy-mm-dd"" or minDate:0" +14810602,"This is my code and it is not working correctly. I want to set `minDate` to the current date. How can I do it? + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } + +```",2013/02/11,"['https://Stackoverflow.com/questions/14810602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305280/']","Use this one : + +``` + onSelect: function(dateText) { + $(""input#DateTo"").datepicker('option', 'minDate', dateText); + } + +``` + +This may be useful : +","**Set minDate to current date in jQuery Datepicker :** + +``` +$(""input.DateFrom"").datepicker({ + minDate: new Date() +}); + +```" +14810602,"This is my code and it is not working correctly. I want to set `minDate` to the current date. How can I do it? + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } + +```",2013/02/11,"['https://Stackoverflow.com/questions/14810602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305280/']","You can use the `minDate` property, like this: + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + minDate: 0, // 0 days offset = today + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } +}); + +``` + +You can also specify a date, like this: + +``` +minDate: new Date(), // = today + +```","I set starting date using this method, because aforesaid or other codes didn't work for me + +```js +$(document).ready(function() { + $('#dateFrm').datepicker('setStartDate', new Date(yyyy, dd, MM)); + }); +```" +14810602,"This is my code and it is not working correctly. I want to set `minDate` to the current date. How can I do it? + +``` +$(""input.DateFrom"").datepicker({ + changeMonth: true, + changeYear: true, + dateFormat: 'yy-mm-dd', + maxDate: 'today', + onSelect: function(dateText) { + $sD = new Date(dateText); + $(""input#DateTo"").datepicker('option', 'minDate', min); + } + +```",2013/02/11,"['https://Stackoverflow.com/questions/14810602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1305280/']","You can specify minDate as today by adding `minDate: 0` to the options. + +``` +$(""input.DateFrom"").datepicker({ + minDate: 0, + ... +}); + +``` + +**Demo**: + +**Docs**: ","can also use: + +``` +$(""input.DateFrom"").datepicker({ + minDate: 'today' +}); + +```" +55409656,"I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset + +I have some error in my code I don't know who I can fix it. + +code: +[enter image description here][1] +[enter image description here][2]",2019/03/29,"['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']","To add to `cglacet`'s answer - if one wants to detect whether a loop is running and adjust automatically (ie run `main()` on the existing loop, otherwise `asyncio.run()`), here is a snippet that may prove useful: + +```py +# async def main(): +# ... + +try: + loop = asyncio.get_running_loop() +except RuntimeError: # 'RuntimeError: There is no current event loop...' + loop = None + +if loop and loop.is_running(): + print('Async event loop already running. Adding coroutine to the event loop.') + tsk = loop.create_task(main()) + # ^-- https://docs.python.org/3/library/asyncio-task.html#task-object + # Optionally, a callback function can be executed when the coroutine completes + tsk.add_done_callback( + lambda t: print(f'Task done with result={t.result()} << return val of main()')) +else: + print('Starting new event loop') + result = asyncio.run(main()) + +```","I found the [`unsync`](https://github.com/alex-sherman/unsync) package useful for writing code that behaves the same way in a Python script and the Jupyter REPL. + +```py +import asyncio +from unsync import unsync + +@unsync +async def demo_async_fn(): + await asyncio.sleep(0.1) + return ""done!"" + +print(demo_async_fn().result()) + +```" +55409656,"I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset + +I have some error in my code I don't know who I can fix it. + +code: +[enter image description here][1] +[enter image description here][2]",2019/03/29,"['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']","Just use this: + + + +``` +import nest_asyncio +nest_asyncio.apply() + +```","I found the [`unsync`](https://github.com/alex-sherman/unsync) package useful for writing code that behaves the same way in a Python script and the Jupyter REPL. + +```py +import asyncio +from unsync import unsync + +@unsync +async def demo_async_fn(): + await asyncio.sleep(0.1) + return ""done!"" + +print(demo_async_fn().result()) + +```" +55409656,"I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset + +I have some error in my code I don't know who I can fix it. + +code: +[enter image description here][1] +[enter image description here][2]",2019/03/29,"['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']","To add to `cglacet`'s answer - if one wants to detect whether a loop is running and adjust automatically (ie run `main()` on the existing loop, otherwise `asyncio.run()`), here is a snippet that may prove useful: + +```py +# async def main(): +# ... + +try: + loop = asyncio.get_running_loop() +except RuntimeError: # 'RuntimeError: There is no current event loop...' + loop = None + +if loop and loop.is_running(): + print('Async event loop already running. Adding coroutine to the event loop.') + tsk = loop.create_task(main()) + # ^-- https://docs.python.org/3/library/asyncio-task.html#task-object + # Optionally, a callback function can be executed when the coroutine completes + tsk.add_done_callback( + lambda t: print(f'Task done with result={t.result()} << return val of main()')) +else: + print('Starting new event loop') + result = asyncio.run(main()) + +```","Just use this: + + + +``` +import nest_asyncio +nest_asyncio.apply() + +```" +55409656,"I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset + +I have some error in my code I don't know who I can fix it. + +code: +[enter image description here][1] +[enter image description here][2]",2019/03/29,"['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']","Combining the methods from Pankaj Sharma and Jean Monet, I wrote the following snippet that acts as asyncio.run (with slightly different syntax), but also works within a Jupyter notebook. + +``` +class RunThread(threading.Thread): + def __init__(self, func, args, kwargs): + self.func = func + self.args = args + self.kwargs = kwargs + self.result = None + super().__init__() + + def run(self): + self.result = asyncio.run(self.func(*self.args, **self.kwargs)) + +def run_async(func, *args, **kwargs): + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + if loop and loop.is_running(): + thread = RunThread(func, args, kwargs) + thread.start() + thread.join() + return thread.result + else: + return asyncio.run(func(*args, **kwargs)) + +``` + +Usage: + +``` +async def test(name): + await asyncio.sleep(5) + return f""hello {name}"" + +run_async(test, ""user"") # blocks for 5 seconds and returns ""hello user"" + +```","I found the [`unsync`](https://github.com/alex-sherman/unsync) package useful for writing code that behaves the same way in a Python script and the Jupyter REPL. + +```py +import asyncio +from unsync import unsync + +@unsync +async def demo_async_fn(): + await asyncio.sleep(0.1) + return ""done!"" + +print(demo_async_fn().result()) + +```" +55409656,"I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset + +I have some error in my code I don't know who I can fix it. + +code: +[enter image description here][1] +[enter image description here][2]",2019/03/29,"['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']","Just use this: + + + +``` +import nest_asyncio +nest_asyncio.apply() + +```","Combining the methods from Pankaj Sharma and Jean Monet, I wrote the following snippet that acts as asyncio.run (with slightly different syntax), but also works within a Jupyter notebook. + +``` +class RunThread(threading.Thread): + def __init__(self, func, args, kwargs): + self.func = func + self.args = args + self.kwargs = kwargs + self.result = None + super().__init__() + + def run(self): + self.result = asyncio.run(self.func(*self.args, **self.kwargs)) + +def run_async(func, *args, **kwargs): + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + if loop and loop.is_running(): + thread = RunThread(func, args, kwargs) + thread.start() + thread.join() + return thread.result + else: + return asyncio.run(func(*args, **kwargs)) + +``` + +Usage: + +``` +async def test(name): + await asyncio.sleep(5) + return f""hello {name}"" + +run_async(test, ""user"") # blocks for 5 seconds and returns ""hello user"" + +```" +55409656,"I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset + +I have some error in my code I don't know who I can fix it. + +code: +[enter image description here][1] +[enter image description here][2]",2019/03/29,"['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']","The [`asyncio.run()`](https://docs.python.org/3.7/library/asyncio-task.html#asyncio.run) documentation says: + +> +> This function [cannot](https://github.com/python/cpython/blob/3.8/Lib/asyncio/runners.py#L32-L34) be called when another asyncio event loop is running in the same thread. +> +> +> + +In your case, jupyter ([IPython ≥ 7.0](https://blog.jupyter.org/ipython-7-0-async-repl-a35ce050f7f7)) is already running an event loop: + +> +> You can now use async/await at the top level in the IPython terminal and in the notebook, it should — in most of the cases — “just work”. Update IPython to version 7+, IPykernel to version 5+, and you’re off to the races. +> +> +> + +Therefore you don't need to start the event loop yourself and can instead call `await main(url)` directly, even if your code lies outside any asynchronous function. + +**Jupyter / IPython** + +```py +async def main(): + print(1) + +await main() + +``` + +**Python (≥ 3.7) or older versions of IPython** + +```py +import asyncio + +async def main(): + print(1) + +asyncio.run(main()) + +``` + +In your code that would give: + +```py +url = ['url1', 'url2'] +result = await main(url) + +for text in result: + pass # text contains your html (text) response + +``` + +**Caution** + +There is a [slight difference](https://ipython.readthedocs.io/en/stable/interactive/autoawait.html#difference-between-terminal-ipython-and-ipykernel) on how Jupyter uses the loop compared to IPython.","Combining the methods from Pankaj Sharma and Jean Monet, I wrote the following snippet that acts as asyncio.run (with slightly different syntax), but also works within a Jupyter notebook. + +``` +class RunThread(threading.Thread): + def __init__(self, func, args, kwargs): + self.func = func + self.args = args + self.kwargs = kwargs + self.result = None + super().__init__() + + def run(self): + self.result = asyncio.run(self.func(*self.args, **self.kwargs)) + +def run_async(func, *args, **kwargs): + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + if loop and loop.is_running(): + thread = RunThread(func, args, kwargs) + thread.start() + thread.join() + return thread.result + else: + return asyncio.run(func(*args, **kwargs)) + +``` + +Usage: + +``` +async def test(name): + await asyncio.sleep(5) + return f""hello {name}"" + +run_async(test, ""user"") # blocks for 5 seconds and returns ""hello user"" + +```" +55409656,"I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset + +I have some error in my code I don't know who I can fix it. + +code: +[enter image description here][1] +[enter image description here][2]",2019/03/29,"['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']","The [`asyncio.run()`](https://docs.python.org/3.7/library/asyncio-task.html#asyncio.run) documentation says: + +> +> This function [cannot](https://github.com/python/cpython/blob/3.8/Lib/asyncio/runners.py#L32-L34) be called when another asyncio event loop is running in the same thread. +> +> +> + +In your case, jupyter ([IPython ≥ 7.0](https://blog.jupyter.org/ipython-7-0-async-repl-a35ce050f7f7)) is already running an event loop: + +> +> You can now use async/await at the top level in the IPython terminal and in the notebook, it should — in most of the cases — “just work”. Update IPython to version 7+, IPykernel to version 5+, and you’re off to the races. +> +> +> + +Therefore you don't need to start the event loop yourself and can instead call `await main(url)` directly, even if your code lies outside any asynchronous function. + +**Jupyter / IPython** + +```py +async def main(): + print(1) + +await main() + +``` + +**Python (≥ 3.7) or older versions of IPython** + +```py +import asyncio + +async def main(): + print(1) + +asyncio.run(main()) + +``` + +In your code that would give: + +```py +url = ['url1', 'url2'] +result = await main(url) + +for text in result: + pass # text contains your html (text) response + +``` + +**Caution** + +There is a [slight difference](https://ipython.readthedocs.io/en/stable/interactive/autoawait.html#difference-between-terminal-ipython-and-ipykernel) on how Jupyter uses the loop compared to IPython.","Just use this: + + + +``` +import nest_asyncio +nest_asyncio.apply() + +```" +55409656,"I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset + +I have some error in my code I don't know who I can fix it. + +code: +[enter image description here][1] +[enter image description here][2]",2019/03/29,"['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']","Combining the methods from Pankaj Sharma and Jean Monet, I wrote the following snippet that acts as asyncio.run (with slightly different syntax), but also works within a Jupyter notebook. + +``` +class RunThread(threading.Thread): + def __init__(self, func, args, kwargs): + self.func = func + self.args = args + self.kwargs = kwargs + self.result = None + super().__init__() + + def run(self): + self.result = asyncio.run(self.func(*self.args, **self.kwargs)) + +def run_async(func, *args, **kwargs): + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + if loop and loop.is_running(): + thread = RunThread(func, args, kwargs) + thread.start() + thread.join() + return thread.result + else: + return asyncio.run(func(*args, **kwargs)) + +``` + +Usage: + +``` +async def test(name): + await asyncio.sleep(5) + return f""hello {name}"" + +run_async(test, ""user"") # blocks for 5 seconds and returns ""hello user"" + +```","As cglacet mentioned that documentation says + +> +> This function cannot be called when another asyncio event loop is +> running in the same thread. +> +> +> + +You can use another thread i.e - + +``` +class ResolveThread(threading.Thread): + def __init__(self,result1,fun,url): + self.result1= result1 + self.fun = fun + self.url = url + threading.Thread.__init__(self) + def run(self): + result1[0] = asyncio.run(self.fun(self.url)) + +result1 = [None] +sp = ResolveThread(result1) +sp.start() +sp.join() # connect main thread +result = result1[0] + +```" +55409656,"I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset + +I have some error in my code I don't know who I can fix it. + +code: +[enter image description here][1] +[enter image description here][2]",2019/03/29,"['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']","The [`asyncio.run()`](https://docs.python.org/3.7/library/asyncio-task.html#asyncio.run) documentation says: + +> +> This function [cannot](https://github.com/python/cpython/blob/3.8/Lib/asyncio/runners.py#L32-L34) be called when another asyncio event loop is running in the same thread. +> +> +> + +In your case, jupyter ([IPython ≥ 7.0](https://blog.jupyter.org/ipython-7-0-async-repl-a35ce050f7f7)) is already running an event loop: + +> +> You can now use async/await at the top level in the IPython terminal and in the notebook, it should — in most of the cases — “just work”. Update IPython to version 7+, IPykernel to version 5+, and you’re off to the races. +> +> +> + +Therefore you don't need to start the event loop yourself and can instead call `await main(url)` directly, even if your code lies outside any asynchronous function. + +**Jupyter / IPython** + +```py +async def main(): + print(1) + +await main() + +``` + +**Python (≥ 3.7) or older versions of IPython** + +```py +import asyncio + +async def main(): + print(1) + +asyncio.run(main()) + +``` + +In your code that would give: + +```py +url = ['url1', 'url2'] +result = await main(url) + +for text in result: + pass # text contains your html (text) response + +``` + +**Caution** + +There is a [slight difference](https://ipython.readthedocs.io/en/stable/interactive/autoawait.html#difference-between-terminal-ipython-and-ipykernel) on how Jupyter uses the loop compared to IPython.","As cglacet mentioned that documentation says + +> +> This function cannot be called when another asyncio event loop is +> running in the same thread. +> +> +> + +You can use another thread i.e - + +``` +class ResolveThread(threading.Thread): + def __init__(self,result1,fun,url): + self.result1= result1 + self.fun = fun + self.url = url + threading.Thread.__init__(self) + def run(self): + result1[0] = asyncio.run(self.fun(self.url)) + +result1 = [None] +sp = ResolveThread(result1) +sp.start() +sp.join() # connect main thread +result = result1[0] + +```" +55409656,"I have a dataset in CSV file and all data is a numeric attribute, I want to apply k-Nearest Neighbors in my dataset + +I have some error in my code I don't know who I can fix it. + +code: +[enter image description here][1] +[enter image description here][2]",2019/03/29,"['https://Stackoverflow.com/questions/55409656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11273598/']","To add to `cglacet`'s answer - if one wants to detect whether a loop is running and adjust automatically (ie run `main()` on the existing loop, otherwise `asyncio.run()`), here is a snippet that may prove useful: + +```py +# async def main(): +# ... + +try: + loop = asyncio.get_running_loop() +except RuntimeError: # 'RuntimeError: There is no current event loop...' + loop = None + +if loop and loop.is_running(): + print('Async event loop already running. Adding coroutine to the event loop.') + tsk = loop.create_task(main()) + # ^-- https://docs.python.org/3/library/asyncio-task.html#task-object + # Optionally, a callback function can be executed when the coroutine completes + tsk.add_done_callback( + lambda t: print(f'Task done with result={t.result()} << return val of main()')) +else: + print('Starting new event loop') + result = asyncio.run(main()) + +```","Combining the methods from Pankaj Sharma and Jean Monet, I wrote the following snippet that acts as asyncio.run (with slightly different syntax), but also works within a Jupyter notebook. + +``` +class RunThread(threading.Thread): + def __init__(self, func, args, kwargs): + self.func = func + self.args = args + self.kwargs = kwargs + self.result = None + super().__init__() + + def run(self): + self.result = asyncio.run(self.func(*self.args, **self.kwargs)) + +def run_async(func, *args, **kwargs): + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + if loop and loop.is_running(): + thread = RunThread(func, args, kwargs) + thread.start() + thread.join() + return thread.result + else: + return asyncio.run(func(*args, **kwargs)) + +``` + +Usage: + +``` +async def test(name): + await asyncio.sleep(5) + return f""hello {name}"" + +run_async(test, ""user"") # blocks for 5 seconds and returns ""hello user"" + +```" +11422517,"I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. + +``` +product color size +------- ------- ------- +id id id +unique_id id_product (FK from product) id_product (FK from version) +stock unique_id id_version (FK from version) +title stock unique_id + stock + +``` + +The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. + +It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. + +As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: + +``` +select title, stock +from product +where unique_id = 10 + +UNION + +select p.title, c.stock +from color c +join product p on c.id_product = p.id +where c.unique_id = 10 + +UNION + +select p.title, s.stock +from size s +join product p on s.id_product = p.id +where s.unique_id = 10; + +``` + +Is there a better way to do this? Thanks for any suggestion! + +**EDIT 1** + +Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: + +1) As `unique_id` has indexes in all tables, i will get a good performance + +2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join + +``` +SELECT + + p.title, + ps.stock + +FROM ( + + select id as id_product, stock + from product + where unique_id = 10 + + UNION + + select id_product, stock + from color + where unique_id = 10 + + UNION + + select id_product, stock + from size + where unique_id = 10 + +) AS ps + +JOIN product p ON ps.id_product = p.id; + +```",2012/07/10,"['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']","### PL/pgSQL function + +To solve the problem at hand, a plpgsql function like the following should be faster: + +``` +CREATE OR REPLACE FUNCTION func(int) + RETURNS TABLE (title text, stock int) LANGUAGE plpgsql AS +$BODY$ +BEGIN + +RETURN QUERY +SELECT p.title, p.stock +FROM product p +WHERE p.unique_id = $1; -- Put the most likely table first. + +IF NOT FOUND THEN + RETURN QUERY + SELECT p.title, c.stock + FROM color c + JOIN product p ON c.id_product = p.id + WHERE c.unique_id = $1; +END; + +IF NOT FOUND THEN + RETURN QUERY + SELECT p.title, s.stock + FROM size s + JOIN product p ON s.id_product = p.id + WHERE s.unique_id = $1; +END IF; + +END; +$BODY$; + +``` + +Updated function with table-qualified column names to avoid naming conflicts with `OUT` parameters. + +`RETURNS TABLE` requires PostgreSQL 8.4, `RETURN QUERY` requires version 8.2. You can substitute both for older versions. + +It goes without saying that you need to **index** the columns `unique_id` of every involved table. `id` should be indexed automatically, being the primary key. + +--- + +### Redesign + +Ideally, you can tell which table from the ID alone. You could keep using one common sequence, but add `100000000` for the first table, `200000000` for the second and `300000000` for the third - or whatever suits your needs. This way, the least significant part of the number is easily distinguishable. + +A plain integer spans numbers from -2147483648 to +2147483647, move to [`bigint`](http://www.postgresql.org/docs/current/interactive/datatype-numeric.html#DATATYPE-INT) if that's not enough for you. I would stick to `integer` IDs, though, if possible. They are smaller and faster than `bigint` or `text`. + +--- + +### CTEs (experimental!) + +If you cannot create a function for some reason, this pure SQL solution might do a similar trick: + +``` +WITH x(uid) AS (SELECT 10) -- provide unique_id here + , a AS ( + SELECT title, stock + FROM x, product + WHERE unique_id = x.uid + ) + , b AS ( + SELECT p.title, c.stock + FROM x, color c + JOIN product p ON c.id_product = p.id + WHERE NOT EXISTS (SELECT 1 FROM a) + AND c.unique_id = x.uid + ) + , c AS ( + SELECT p.title, s.stock + FROM x, size s + JOIN product p ON s.id_product = p.id + WHERE NOT EXISTS (SELECT 1 FROM b) + AND s.unique_id = x.uid + ) +SELECT * FROM a +UNION ALL +SELECT * FROM b +UNION ALL +SELECT * FROM c; + +``` + +I am *not sure* whether it avoids additional scans like I hope. Would have to be tested. This query requires at least PostgreSQL 8.4. + +--- + +### Upgrade! + +As I just learned, the OP runs on PostgreSQL 8.1. + +**Upgrading alone** would speed up the operation a lot. + +--- + +### Query for PostgreSQL 8.1 + +As you are limited in your options, and a plpgsql function is not possible, this function should perform better than the one you have. Test with [`EXPLAIN ANALYZE`](http://www.postgresql.org/docs/8.1/interactive/sql-explain.html) - available in v8.1. + +``` +SELECT title, stock +FROM product +WHERE unique_id = 10 + +UNION ALL +SELECT p.title, ps.stock +FROM product p +JOIN ( + SELECT id_product, stock + FROM color + WHERE unique_id = 10 + + UNION ALL + SELECT id_product, stock + FROM size + WHERE unique_id = 10 + ) ps ON ps.id_product = p.id; + +```","There's an easier way to generate unique IDs using three separate auto\_increment columns. Just prepend a letter to the ID to uniquify it: + +Colors: + +``` + C0000001 + C0000002 + C0000003 + +``` + +Sizes: + +``` + S0000001 + S0000002 + S0000003 + ... + +``` + +Products: + +``` + P0000001 + P0000002 + P0000003 + ... + +``` + +A few advantages: + +* You don't need to serialize creation of ids across tables to ensure uniqueness. This will give better performance. +* You don't actually need to store the letter in the table. All IDs in the same table start with the same letter, so you only need to store the number. This means that you can use an ordinary `auto_increment` column to generate your IDs. +* If you have an ID you only need to check the first character to see which table it can be found in. You don't even need to make a query to the database if you just want to know whether it's a product ID or a size ID. + +A disadvantage: + +* It's no longer a number. But you can get around that by using 1,2,3 instead of C,S,P." +11422517,"I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. + +``` +product color size +------- ------- ------- +id id id +unique_id id_product (FK from product) id_product (FK from version) +stock unique_id id_version (FK from version) +title stock unique_id + stock + +``` + +The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. + +It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. + +As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: + +``` +select title, stock +from product +where unique_id = 10 + +UNION + +select p.title, c.stock +from color c +join product p on c.id_product = p.id +where c.unique_id = 10 + +UNION + +select p.title, s.stock +from size s +join product p on s.id_product = p.id +where s.unique_id = 10; + +``` + +Is there a better way to do this? Thanks for any suggestion! + +**EDIT 1** + +Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: + +1) As `unique_id` has indexes in all tables, i will get a good performance + +2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join + +``` +SELECT + + p.title, + ps.stock + +FROM ( + + select id as id_product, stock + from product + where unique_id = 10 + + UNION + + select id_product, stock + from color + where unique_id = 10 + + UNION + + select id_product, stock + from size + where unique_id = 10 + +) AS ps + +JOIN product p ON ps.id_product = p.id; + +```",2012/07/10,"['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']","I think it's time for a redesign. + +You have things that you're using as bar codes for items that are basically all the same in one respect (they are SerialNumberItems), but have been split into multiple tables because they are different in other respects. + +I have several ideas for you: + +Change the Defaults +------------------- + +Just make each product required to have one color ""no color"" and one size ""no size"". Then you can query any table you want to find the info you need. + +SuperType/SubType +----------------- + +Without too much modification you could use the supertype/subtype database design pattern. + +In it, there is a parent table where all the distinct detail-level identifiers live, and the shared columns of the subtype tables go in the supertype table (the ways that all the items are the same). There is one subtype table for each different way that the items are distinct. If mutual exclusivity of the subtype is required (you can have a Color or a Size but not both), then the parent table is given a TypeID column and the subtype tables have an FK to both the ParentID and the TypeID. Looking at your design, in fact you would not use mutual exclusivity. + +If you use the pattern of a supertype table, you do have the issue of having to insert in two parts, first to the supertype, then the subtype. Deleting also requires deleting in reverse order. But you get a great benefit of being able to get basic information such as Title and Stock out of the supertype table with a single query. + +You could even create schema-bound views for each subtype, with instead-of triggers that convert inserts, updates, and deletes into operations on the base table + child table. + +A Bigger Redesign +----------------- + +You could completely change how Colors and Sizes are related to products. + +First, your patterns of ""has-a"" are these: + +* Product (has nothing) +* Product->Color +* Product->Size +* Product->Color->Size + +There is a problem here. Clearly Product is the main item that has other things (colors and sizes) but colors don't have sizes! That is an arbitrary assignment. You may as well have said that Sizes have Colors--it doesn't make a difference. This reveals that your table design may not be best, as you're trying to model orthogonal data in a parent-child type of relationship. Really, products have a ColorAndSize. + +Furthermore, when a product comes in colors and sizes, what does the `uniqueid` in the Color table mean? Can such a product be ordered without a size, having only a color? This design is assigning a unique ID to something that (it seems to me) should never be allowed to be ordered--but you can't find this information out from the Color table, you have to compare the Color and Size tables first. It is a problem. + +I would design this as: Table `Product`. Table `Size` listing all distinct sizes possible for any product ever. Table `Color` listing all distinct colors possible for any product ever. And table `OrderableProduct` that has columns `ProductId`, `ColorID`, `SizeID`, and `UniqueID` (your bar code value). Additionally, each product must have one color and one size or it doesn't exist. + +Basically, Color and Size are like X and Y coordinates into a grid; you are filling in the boxes that are allowable combinations. Which one is the row and which the column is irrelevant. Certainly, one is not a child of the other. + +If there are any reasonable rules, in general, about what colors or sizes can be applied to various sub-groups of products, there might be utility in a ProductType table and a ProductTypeOrderables table that, when creating a new product, could populate the OrderableProduct table with the standard set—it could still be customized but might be easier to modify than to create anew. Or, it could define the range of colors and sizes that are allowable. You might need separate ProductTypeAllowedColor and ProductTypeAllowedSize tables. For example, if you are selling T-shirts, you'd want to allow XXXS, XXS, XS, S, M, L, XL, XXL, XXXL, and XXXXL, even if most products never use all those sizes. But for soft drinks, the sizes might be 6-pack 8oz, 24-pack 8oz, 2 liter, and so on, even if each soft drink is not offered in that size (and soft drinks don't have colors). + +In this new scheme, you only have one table to query to find the correct orderable product. With proper indexes, it should be blazing fast. + +Your Question +------------- + +You asked: + +> +> in PostgreSQL, so do you think if i use indexes on unique\_id i will get a satisfactory performance? +> +> +> + +Any column or set of columns that you use to repeatedly look up data must have an index! Any other pattern will result in a full table scan each time, which will be awful performance. I am sure that these indexes will make your queries lightning fast as it will take only one leaf-level read per table.","There's an easier way to generate unique IDs using three separate auto\_increment columns. Just prepend a letter to the ID to uniquify it: + +Colors: + +``` + C0000001 + C0000002 + C0000003 + +``` + +Sizes: + +``` + S0000001 + S0000002 + S0000003 + ... + +``` + +Products: + +``` + P0000001 + P0000002 + P0000003 + ... + +``` + +A few advantages: + +* You don't need to serialize creation of ids across tables to ensure uniqueness. This will give better performance. +* You don't actually need to store the letter in the table. All IDs in the same table start with the same letter, so you only need to store the number. This means that you can use an ordinary `auto_increment` column to generate your IDs. +* If you have an ID you only need to check the first character to see which table it can be found in. You don't even need to make a query to the database if you just want to know whether it's a product ID or a size ID. + +A disadvantage: + +* It's no longer a number. But you can get around that by using 1,2,3 instead of C,S,P." +11422517,"I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. + +``` +product color size +------- ------- ------- +id id id +unique_id id_product (FK from product) id_product (FK from version) +stock unique_id id_version (FK from version) +title stock unique_id + stock + +``` + +The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. + +It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. + +As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: + +``` +select title, stock +from product +where unique_id = 10 + +UNION + +select p.title, c.stock +from color c +join product p on c.id_product = p.id +where c.unique_id = 10 + +UNION + +select p.title, s.stock +from size s +join product p on s.id_product = p.id +where s.unique_id = 10; + +``` + +Is there a better way to do this? Thanks for any suggestion! + +**EDIT 1** + +Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: + +1) As `unique_id` has indexes in all tables, i will get a good performance + +2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join + +``` +SELECT + + p.title, + ps.stock + +FROM ( + + select id as id_product, stock + from product + where unique_id = 10 + + UNION + + select id_product, stock + from color + where unique_id = 10 + + UNION + + select id_product, stock + from size + where unique_id = 10 + +) AS ps + +JOIN product p ON ps.id_product = p.id; + +```",2012/07/10,"['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']","### PL/pgSQL function + +To solve the problem at hand, a plpgsql function like the following should be faster: + +``` +CREATE OR REPLACE FUNCTION func(int) + RETURNS TABLE (title text, stock int) LANGUAGE plpgsql AS +$BODY$ +BEGIN + +RETURN QUERY +SELECT p.title, p.stock +FROM product p +WHERE p.unique_id = $1; -- Put the most likely table first. + +IF NOT FOUND THEN + RETURN QUERY + SELECT p.title, c.stock + FROM color c + JOIN product p ON c.id_product = p.id + WHERE c.unique_id = $1; +END; + +IF NOT FOUND THEN + RETURN QUERY + SELECT p.title, s.stock + FROM size s + JOIN product p ON s.id_product = p.id + WHERE s.unique_id = $1; +END IF; + +END; +$BODY$; + +``` + +Updated function with table-qualified column names to avoid naming conflicts with `OUT` parameters. + +`RETURNS TABLE` requires PostgreSQL 8.4, `RETURN QUERY` requires version 8.2. You can substitute both for older versions. + +It goes without saying that you need to **index** the columns `unique_id` of every involved table. `id` should be indexed automatically, being the primary key. + +--- + +### Redesign + +Ideally, you can tell which table from the ID alone. You could keep using one common sequence, but add `100000000` for the first table, `200000000` for the second and `300000000` for the third - or whatever suits your needs. This way, the least significant part of the number is easily distinguishable. + +A plain integer spans numbers from -2147483648 to +2147483647, move to [`bigint`](http://www.postgresql.org/docs/current/interactive/datatype-numeric.html#DATATYPE-INT) if that's not enough for you. I would stick to `integer` IDs, though, if possible. They are smaller and faster than `bigint` or `text`. + +--- + +### CTEs (experimental!) + +If you cannot create a function for some reason, this pure SQL solution might do a similar trick: + +``` +WITH x(uid) AS (SELECT 10) -- provide unique_id here + , a AS ( + SELECT title, stock + FROM x, product + WHERE unique_id = x.uid + ) + , b AS ( + SELECT p.title, c.stock + FROM x, color c + JOIN product p ON c.id_product = p.id + WHERE NOT EXISTS (SELECT 1 FROM a) + AND c.unique_id = x.uid + ) + , c AS ( + SELECT p.title, s.stock + FROM x, size s + JOIN product p ON s.id_product = p.id + WHERE NOT EXISTS (SELECT 1 FROM b) + AND s.unique_id = x.uid + ) +SELECT * FROM a +UNION ALL +SELECT * FROM b +UNION ALL +SELECT * FROM c; + +``` + +I am *not sure* whether it avoids additional scans like I hope. Would have to be tested. This query requires at least PostgreSQL 8.4. + +--- + +### Upgrade! + +As I just learned, the OP runs on PostgreSQL 8.1. + +**Upgrading alone** would speed up the operation a lot. + +--- + +### Query for PostgreSQL 8.1 + +As you are limited in your options, and a plpgsql function is not possible, this function should perform better than the one you have. Test with [`EXPLAIN ANALYZE`](http://www.postgresql.org/docs/8.1/interactive/sql-explain.html) - available in v8.1. + +``` +SELECT title, stock +FROM product +WHERE unique_id = 10 + +UNION ALL +SELECT p.title, ps.stock +FROM product p +JOIN ( + SELECT id_product, stock + FROM color + WHERE unique_id = 10 + + UNION ALL + SELECT id_product, stock + FROM size + WHERE unique_id = 10 + ) ps ON ps.id_product = p.id; + +```","Your query will be pretty much efficient, as long as you have an index on `unique_id`, on every table and indices on the joining columns. + +You could turn those `UNION` into `UNION ALL` but the won't be any differnce on performance, for this query." +11422517,"I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. + +``` +product color size +------- ------- ------- +id id id +unique_id id_product (FK from product) id_product (FK from version) +stock unique_id id_version (FK from version) +title stock unique_id + stock + +``` + +The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. + +It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. + +As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: + +``` +select title, stock +from product +where unique_id = 10 + +UNION + +select p.title, c.stock +from color c +join product p on c.id_product = p.id +where c.unique_id = 10 + +UNION + +select p.title, s.stock +from size s +join product p on s.id_product = p.id +where s.unique_id = 10; + +``` + +Is there a better way to do this? Thanks for any suggestion! + +**EDIT 1** + +Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: + +1) As `unique_id` has indexes in all tables, i will get a good performance + +2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join + +``` +SELECT + + p.title, + ps.stock + +FROM ( + + select id as id_product, stock + from product + where unique_id = 10 + + UNION + + select id_product, stock + from color + where unique_id = 10 + + UNION + + select id_product, stock + from size + where unique_id = 10 + +) AS ps + +JOIN product p ON ps.id_product = p.id; + +```",2012/07/10,"['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']","### PL/pgSQL function + +To solve the problem at hand, a plpgsql function like the following should be faster: + +``` +CREATE OR REPLACE FUNCTION func(int) + RETURNS TABLE (title text, stock int) LANGUAGE plpgsql AS +$BODY$ +BEGIN + +RETURN QUERY +SELECT p.title, p.stock +FROM product p +WHERE p.unique_id = $1; -- Put the most likely table first. + +IF NOT FOUND THEN + RETURN QUERY + SELECT p.title, c.stock + FROM color c + JOIN product p ON c.id_product = p.id + WHERE c.unique_id = $1; +END; + +IF NOT FOUND THEN + RETURN QUERY + SELECT p.title, s.stock + FROM size s + JOIN product p ON s.id_product = p.id + WHERE s.unique_id = $1; +END IF; + +END; +$BODY$; + +``` + +Updated function with table-qualified column names to avoid naming conflicts with `OUT` parameters. + +`RETURNS TABLE` requires PostgreSQL 8.4, `RETURN QUERY` requires version 8.2. You can substitute both for older versions. + +It goes without saying that you need to **index** the columns `unique_id` of every involved table. `id` should be indexed automatically, being the primary key. + +--- + +### Redesign + +Ideally, you can tell which table from the ID alone. You could keep using one common sequence, but add `100000000` for the first table, `200000000` for the second and `300000000` for the third - or whatever suits your needs. This way, the least significant part of the number is easily distinguishable. + +A plain integer spans numbers from -2147483648 to +2147483647, move to [`bigint`](http://www.postgresql.org/docs/current/interactive/datatype-numeric.html#DATATYPE-INT) if that's not enough for you. I would stick to `integer` IDs, though, if possible. They are smaller and faster than `bigint` or `text`. + +--- + +### CTEs (experimental!) + +If you cannot create a function for some reason, this pure SQL solution might do a similar trick: + +``` +WITH x(uid) AS (SELECT 10) -- provide unique_id here + , a AS ( + SELECT title, stock + FROM x, product + WHERE unique_id = x.uid + ) + , b AS ( + SELECT p.title, c.stock + FROM x, color c + JOIN product p ON c.id_product = p.id + WHERE NOT EXISTS (SELECT 1 FROM a) + AND c.unique_id = x.uid + ) + , c AS ( + SELECT p.title, s.stock + FROM x, size s + JOIN product p ON s.id_product = p.id + WHERE NOT EXISTS (SELECT 1 FROM b) + AND s.unique_id = x.uid + ) +SELECT * FROM a +UNION ALL +SELECT * FROM b +UNION ALL +SELECT * FROM c; + +``` + +I am *not sure* whether it avoids additional scans like I hope. Would have to be tested. This query requires at least PostgreSQL 8.4. + +--- + +### Upgrade! + +As I just learned, the OP runs on PostgreSQL 8.1. + +**Upgrading alone** would speed up the operation a lot. + +--- + +### Query for PostgreSQL 8.1 + +As you are limited in your options, and a plpgsql function is not possible, this function should perform better than the one you have. Test with [`EXPLAIN ANALYZE`](http://www.postgresql.org/docs/8.1/interactive/sql-explain.html) - available in v8.1. + +``` +SELECT title, stock +FROM product +WHERE unique_id = 10 + +UNION ALL +SELECT p.title, ps.stock +FROM product p +JOIN ( + SELECT id_product, stock + FROM color + WHERE unique_id = 10 + + UNION ALL + SELECT id_product, stock + FROM size + WHERE unique_id = 10 + ) ps ON ps.id_product = p.id; + +```","I think it's time for a redesign. + +You have things that you're using as bar codes for items that are basically all the same in one respect (they are SerialNumberItems), but have been split into multiple tables because they are different in other respects. + +I have several ideas for you: + +Change the Defaults +------------------- + +Just make each product required to have one color ""no color"" and one size ""no size"". Then you can query any table you want to find the info you need. + +SuperType/SubType +----------------- + +Without too much modification you could use the supertype/subtype database design pattern. + +In it, there is a parent table where all the distinct detail-level identifiers live, and the shared columns of the subtype tables go in the supertype table (the ways that all the items are the same). There is one subtype table for each different way that the items are distinct. If mutual exclusivity of the subtype is required (you can have a Color or a Size but not both), then the parent table is given a TypeID column and the subtype tables have an FK to both the ParentID and the TypeID. Looking at your design, in fact you would not use mutual exclusivity. + +If you use the pattern of a supertype table, you do have the issue of having to insert in two parts, first to the supertype, then the subtype. Deleting also requires deleting in reverse order. But you get a great benefit of being able to get basic information such as Title and Stock out of the supertype table with a single query. + +You could even create schema-bound views for each subtype, with instead-of triggers that convert inserts, updates, and deletes into operations on the base table + child table. + +A Bigger Redesign +----------------- + +You could completely change how Colors and Sizes are related to products. + +First, your patterns of ""has-a"" are these: + +* Product (has nothing) +* Product->Color +* Product->Size +* Product->Color->Size + +There is a problem here. Clearly Product is the main item that has other things (colors and sizes) but colors don't have sizes! That is an arbitrary assignment. You may as well have said that Sizes have Colors--it doesn't make a difference. This reveals that your table design may not be best, as you're trying to model orthogonal data in a parent-child type of relationship. Really, products have a ColorAndSize. + +Furthermore, when a product comes in colors and sizes, what does the `uniqueid` in the Color table mean? Can such a product be ordered without a size, having only a color? This design is assigning a unique ID to something that (it seems to me) should never be allowed to be ordered--but you can't find this information out from the Color table, you have to compare the Color and Size tables first. It is a problem. + +I would design this as: Table `Product`. Table `Size` listing all distinct sizes possible for any product ever. Table `Color` listing all distinct colors possible for any product ever. And table `OrderableProduct` that has columns `ProductId`, `ColorID`, `SizeID`, and `UniqueID` (your bar code value). Additionally, each product must have one color and one size or it doesn't exist. + +Basically, Color and Size are like X and Y coordinates into a grid; you are filling in the boxes that are allowable combinations. Which one is the row and which the column is irrelevant. Certainly, one is not a child of the other. + +If there are any reasonable rules, in general, about what colors or sizes can be applied to various sub-groups of products, there might be utility in a ProductType table and a ProductTypeOrderables table that, when creating a new product, could populate the OrderableProduct table with the standard set—it could still be customized but might be easier to modify than to create anew. Or, it could define the range of colors and sizes that are allowable. You might need separate ProductTypeAllowedColor and ProductTypeAllowedSize tables. For example, if you are selling T-shirts, you'd want to allow XXXS, XXS, XS, S, M, L, XL, XXL, XXXL, and XXXXL, even if most products never use all those sizes. But for soft drinks, the sizes might be 6-pack 8oz, 24-pack 8oz, 2 liter, and so on, even if each soft drink is not offered in that size (and soft drinks don't have colors). + +In this new scheme, you only have one table to query to find the correct orderable product. With proper indexes, it should be blazing fast. + +Your Question +------------- + +You asked: + +> +> in PostgreSQL, so do you think if i use indexes on unique\_id i will get a satisfactory performance? +> +> +> + +Any column or set of columns that you use to repeatedly look up data must have an index! Any other pattern will result in a full table scan each time, which will be awful performance. I am sure that these indexes will make your queries lightning fast as it will take only one leaf-level read per table." +11422517,"I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. + +``` +product color size +------- ------- ------- +id id id +unique_id id_product (FK from product) id_product (FK from version) +stock unique_id id_version (FK from version) +title stock unique_id + stock + +``` + +The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. + +It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. + +As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: + +``` +select title, stock +from product +where unique_id = 10 + +UNION + +select p.title, c.stock +from color c +join product p on c.id_product = p.id +where c.unique_id = 10 + +UNION + +select p.title, s.stock +from size s +join product p on s.id_product = p.id +where s.unique_id = 10; + +``` + +Is there a better way to do this? Thanks for any suggestion! + +**EDIT 1** + +Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: + +1) As `unique_id` has indexes in all tables, i will get a good performance + +2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join + +``` +SELECT + + p.title, + ps.stock + +FROM ( + + select id as id_product, stock + from product + where unique_id = 10 + + UNION + + select id_product, stock + from color + where unique_id = 10 + + UNION + + select id_product, stock + from size + where unique_id = 10 + +) AS ps + +JOIN product p ON ps.id_product = p.id; + +```",2012/07/10,"['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']","### PL/pgSQL function + +To solve the problem at hand, a plpgsql function like the following should be faster: + +``` +CREATE OR REPLACE FUNCTION func(int) + RETURNS TABLE (title text, stock int) LANGUAGE plpgsql AS +$BODY$ +BEGIN + +RETURN QUERY +SELECT p.title, p.stock +FROM product p +WHERE p.unique_id = $1; -- Put the most likely table first. + +IF NOT FOUND THEN + RETURN QUERY + SELECT p.title, c.stock + FROM color c + JOIN product p ON c.id_product = p.id + WHERE c.unique_id = $1; +END; + +IF NOT FOUND THEN + RETURN QUERY + SELECT p.title, s.stock + FROM size s + JOIN product p ON s.id_product = p.id + WHERE s.unique_id = $1; +END IF; + +END; +$BODY$; + +``` + +Updated function with table-qualified column names to avoid naming conflicts with `OUT` parameters. + +`RETURNS TABLE` requires PostgreSQL 8.4, `RETURN QUERY` requires version 8.2. You can substitute both for older versions. + +It goes without saying that you need to **index** the columns `unique_id` of every involved table. `id` should be indexed automatically, being the primary key. + +--- + +### Redesign + +Ideally, you can tell which table from the ID alone. You could keep using one common sequence, but add `100000000` for the first table, `200000000` for the second and `300000000` for the third - or whatever suits your needs. This way, the least significant part of the number is easily distinguishable. + +A plain integer spans numbers from -2147483648 to +2147483647, move to [`bigint`](http://www.postgresql.org/docs/current/interactive/datatype-numeric.html#DATATYPE-INT) if that's not enough for you. I would stick to `integer` IDs, though, if possible. They are smaller and faster than `bigint` or `text`. + +--- + +### CTEs (experimental!) + +If you cannot create a function for some reason, this pure SQL solution might do a similar trick: + +``` +WITH x(uid) AS (SELECT 10) -- provide unique_id here + , a AS ( + SELECT title, stock + FROM x, product + WHERE unique_id = x.uid + ) + , b AS ( + SELECT p.title, c.stock + FROM x, color c + JOIN product p ON c.id_product = p.id + WHERE NOT EXISTS (SELECT 1 FROM a) + AND c.unique_id = x.uid + ) + , c AS ( + SELECT p.title, s.stock + FROM x, size s + JOIN product p ON s.id_product = p.id + WHERE NOT EXISTS (SELECT 1 FROM b) + AND s.unique_id = x.uid + ) +SELECT * FROM a +UNION ALL +SELECT * FROM b +UNION ALL +SELECT * FROM c; + +``` + +I am *not sure* whether it avoids additional scans like I hope. Would have to be tested. This query requires at least PostgreSQL 8.4. + +--- + +### Upgrade! + +As I just learned, the OP runs on PostgreSQL 8.1. + +**Upgrading alone** would speed up the operation a lot. + +--- + +### Query for PostgreSQL 8.1 + +As you are limited in your options, and a plpgsql function is not possible, this function should perform better than the one you have. Test with [`EXPLAIN ANALYZE`](http://www.postgresql.org/docs/8.1/interactive/sql-explain.html) - available in v8.1. + +``` +SELECT title, stock +FROM product +WHERE unique_id = 10 + +UNION ALL +SELECT p.title, ps.stock +FROM product p +JOIN ( + SELECT id_product, stock + FROM color + WHERE unique_id = 10 + + UNION ALL + SELECT id_product, stock + FROM size + WHERE unique_id = 10 + ) ps ON ps.id_product = p.id; + +```","This is a bit different. I don't understand the intended behaviour if stocks exists in more than one of the {product,color,zsize} tables. (UNION will remove duplicates, but for the row-as-a-whole, eg the {product\_id,stock} tuples. That makes no sense to me. I just take the first. (Note the funky self-join!!) + +``` +SELECT p.title + , COALESCE (p2.stock, c.stock, s.stock) AS stock +FROM product p +LEFT JOIN product p2 on p2.id = p.id AND p2.unique_id = 10 +LEFT JOIN color c on c.id_product = p.id AND c.unique_id = 10 +LEFT JOIN zsize s on s.id_product = p.id AND s.unique_id = 10 +WHERE COALESCE (p2.stock, c.stock, s.stock) IS NOT NULL + ; + +```" +11422517,"I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. + +``` +product color size +------- ------- ------- +id id id +unique_id id_product (FK from product) id_product (FK from version) +stock unique_id id_version (FK from version) +title stock unique_id + stock + +``` + +The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. + +It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. + +As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: + +``` +select title, stock +from product +where unique_id = 10 + +UNION + +select p.title, c.stock +from color c +join product p on c.id_product = p.id +where c.unique_id = 10 + +UNION + +select p.title, s.stock +from size s +join product p on s.id_product = p.id +where s.unique_id = 10; + +``` + +Is there a better way to do this? Thanks for any suggestion! + +**EDIT 1** + +Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: + +1) As `unique_id` has indexes in all tables, i will get a good performance + +2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join + +``` +SELECT + + p.title, + ps.stock + +FROM ( + + select id as id_product, stock + from product + where unique_id = 10 + + UNION + + select id_product, stock + from color + where unique_id = 10 + + UNION + + select id_product, stock + from size + where unique_id = 10 + +) AS ps + +JOIN product p ON ps.id_product = p.id; + +```",2012/07/10,"['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']","I think it's time for a redesign. + +You have things that you're using as bar codes for items that are basically all the same in one respect (they are SerialNumberItems), but have been split into multiple tables because they are different in other respects. + +I have several ideas for you: + +Change the Defaults +------------------- + +Just make each product required to have one color ""no color"" and one size ""no size"". Then you can query any table you want to find the info you need. + +SuperType/SubType +----------------- + +Without too much modification you could use the supertype/subtype database design pattern. + +In it, there is a parent table where all the distinct detail-level identifiers live, and the shared columns of the subtype tables go in the supertype table (the ways that all the items are the same). There is one subtype table for each different way that the items are distinct. If mutual exclusivity of the subtype is required (you can have a Color or a Size but not both), then the parent table is given a TypeID column and the subtype tables have an FK to both the ParentID and the TypeID. Looking at your design, in fact you would not use mutual exclusivity. + +If you use the pattern of a supertype table, you do have the issue of having to insert in two parts, first to the supertype, then the subtype. Deleting also requires deleting in reverse order. But you get a great benefit of being able to get basic information such as Title and Stock out of the supertype table with a single query. + +You could even create schema-bound views for each subtype, with instead-of triggers that convert inserts, updates, and deletes into operations on the base table + child table. + +A Bigger Redesign +----------------- + +You could completely change how Colors and Sizes are related to products. + +First, your patterns of ""has-a"" are these: + +* Product (has nothing) +* Product->Color +* Product->Size +* Product->Color->Size + +There is a problem here. Clearly Product is the main item that has other things (colors and sizes) but colors don't have sizes! That is an arbitrary assignment. You may as well have said that Sizes have Colors--it doesn't make a difference. This reveals that your table design may not be best, as you're trying to model orthogonal data in a parent-child type of relationship. Really, products have a ColorAndSize. + +Furthermore, when a product comes in colors and sizes, what does the `uniqueid` in the Color table mean? Can such a product be ordered without a size, having only a color? This design is assigning a unique ID to something that (it seems to me) should never be allowed to be ordered--but you can't find this information out from the Color table, you have to compare the Color and Size tables first. It is a problem. + +I would design this as: Table `Product`. Table `Size` listing all distinct sizes possible for any product ever. Table `Color` listing all distinct colors possible for any product ever. And table `OrderableProduct` that has columns `ProductId`, `ColorID`, `SizeID`, and `UniqueID` (your bar code value). Additionally, each product must have one color and one size or it doesn't exist. + +Basically, Color and Size are like X and Y coordinates into a grid; you are filling in the boxes that are allowable combinations. Which one is the row and which the column is irrelevant. Certainly, one is not a child of the other. + +If there are any reasonable rules, in general, about what colors or sizes can be applied to various sub-groups of products, there might be utility in a ProductType table and a ProductTypeOrderables table that, when creating a new product, could populate the OrderableProduct table with the standard set—it could still be customized but might be easier to modify than to create anew. Or, it could define the range of colors and sizes that are allowable. You might need separate ProductTypeAllowedColor and ProductTypeAllowedSize tables. For example, if you are selling T-shirts, you'd want to allow XXXS, XXS, XS, S, M, L, XL, XXL, XXXL, and XXXXL, even if most products never use all those sizes. But for soft drinks, the sizes might be 6-pack 8oz, 24-pack 8oz, 2 liter, and so on, even if each soft drink is not offered in that size (and soft drinks don't have colors). + +In this new scheme, you only have one table to query to find the correct orderable product. With proper indexes, it should be blazing fast. + +Your Question +------------- + +You asked: + +> +> in PostgreSQL, so do you think if i use indexes on unique\_id i will get a satisfactory performance? +> +> +> + +Any column or set of columns that you use to repeatedly look up data must have an index! Any other pattern will result in a full table scan each time, which will be awful performance. I am sure that these indexes will make your queries lightning fast as it will take only one leaf-level read per table.","Your query will be pretty much efficient, as long as you have an index on `unique_id`, on every table and indices on the joining columns. + +You could turn those `UNION` into `UNION ALL` but the won't be any differnce on performance, for this query." +11422517,"I have three tables that control products, colors and sizes. Products can have or not colors and sizes. Colors can or not have sizes. + +``` +product color size +------- ------- ------- +id id id +unique_id id_product (FK from product) id_product (FK from version) +stock unique_id id_version (FK from version) +title stock unique_id + stock + +``` + +The `unique_id` column, that is present in all tables, is a serial type (autoincrement) and its counter is shared with the three tables, basically it works as a global unique ID between them. + +It works fine, but i am trying to increase the query performance when i have to select some fields based in the `unique_id`. + +As i don't know where is the `unique_id` that i am looking for, i am using `UNION`, like below: + +``` +select title, stock +from product +where unique_id = 10 + +UNION + +select p.title, c.stock +from color c +join product p on c.id_product = p.id +where c.unique_id = 10 + +UNION + +select p.title, s.stock +from size s +join product p on s.id_product = p.id +where s.unique_id = 10; + +``` + +Is there a better way to do this? Thanks for any suggestion! + +**EDIT 1** + +Based on @ErwinBrandstetter and @ErikE answers i decided to use the below query. The main reasons is: + +1) As `unique_id` has indexes in all tables, i will get a good performance + +2) Using the `unique_id` i will find the product code, so i can get all columns i need using a another simple join + +``` +SELECT + + p.title, + ps.stock + +FROM ( + + select id as id_product, stock + from product + where unique_id = 10 + + UNION + + select id_product, stock + from color + where unique_id = 10 + + UNION + + select id_product, stock + from size + where unique_id = 10 + +) AS ps + +JOIN product p ON ps.id_product = p.id; + +```",2012/07/10,"['https://Stackoverflow.com/questions/11422517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999820/']","I think it's time for a redesign. + +You have things that you're using as bar codes for items that are basically all the same in one respect (they are SerialNumberItems), but have been split into multiple tables because they are different in other respects. + +I have several ideas for you: + +Change the Defaults +------------------- + +Just make each product required to have one color ""no color"" and one size ""no size"". Then you can query any table you want to find the info you need. + +SuperType/SubType +----------------- + +Without too much modification you could use the supertype/subtype database design pattern. + +In it, there is a parent table where all the distinct detail-level identifiers live, and the shared columns of the subtype tables go in the supertype table (the ways that all the items are the same). There is one subtype table for each different way that the items are distinct. If mutual exclusivity of the subtype is required (you can have a Color or a Size but not both), then the parent table is given a TypeID column and the subtype tables have an FK to both the ParentID and the TypeID. Looking at your design, in fact you would not use mutual exclusivity. + +If you use the pattern of a supertype table, you do have the issue of having to insert in two parts, first to the supertype, then the subtype. Deleting also requires deleting in reverse order. But you get a great benefit of being able to get basic information such as Title and Stock out of the supertype table with a single query. + +You could even create schema-bound views for each subtype, with instead-of triggers that convert inserts, updates, and deletes into operations on the base table + child table. + +A Bigger Redesign +----------------- + +You could completely change how Colors and Sizes are related to products. + +First, your patterns of ""has-a"" are these: + +* Product (has nothing) +* Product->Color +* Product->Size +* Product->Color->Size + +There is a problem here. Clearly Product is the main item that has other things (colors and sizes) but colors don't have sizes! That is an arbitrary assignment. You may as well have said that Sizes have Colors--it doesn't make a difference. This reveals that your table design may not be best, as you're trying to model orthogonal data in a parent-child type of relationship. Really, products have a ColorAndSize. + +Furthermore, when a product comes in colors and sizes, what does the `uniqueid` in the Color table mean? Can such a product be ordered without a size, having only a color? This design is assigning a unique ID to something that (it seems to me) should never be allowed to be ordered--but you can't find this information out from the Color table, you have to compare the Color and Size tables first. It is a problem. + +I would design this as: Table `Product`. Table `Size` listing all distinct sizes possible for any product ever. Table `Color` listing all distinct colors possible for any product ever. And table `OrderableProduct` that has columns `ProductId`, `ColorID`, `SizeID`, and `UniqueID` (your bar code value). Additionally, each product must have one color and one size or it doesn't exist. + +Basically, Color and Size are like X and Y coordinates into a grid; you are filling in the boxes that are allowable combinations. Which one is the row and which the column is irrelevant. Certainly, one is not a child of the other. + +If there are any reasonable rules, in general, about what colors or sizes can be applied to various sub-groups of products, there might be utility in a ProductType table and a ProductTypeOrderables table that, when creating a new product, could populate the OrderableProduct table with the standard set—it could still be customized but might be easier to modify than to create anew. Or, it could define the range of colors and sizes that are allowable. You might need separate ProductTypeAllowedColor and ProductTypeAllowedSize tables. For example, if you are selling T-shirts, you'd want to allow XXXS, XXS, XS, S, M, L, XL, XXL, XXXL, and XXXXL, even if most products never use all those sizes. But for soft drinks, the sizes might be 6-pack 8oz, 24-pack 8oz, 2 liter, and so on, even if each soft drink is not offered in that size (and soft drinks don't have colors). + +In this new scheme, you only have one table to query to find the correct orderable product. With proper indexes, it should be blazing fast. + +Your Question +------------- + +You asked: + +> +> in PostgreSQL, so do you think if i use indexes on unique\_id i will get a satisfactory performance? +> +> +> + +Any column or set of columns that you use to repeatedly look up data must have an index! Any other pattern will result in a full table scan each time, which will be awful performance. I am sure that these indexes will make your queries lightning fast as it will take only one leaf-level read per table.","This is a bit different. I don't understand the intended behaviour if stocks exists in more than one of the {product,color,zsize} tables. (UNION will remove duplicates, but for the row-as-a-whole, eg the {product\_id,stock} tuples. That makes no sense to me. I just take the first. (Note the funky self-join!!) + +``` +SELECT p.title + , COALESCE (p2.stock, c.stock, s.stock) AS stock +FROM product p +LEFT JOIN product p2 on p2.id = p.id AND p2.unique_id = 10 +LEFT JOIN color c on c.id_product = p.id AND c.unique_id = 10 +LEFT JOIN zsize s on s.id_product = p.id AND s.unique_id = 10 +WHERE COALESCE (p2.stock, c.stock, s.stock) IS NOT NULL + ; + +```" +597528,"From Wikipedia I have the compliment of the CDF parameterized for fat-tails distributions. + +$$ +\Pr[X>x] \sim x^{- \alpha}\text{ as }x \to \infty,\qquad \alpha > 0.\, +$$ + +Here $\alpha$ is the fatness parameter. According to Taleb. $\alpha \leq 2.5$ is forecastable, but $\alpha > 2.5$ is not. + +I would like to fit $\alpha$ given my data so I can mark it as forecastable or not. + +I thought I would start by trying to fit my data to a linear model. + +``` +set.seed(42) +df_tails <- tibble(y = 1- seq(0.01,1, 0.01), + norm = sort(rnorm(n = 100, 0,1)), + cauchy = sort(rcauchy(n = 100, 0,1))) +lm(log(y) ~ norm - 1, data = df_tails) +lm(log(y) ~ cauchy - 1, data = df_tails) + +``` + +The problem is that I end up with many `NAs` so I think I am coding something wrong. + +### Try 2 + +``` +library(tidyverse) +set.seed(42) + +df_tails_raw <- tibble(y = log(1- seq(0.01,1, 0.01)), + norm = log(sort(rnorm(n = 100, 0,1))), + cauchy = log(sort(rcauchy(n = 100, 0,1)))) +df_tails <- na.omit(df_tails_raw) + +df_tails |> + ggplot() + + geom_point(aes(x = norm, y=y), color = 'tomato', size = 2, stroke = 2, shape = 1) + + geom_point(aes(x = cauchy, y = y), color = 'grey50', size = 2, stroke = 2, shape = 1) + + theme_classic() + + labs('Red is normal and Grey is Cauchy') + +lm(y ~ norm, data = df_tails) +lm(y ~ cauchy - 1, data = df_tails) + +``` + +[![enter image description here](https://i.stack.imgur.com/1WjzT.png)](https://i.stack.imgur.com/1WjzT.png) + +My error is + +> +> Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : +> NA/NaN/Inf in 'y' +> +> +>",2022/11/30,"['https://stats.stackexchange.com/questions/597528', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/142914/']","There are several issues with this question. + +### The error message + +The simplest, is the issue about the error message which is the explicit question in the text. + +> +> Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : +> NA/NaN/Inf in 'y' +> +> +> + +The error says that the dependent variable in the linear model is not right and contains NA/NaN/Inf. The reason is because your $y$ variable contains a zero and when you take the logarithm of this then you get an NA value. Then, when you pass this to the `lm` function you get the error. (Because you pass log(y) nested inside the lm function this is not so clear, but the 'y' of the lm function is your 'log(y)' value and not your 'y' value) + +Sidenote: to fit a powerlaw with linearisation you should use $\log(y) = a + b \cdot \log(x)$. In your code you use $\log(y) = bx$ and you miss the intercept as well as taking the logarithm of $x$. + +### The fitting of the power law + +Distributions that have power law behaviour are often only having this behaviour for a limited range. In your fitting method you should only fit the part of the distribution that follows the power law. + +In the log-log plot below you see that you don't have a straight line over the entire range, in addition, the points in the tail are the ones with a large scatter and error. If you plot the points along with the known underlying distribution you see that the error is not just the scatter but also the error is correlated and the entire curve can have an error. + +[![example of behaviour on log log scale](https://i.stack.imgur.com/HIXsD.png)](https://i.stack.imgur.com/HIXsD.png) + +On the plot I also have added a log-normal distribution. It shows that curves that are not really straight can appear to be straight. Just fitting a straight line does not tell that you also actually have a straight line. + +The article mentioned by Sycorax on the comments, [Power-law distributions in empirical data](https://arxiv.org/abs/0706.1062), discusses this issue on more detail.","#### You might want to use the `tailplot` function in the `utilities` package + +The standard way of examining tail behaviour of data is through a tail-plot or a Hill plot (or variations of these). The tailplot shows the tails of a dataset against the empirical tail probability, each exhibited on a logarithmic scale. The plot can be generated in `R` by using the [`tailplot` function](https://search.r-project.org/CRAN/refmans/utilities/html/tailplot.html) in the [`utilities` package](https://CRAN.R-project.org/package=utilities). This function allows you to plot the data in one or both tails using a chosen proportion of the dataset (by default the plot will show 5% of the data in each tail) and it will compare this with a specified power-rate of decay (by default it is compared with cubic decay, which determines finiteness of the variance. + +In the code below I give an example of a tailplot for a set of $n=1000$ datapoints generated from a standard normal distribution. The plot shows that the tails of the distributin decays substantially faster than cubic decay, which is sufficient to give finite variance. You can compare your data with an alternate rate-of-decay if you prefer. + +``` +#Set some mock data +set.seed(1) +DATA <- rnorm(1000) + +#Show the tail plots +library(utilities) +tailplot(DATA) + +``` + +[![enter image description here](https://i.stack.imgur.com/4yIFi.jpg)](https://i.stack.imgur.com/4yIFi.jpg) + +Note that the `tailplot` function also allows you to include a Hill-plot and/or De Sousa-Michailidis plot used for estimating the rate-of-decay of the tails. To include these plots, just set `hill.plot = TRUE` and/or `dsm.plot = TRUE`." +5174788,"I have a Perl controller class in which I do: + +``` +sub func1 { + my $f1 = Model::myModel->new(); + my $param = ""test""; + $f1->func2($param); +} + +``` + +Model class: + +``` +sub new { + my ($class, %arg) = @_; + my $self = bless {}, $class; + return $self; +} + +sub func2 { + my ($self, $param) = shift(@_); + warn $param; +} + +``` + +`$param` is blank. What is the mistake I am doing?",2011/03/02,"['https://Stackoverflow.com/questions/5174788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67476/']","`shift` only shifts the first value off of `@_`. `perldoc -f shift` will tell you more about how shift works. + +You want: + +``` +my( $self, $param ) = @_; + +``` + +You had it right in `new()`. Not sure what happened ;) + +Actually, FYI, your `new()` will give the warning: + +``` +Odd number of elements in hash assignment + +``` + +If you call it like `$package->new( 'a' );` You might want to trap that, something like: + +``` +use Carp qw( croak confess ); +sub new { + my $class = shift; + confess ""$class requires an even number of args"" if( @_ & 1 ); + my %args = @_; + # ... +} + +``` + +Or using whatever exception catching mechanism you use.","Try: + +``` +sub func2 { + my ( $self, $param ) = @_; + warn $param; +} + +``` + +or + +``` +sub func2 { + my $self = shift @_; + my $param = shift @_; + warn $param; +} + +```" +184845,"This is my current partition table: + +![screen0](https://i.stack.imgur.com/GeuKx.png) + +In which `/dev/sda8` is the partition on Which I am currently running my primary OS - [Trisquel](https://trisquel.info) GNU/Linux (you can see it's mount point as `/`). The `/dev/sda1` is the primary partition containing Windows XP. + +I want to resize `/dev/sda1` (Size:50GB ; Used 27.97GB) i.e. want to reduce it to 30GB (Split into 30GB + 20GB). So, I've first Unmounted `/dev/sda1`. + +Now When I use **Resize/Move** option (from right-click menu) The following window appears: + +![screen1](https://i.stack.imgur.com/POAWi.png) + +The **problem** is that it doesn't allow to reduce partition! Why?(Because it is primary partition?) + +And Finally **How can I resize (reduce/split) `/dev/sda1`?** + +Note:- Gparted is running from Trisquel (GNU/Linux).",2015/02/14,"['https://unix.stackexchange.com/questions/184845', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/66803/']","My guess is that Windows XP places a master file table at the end of the partition, preventing you from resizing it. You should be able to move the master file table from within XP. Also maybe you need to defrag the Windows partition? And finally, are you sure you unmounted sda1? Run `df` in a terminal and make sure you don't see /dev/sda1 anywhere in the output, then close and reopen GParted",Try running a chkdsk and/or scandisk in Windows [to rule out bad sectors & other inconcistencies] then attempt to resize. +184845,"This is my current partition table: + +![screen0](https://i.stack.imgur.com/GeuKx.png) + +In which `/dev/sda8` is the partition on Which I am currently running my primary OS - [Trisquel](https://trisquel.info) GNU/Linux (you can see it's mount point as `/`). The `/dev/sda1` is the primary partition containing Windows XP. + +I want to resize `/dev/sda1` (Size:50GB ; Used 27.97GB) i.e. want to reduce it to 30GB (Split into 30GB + 20GB). So, I've first Unmounted `/dev/sda1`. + +Now When I use **Resize/Move** option (from right-click menu) The following window appears: + +![screen1](https://i.stack.imgur.com/POAWi.png) + +The **problem** is that it doesn't allow to reduce partition! Why?(Because it is primary partition?) + +And Finally **How can I resize (reduce/split) `/dev/sda1`?** + +Note:- Gparted is running from Trisquel (GNU/Linux).",2015/02/14,"['https://unix.stackexchange.com/questions/184845', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/66803/']","Before you can resize any ntfs based partition, you need to ensure all the files are pushed up to the start of the partition. This is acomplisehd by running the defragmentation process on the partition within windowsXP. +It may also be useful to delete any temporal files or any other stuff you don't want from the windows partition. +In addition, deleting the windows swap file may also be helpfull, as it is normally not moved by the defragmentation tool. You can safely delete the pagefile from linux before resizing the partition, or you may turn off the swap file within windows.","My guess is that Windows XP places a master file table at the end of the partition, preventing you from resizing it. You should be able to move the master file table from within XP. Also maybe you need to defrag the Windows partition? And finally, are you sure you unmounted sda1? Run `df` in a terminal and make sure you don't see /dev/sda1 anywhere in the output, then close and reopen GParted" +184845,"This is my current partition table: + +![screen0](https://i.stack.imgur.com/GeuKx.png) + +In which `/dev/sda8` is the partition on Which I am currently running my primary OS - [Trisquel](https://trisquel.info) GNU/Linux (you can see it's mount point as `/`). The `/dev/sda1` is the primary partition containing Windows XP. + +I want to resize `/dev/sda1` (Size:50GB ; Used 27.97GB) i.e. want to reduce it to 30GB (Split into 30GB + 20GB). So, I've first Unmounted `/dev/sda1`. + +Now When I use **Resize/Move** option (from right-click menu) The following window appears: + +![screen1](https://i.stack.imgur.com/POAWi.png) + +The **problem** is that it doesn't allow to reduce partition! Why?(Because it is primary partition?) + +And Finally **How can I resize (reduce/split) `/dev/sda1`?** + +Note:- Gparted is running from Trisquel (GNU/Linux).",2015/02/14,"['https://unix.stackexchange.com/questions/184845', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/66803/']","Before you can resize any ntfs based partition, you need to ensure all the files are pushed up to the start of the partition. This is acomplisehd by running the defragmentation process on the partition within windowsXP. +It may also be useful to delete any temporal files or any other stuff you don't want from the windows partition. +In addition, deleting the windows swap file may also be helpfull, as it is normally not moved by the defragmentation tool. You can safely delete the pagefile from linux before resizing the partition, or you may turn off the swap file within windows.",Try running a chkdsk and/or scandisk in Windows [to rule out bad sectors & other inconcistencies] then attempt to resize. +69677554,"I am extreme beginner and I have this dumb problem. +So I wrote a css file and html file. + +HTML : + +``` + + + + + +

Paragraph

+ + + + +``` + +I did this for my css file + +``` +p { + color: red; +} + +``` + +When I save and refresh my website, the html shows up. + +The css doesnt show up like the paragraph doesnt change red. I also want to change the position of the image. + +Please help! + +I also want to know about indenting please. + +Also should for website developing, should I learn css and html at the same time, or like html for 1 year, and then css for one year, because im learning javascript like in a 2 years, next year.",2021/10/22,"['https://Stackoverflow.com/questions/69677554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17187107/']","You must tell your HMTL page where to find your CSS. +To do that you have to add `link` tag into your `head` tag using: + +``` + + + + +``` + +``: The External Resource Link element + +> +> The HTML element specifies relationships between the current +> document and an external resource. This element is most commonly used +> to link to stylesheets, but is also used to establish site icons (both +> ""favicon"" style icons and icons for the home screen and apps on mobile +> devices) among other things. +> +> +> + +Take a look at + +In your case if your css file named `style.css` and `your index.html` file are on the same folder, your html should look like that: + +``` + + + + + + + + + +

Paragraph

+ + + + +``` + +> +> The HTML element contains machine-readable information +> (metadata) about the document, like its title, scripts, and style +> sheets. +> +> +> + + + +If you want to use [inline css](https://www.w3schools.com/css/css_howto.asp) you have to put your ` + + + + +

Paragraph

+ + + +```","> +> Also should for website developing, should I learn css and html at the +> same time, or like html for 1 year, and then css for one year, because +> im learning javascript like in a 2 years, next year. +> +> +> + +Well, HTML, CSS & JS are the fabric of the front end so my advice is why not all three at the same time? They each compliment each other and after 3 years studying you will have understood more about them than focusing your time and energy learning each as separate entities. + +Think of HTML as your initial sketch (your structure), CSS as painting your sketch (your make-up and beautifier), and JS as making your painting come to life (your functional and interactive parts). Simply put, it's more fun with working with all 3" +4307118,"I've a JSONArray and I need to get the hashmap with the values, because I need to populate a stream, like twitter done. +What you suggest to do?",2010/11/29,"['https://Stackoverflow.com/questions/4307118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/496371/']","``` +HashMap pairs = new HashMap(); +for (int i = 0; i < myArray.length(); i++) { + JSONObject j = myArray.optJSONObject(i); + Iterator it = j.keys(); + while (it.hasNext()) { + String n = it.next(); + pairs.put(n, j.getString(n)); + } +} + +``` + +Something like that.","You can use `Iterator` for getting `JsonArrays`. or use this way + +eg. json + +``` +{ +........ +........ + + ""FARE"":[ //JSON Array + { + ""REG_ID"":3, + ""PACKAGE_ID"":1, + ""MODEL_ID"":9, + ""MIN_HOUR"":0 + ....... + ....... + ....... + } + ] +} + +``` + +> +> +> ``` +> HashMap mMap= new HashMap<>(); +> for (int i = 0; i < myArray.length(); i++) { +> +> JSONObject j = myArray.optJSONObject(i); +> mMap.put(""KEY1"", j.getString(""REG_ID"")); +> mMap.put(""KEY2"", j.getString(""PACKAGE_ID"")); +> ............ +> ............ +> } +> +> ``` +> +> + +**note**: For better coding use `Iterator`" +25467734,"I have a JXTreeTable with an add button. The button works as expected: it adds a new node to the end, with values that (for the purpose of testing) are hard-coded into my program. The line: + +``` +modelSupport.fireChildAdded(new TreePath(root), noOfChildren-1, dataNode); + +``` + +tells the JXTreeTable to recognise the update made to the TreeTableModel, and to refresh accordingly. + +I then execute: + +``` +treeTable.changeSelection(treeTable.getRowCount()-1, 0, false, false); + +``` + +to automatically select this new node. This works as expected, BUT I also expected it to automatically scroll to bring this new node into sight, which it does not. Instead, it scrolls to show only the penultimate node, leaving the new node hidden just slightly beyond view. + +I've also tried using tricks to programmatically scroll to the final record. However, this code: + +``` +JScrollBar vertical = scrollPane.getVerticalScrollBar(); +vertical.setValue(vertical.getMaximum()); + +``` + +revealed the same problem. + +Bizarrely, if I attach either of the above two blocks of code to a ""Scroll to Bottom"" button, and press this button manually after adding the new node, it all works fine! Please can anyone isolate the cause of this bug, or offer a fix/workaround?",2014/08/24,"['https://Stackoverflow.com/questions/25467734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313909/']","Give it a Name + +``` + + + // ...... + + + +``` + +Then you can just Hide() + +``` +myFlyout.Hide(); + +``` + +[FlyoutBase.Hide method](http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.primitives.flyoutbase.hide.aspx)","``` +public void btnRestart_Click(object sender, RoutedEventArgs) +{ + ((((sender as Button).Parent as StackPanel).Parent as StackPanel).Parent as Flyout).Hide(); +} + +``` + +Very ugly but should work." +25467734,"I have a JXTreeTable with an add button. The button works as expected: it adds a new node to the end, with values that (for the purpose of testing) are hard-coded into my program. The line: + +``` +modelSupport.fireChildAdded(new TreePath(root), noOfChildren-1, dataNode); + +``` + +tells the JXTreeTable to recognise the update made to the TreeTableModel, and to refresh accordingly. + +I then execute: + +``` +treeTable.changeSelection(treeTable.getRowCount()-1, 0, false, false); + +``` + +to automatically select this new node. This works as expected, BUT I also expected it to automatically scroll to bring this new node into sight, which it does not. Instead, it scrolls to show only the penultimate node, leaving the new node hidden just slightly beyond view. + +I've also tried using tricks to programmatically scroll to the final record. However, this code: + +``` +JScrollBar vertical = scrollPane.getVerticalScrollBar(); +vertical.setValue(vertical.getMaximum()); + +``` + +revealed the same problem. + +Bizarrely, if I attach either of the above two blocks of code to a ""Scroll to Bottom"" button, and press this button manually after adding the new node, it all works fine! Please can anyone isolate the cause of this bug, or offer a fix/workaround?",2014/08/24,"['https://Stackoverflow.com/questions/25467734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313909/']","Give it a Name + +``` + + + // ...... + + + +``` + +Then you can just Hide() + +``` +myFlyout.Hide(); + +``` + +[FlyoutBase.Hide method](http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.primitives.flyoutbase.hide.aspx)","You need to get it first. Then you can call `Hide`. + +``` +FlyoutBase.GetAttachedFlyout((FrameworkElement)LayoutRoot).Hide(); + +```" +25467734,"I have a JXTreeTable with an add button. The button works as expected: it adds a new node to the end, with values that (for the purpose of testing) are hard-coded into my program. The line: + +``` +modelSupport.fireChildAdded(new TreePath(root), noOfChildren-1, dataNode); + +``` + +tells the JXTreeTable to recognise the update made to the TreeTableModel, and to refresh accordingly. + +I then execute: + +``` +treeTable.changeSelection(treeTable.getRowCount()-1, 0, false, false); + +``` + +to automatically select this new node. This works as expected, BUT I also expected it to automatically scroll to bring this new node into sight, which it does not. Instead, it scrolls to show only the penultimate node, leaving the new node hidden just slightly beyond view. + +I've also tried using tricks to programmatically scroll to the final record. However, this code: + +``` +JScrollBar vertical = scrollPane.getVerticalScrollBar(); +vertical.setValue(vertical.getMaximum()); + +``` + +revealed the same problem. + +Bizarrely, if I attach either of the above two blocks of code to a ""Scroll to Bottom"" button, and press this button manually after adding the new node, it all works fine! Please can anyone isolate the cause of this bug, or offer a fix/workaround?",2014/08/24,"['https://Stackoverflow.com/questions/25467734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313909/']","``` +public void btnRestart_Click(object sender, RoutedEventArgs) +{ + ((((sender as Button).Parent as StackPanel).Parent as StackPanel).Parent as Flyout).Hide(); +} + +``` + +Very ugly but should work.","You need to get it first. Then you can call `Hide`. + +``` +FlyoutBase.GetAttachedFlyout((FrameworkElement)LayoutRoot).Hide(); + +```" +45658,"I move an elbow from my IK bone and the other arm moves too. Why is that? how can i solve it? +Help =([![enter image description here](https://i.stack.imgur.com/ZMiDL.png)](https://i.stack.imgur.com/ZMiDL.png)",2016/01/26,"['https://blender.stackexchange.com/questions/45658', 'https://blender.stackexchange.com', 'https://blender.stackexchange.com/users/21236/']","Your bone is called Bone.011 so it's not getting mirrored properly. You need to make sure the bones have names like hand.l, hand.r (for the other side) and so on. + +For the automatic weighting, you can just redo it by reparenting the mesh to the armature with automatic weights. + +Another thing that can break the automatic weights are incorrect normals, so you can go into edit mode, select all vertices and Recalculate Normals to make sure they are good.","When you link your armature to your mesh using automatic weight, sometimes the weight is applied wrongly to the mesh. It could be that you did not apply your mesh's scale. + +1. In object mode, Hit `Alt``A` +2. Select ""Scale"" from the Drop down menu. + +You could also go to the vertex group control panel and manually remove those vertices that aren't suppose to be affected by the bone." +49192427,"How could **this.\_arr** array be updated inside a socket.io callback? + +``` +class SocketClass{ + + constructor(server) { + this._arr = []; + this._io = require('socket.io').listen(server); + this._initListeners(); + } + + _initListeners() { + this._io.on('connection', (socket, arr) => { + socket.on('event1', (data) => { + this._arr.push(data); + }); + + }); + } + +} + +``` + +The problem is that **this.\_arr** is ***undefined*** inside a callback. I suppose it's because **this** is referencing to callback function itself...",2018/03/09,"['https://Stackoverflow.com/questions/49192427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1811410/']","I'd use a data attribute for this. Store a template for the image src and a path value for each button, then update the image src values accordingly for each button click... + +```js +var buttons = document.querySelectorAll(""button""); +var images = document.querySelectorAll(""img""); + +[].forEach.call(buttons, function(button) { + + button.addEventListener(""click"", function() { + + var path = this.getAttribute(""data-path""); + + [].forEach.call(images, function(img) { + + var src = img.getAttribute(""data-src-template"").replace(""{path}"", path); + img.src = src; + console.log(img.src); + + }); + }); +}); + +// intialize the image... +document.querySelector(""#one"").click(); +``` + +```html +
+
+
+ + + + +``` + +This gives you what you need as well as being flexible if the path format ever changes, since everything you need is defined in the html and the script never needs to change. + +For example, if you decided to move the images into another subfolder you could just change the image tag and it would still work... + +``` + + +```","I believe you can do that by creating script. +If you assign ID to each of the `` tags you can then do something like: + +``` +document.getElementById('exampleID').innerHTML=""""; + +``` + +Eventually put each `` tag in DIV + +``` +
+ +
+ +``` + +Script: + +``` +document.getElementById('someid').innerHTML=""""; + +``` + +I did not test it but the answer should be really close to this. + +I hope this was helpfull." +612405,"Let $E:\mathbb{R} \to \mathbb{R}$ be an infinitely continuously differentiable function and $E$ is not zero function +such that $$E(u+v)=E(u)E(v).$$ +Show that $E(x)=e^{ax}$ for some $a\in \mathbb{R}$. + +My partial answer: + +The function $x\mapsto e^{ax}$ satisfies the properties immediately. +For $y=0$, we have $E(x)=E(x)E(0)$. Thus, $E(0)=1$. Let $y\in \mathbb{R}$ is fixed, then +$$E'(x+y)=E(y)E'(x)$$. + +I don't know how to continue the answer. +Could you give me some hint? +Thanks.",2013/12/19,"['https://math.stackexchange.com/questions/612405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27594/']","$\newcommand{\+}{^{\dagger}}% + \newcommand{\angles}[1]{\left\langle #1 \right\rangle}% + \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}% + \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}% + \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}% + \newcommand{\dd}{{\rm d}}% + \newcommand{\ds}[1]{\displaystyle{#1}}% + \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}% + \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}% + \newcommand{\fermi}{\,{\rm f}}% + \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}% + \newcommand{\half}{{1 \over 2}}% + \newcommand{\ic}{{\rm i}}% + \newcommand{\iff}{\Longleftrightarrow} + \newcommand{\imp}{\Longrightarrow}% + \newcommand{\isdiv}{\,\left.\right\vert\,}% + \newcommand{\ket}[1]{\left\vert #1\right\rangle}% + \newcommand{\ol}[1]{\overline{#1}}% + \newcommand{\pars}[1]{\left( #1 \right)}% + \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} + \newcommand{\pp}{{\cal P}}% + \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}% + \newcommand{\sech}{\,{\rm sech}}% + \newcommand{\sgn}{\,{\rm sgn}}% + \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} + \newcommand{\ul}[1]{\underline{#1}}% + \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$ +The probability density for the step $n$ is given by +$\ds{{\rm p}\pars{\vec{r}\_{n}} \equiv {\delta\pars{r\_{n} - 1} \over 2\pi}}$. The probability density $\pp\_{N}\pars{\vec{r}}$ of arriving at $\vec{r}$ after $N$ steps is given by: + +> +> \begin{align} +> \pp\_{N}\pars{\vec{r}} +> &\equiv +> \int\dd^{2}\vec{r}\_{1}\,{\rm p}\pars{\vec{r}\_{1}}\ldots +> \int\dd^{2}\vec{r}\_{N}{\rm p}\pars{\vec{r}\_{N}} +> \delta\pars{\vec{r} - \sum\_{\ell = 1}^{N}\vec{r}\_{\ell}} +> \\[3mm]&= +> \int\dd^{2}\vec{r}\_{1}\,{\rm p}\pars{\vec{r}\_{1}}\ldots +> \int\dd^{2}\vec{r}\_{N}{\rm p}\pars{\vec{r}\_{N}} +> \int\exp\pars{\ic\vec{k}\cdot\bracks{\vec{r} - \sum\_{\ell = 1}^{N}\vec{r}\_{\ell}}} +> \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} +> \\[3mm]&= +> \int\expo{\ic\vec{k}\cdot\vec{r}} +> \bracks{\int\dd^{2}\vec{R}\,{\rm p}\pars{\vec{R}}\expo{-\ic\vec{k}\cdot\vec{R}}}^{N} +> \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} +> = +> \int\expo{\ic\vec{k}\cdot\vec{r}} +> \bracks{\int\_{0}^{2\pi}\expo{-\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi}}^{N} +> \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} +> \end{align} +> + +However +$$ +\int\_{0}^{2\pi}\expo{-\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi} += +\int\_{-\pi}^{\pi}\expo{\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi} += +{1 \over \pi}\int\_{0}^{\pi}\expo{\ic k\cos\pars{\theta}}\,\dd\theta += +{\rm J}\_{0}\pars{k} +$$ +where ${\rm J}\_{\nu}\pars{k}$ is the +$\nu$-$\it\mbox{order Bessel Function of the First Kind}$. + +> +> \begin{align} +> \pp\_{N}\pars{\vec{r}} +> &= +> \int\expo{\ic\vec{k}\cdot\vec{r}}{\rm J}\_{0}^{N}\pars{k} +> \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} +> = +> {1 \over 2\pi}\int\_{0}^{\infty}\dd k\,k\,{\rm J}\_{0}^{N}\pars{k}\int\_{0}^{2\pi} +> \expo{\ic kr\cos\pars{\theta}}\,{\dd\theta \over 2\pi} +> \end{align} +> $$ +> \color{#ff0000}{\pp\_{N}\pars{\vec{r}} +> = +> {1 \over 2\pi}\int\_{0}^{\infty}{\rm J}\_{0}\pars{kr}{\rm J}\_{0}^{N}\pars{k}k +> \,\dd k} +> $$ +> + +The probability ${\rm P}\_{N{\Huge\circ}}$ that it returns to the unit circle after $N$ steps is given by: +\begin{align} +\color{#0000ff}{\large{\rm P}\_{N{\Huge\circ}}} +&= +\int\_{r\ <\ 1}\pp\_{N}\pars{\vec{r}}\,\dd^{2}\vec{r} += +\int\_{0}^{\infty}\overbrace{\bracks{\int\_{0}^{1}{\rm J}\_{0}\pars{kr}r\,\dd r}} +^{{\rm J}\_{1}\pars{k}/k} +{\rm J}\_{0}^{N}\pars{k}k\,\dd k +\\[3mm]&= +\color{#0000ff}{\large\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +{\rm J}\_{0}^{N}\pars{k}\,\dd k} +\end{align} +We compute a few values with Wolfram Alpha: +$$ +\begin{array}{rclrcl} +{\rm P}\_{0{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +\,\dd k & = & 1\,,\quad +{\rm P}\_{1{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +{\rm J}\_{0}\pars{k}\,\dd k & = & \half +\\ +{\rm P}\_{2{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{2}\pars{k} +\,\dd k & = & {1 \over 3}\,,\quad +{\rm P}\_{3{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +{\rm J}\_{0}^{3}\pars{k}\,\dd k & = & {1 \over 4} +\\ +{\rm P}\_{4{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{4}\pars{k} +\,\dd k & = & {1 \over 5}\,,\quad +{\rm P}\_{5{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +{\rm J}\_{0}^{5}\pars{k}\,\dd k & = & {1 \over 6} +\end{array} +$$ + +It $\tt\large seems$ the exact result is +$\ds{% +{\rm P}\_{N{\Huge\circ}} += +\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{N}\pars{k} \,\dd k += +{1 \over N + 1}}$ + +Mathematica can solve this integral and it yields the $\ul{\mbox{exact result}}$ $\color{#0000ff}{\Large{1 \over N + 1}}$ when $\color{#ff0000}{\large\Re N > -1}$.","You can create a probility dristribution for the location after one step (the unit circle with a certain constant prbability). After two steps, I think that should be doable too. You can also carculate for each point the probability of entering de unit disk in the next step. Then, by combining the probability distribution ($P\_1(x,y)$) and the probability of ending in the disk $P\_2(x,y)$, you get +$$ +\int P\_1(x,y)P\_2(x,y) \,dx\,dy +$$" +612405,"Let $E:\mathbb{R} \to \mathbb{R}$ be an infinitely continuously differentiable function and $E$ is not zero function +such that $$E(u+v)=E(u)E(v).$$ +Show that $E(x)=e^{ax}$ for some $a\in \mathbb{R}$. + +My partial answer: + +The function $x\mapsto e^{ax}$ satisfies the properties immediately. +For $y=0$, we have $E(x)=E(x)E(0)$. Thus, $E(0)=1$. Let $y\in \mathbb{R}$ is fixed, then +$$E'(x+y)=E(y)E'(x)$$. + +I don't know how to continue the answer. +Could you give me some hint? +Thanks.",2013/12/19,"['https://math.stackexchange.com/questions/612405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27594/']","$\newcommand{\+}{^{\dagger}}% + \newcommand{\angles}[1]{\left\langle #1 \right\rangle}% + \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}% + \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}% + \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}% + \newcommand{\dd}{{\rm d}}% + \newcommand{\ds}[1]{\displaystyle{#1}}% + \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}% + \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}% + \newcommand{\fermi}{\,{\rm f}}% + \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}% + \newcommand{\half}{{1 \over 2}}% + \newcommand{\ic}{{\rm i}}% + \newcommand{\iff}{\Longleftrightarrow} + \newcommand{\imp}{\Longrightarrow}% + \newcommand{\isdiv}{\,\left.\right\vert\,}% + \newcommand{\ket}[1]{\left\vert #1\right\rangle}% + \newcommand{\ol}[1]{\overline{#1}}% + \newcommand{\pars}[1]{\left( #1 \right)}% + \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} + \newcommand{\pp}{{\cal P}}% + \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}% + \newcommand{\sech}{\,{\rm sech}}% + \newcommand{\sgn}{\,{\rm sgn}}% + \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} + \newcommand{\ul}[1]{\underline{#1}}% + \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$ +The probability density for the step $n$ is given by +$\ds{{\rm p}\pars{\vec{r}\_{n}} \equiv {\delta\pars{r\_{n} - 1} \over 2\pi}}$. The probability density $\pp\_{N}\pars{\vec{r}}$ of arriving at $\vec{r}$ after $N$ steps is given by: + +> +> \begin{align} +> \pp\_{N}\pars{\vec{r}} +> &\equiv +> \int\dd^{2}\vec{r}\_{1}\,{\rm p}\pars{\vec{r}\_{1}}\ldots +> \int\dd^{2}\vec{r}\_{N}{\rm p}\pars{\vec{r}\_{N}} +> \delta\pars{\vec{r} - \sum\_{\ell = 1}^{N}\vec{r}\_{\ell}} +> \\[3mm]&= +> \int\dd^{2}\vec{r}\_{1}\,{\rm p}\pars{\vec{r}\_{1}}\ldots +> \int\dd^{2}\vec{r}\_{N}{\rm p}\pars{\vec{r}\_{N}} +> \int\exp\pars{\ic\vec{k}\cdot\bracks{\vec{r} - \sum\_{\ell = 1}^{N}\vec{r}\_{\ell}}} +> \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} +> \\[3mm]&= +> \int\expo{\ic\vec{k}\cdot\vec{r}} +> \bracks{\int\dd^{2}\vec{R}\,{\rm p}\pars{\vec{R}}\expo{-\ic\vec{k}\cdot\vec{R}}}^{N} +> \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} +> = +> \int\expo{\ic\vec{k}\cdot\vec{r}} +> \bracks{\int\_{0}^{2\pi}\expo{-\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi}}^{N} +> \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} +> \end{align} +> + +However +$$ +\int\_{0}^{2\pi}\expo{-\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi} += +\int\_{-\pi}^{\pi}\expo{\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi} += +{1 \over \pi}\int\_{0}^{\pi}\expo{\ic k\cos\pars{\theta}}\,\dd\theta += +{\rm J}\_{0}\pars{k} +$$ +where ${\rm J}\_{\nu}\pars{k}$ is the +$\nu$-$\it\mbox{order Bessel Function of the First Kind}$. + +> +> \begin{align} +> \pp\_{N}\pars{\vec{r}} +> &= +> \int\expo{\ic\vec{k}\cdot\vec{r}}{\rm J}\_{0}^{N}\pars{k} +> \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} +> = +> {1 \over 2\pi}\int\_{0}^{\infty}\dd k\,k\,{\rm J}\_{0}^{N}\pars{k}\int\_{0}^{2\pi} +> \expo{\ic kr\cos\pars{\theta}}\,{\dd\theta \over 2\pi} +> \end{align} +> $$ +> \color{#ff0000}{\pp\_{N}\pars{\vec{r}} +> = +> {1 \over 2\pi}\int\_{0}^{\infty}{\rm J}\_{0}\pars{kr}{\rm J}\_{0}^{N}\pars{k}k +> \,\dd k} +> $$ +> + +The probability ${\rm P}\_{N{\Huge\circ}}$ that it returns to the unit circle after $N$ steps is given by: +\begin{align} +\color{#0000ff}{\large{\rm P}\_{N{\Huge\circ}}} +&= +\int\_{r\ <\ 1}\pp\_{N}\pars{\vec{r}}\,\dd^{2}\vec{r} += +\int\_{0}^{\infty}\overbrace{\bracks{\int\_{0}^{1}{\rm J}\_{0}\pars{kr}r\,\dd r}} +^{{\rm J}\_{1}\pars{k}/k} +{\rm J}\_{0}^{N}\pars{k}k\,\dd k +\\[3mm]&= +\color{#0000ff}{\large\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +{\rm J}\_{0}^{N}\pars{k}\,\dd k} +\end{align} +We compute a few values with Wolfram Alpha: +$$ +\begin{array}{rclrcl} +{\rm P}\_{0{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +\,\dd k & = & 1\,,\quad +{\rm P}\_{1{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +{\rm J}\_{0}\pars{k}\,\dd k & = & \half +\\ +{\rm P}\_{2{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{2}\pars{k} +\,\dd k & = & {1 \over 3}\,,\quad +{\rm P}\_{3{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +{\rm J}\_{0}^{3}\pars{k}\,\dd k & = & {1 \over 4} +\\ +{\rm P}\_{4{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{4}\pars{k} +\,\dd k & = & {1 \over 5}\,,\quad +{\rm P}\_{5{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +{\rm J}\_{0}^{5}\pars{k}\,\dd k & = & {1 \over 6} +\end{array} +$$ + +It $\tt\large seems$ the exact result is +$\ds{% +{\rm P}\_{N{\Huge\circ}} += +\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{N}\pars{k} \,\dd k += +{1 \over N + 1}}$ + +Mathematica can solve this integral and it yields the $\ul{\mbox{exact result}}$ $\color{#0000ff}{\Large{1 \over N + 1}}$ when $\color{#ff0000}{\large\Re N > -1}$.","This is not a complete answer, but is kind of long for a comment. + +For $t=2$, draw a picture. It's pretty easy to see the answer is $1/3$. + +For the $t=3$ case, let the angles be $\theta\_1$, $\theta\_2$, and $\theta\_3$. By symmetry, you can assume without loss of generality that $\theta\_1 = 0$. So you need to find the probability that +$\|\langle 1, 0 \rangle + \langle \cos\theta\_2, \sin\theta\_2 \rangle +\langle \cos\theta\_3,\sin\theta\_3\rangle \|<1$. A little computation shows that this is equals +$P(1+\cos\theta\_2+\cos\theta\_3+\cos(\theta\_2-\theta\_3)<0)$, where $\theta\_2$ and $\theta\_3$ are chosen independently from the uniform distribution on $[0,2\pi]$. That's as far as I got. + +This is the probability that the particle is in the unit disc *at time* $t=3$ (not $t$ equals 2 or 3)." +612405,"Let $E:\mathbb{R} \to \mathbb{R}$ be an infinitely continuously differentiable function and $E$ is not zero function +such that $$E(u+v)=E(u)E(v).$$ +Show that $E(x)=e^{ax}$ for some $a\in \mathbb{R}$. + +My partial answer: + +The function $x\mapsto e^{ax}$ satisfies the properties immediately. +For $y=0$, we have $E(x)=E(x)E(0)$. Thus, $E(0)=1$. Let $y\in \mathbb{R}$ is fixed, then +$$E'(x+y)=E(y)E'(x)$$. + +I don't know how to continue the answer. +Could you give me some hint? +Thanks.",2013/12/19,"['https://math.stackexchange.com/questions/612405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27594/']","$\newcommand{\+}{^{\dagger}}% + \newcommand{\angles}[1]{\left\langle #1 \right\rangle}% + \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}% + \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}% + \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}% + \newcommand{\dd}{{\rm d}}% + \newcommand{\ds}[1]{\displaystyle{#1}}% + \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}% + \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}% + \newcommand{\fermi}{\,{\rm f}}% + \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}% + \newcommand{\half}{{1 \over 2}}% + \newcommand{\ic}{{\rm i}}% + \newcommand{\iff}{\Longleftrightarrow} + \newcommand{\imp}{\Longrightarrow}% + \newcommand{\isdiv}{\,\left.\right\vert\,}% + \newcommand{\ket}[1]{\left\vert #1\right\rangle}% + \newcommand{\ol}[1]{\overline{#1}}% + \newcommand{\pars}[1]{\left( #1 \right)}% + \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} + \newcommand{\pp}{{\cal P}}% + \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}% + \newcommand{\sech}{\,{\rm sech}}% + \newcommand{\sgn}{\,{\rm sgn}}% + \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} + \newcommand{\ul}[1]{\underline{#1}}% + \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$ +The probability density for the step $n$ is given by +$\ds{{\rm p}\pars{\vec{r}\_{n}} \equiv {\delta\pars{r\_{n} - 1} \over 2\pi}}$. The probability density $\pp\_{N}\pars{\vec{r}}$ of arriving at $\vec{r}$ after $N$ steps is given by: + +> +> \begin{align} +> \pp\_{N}\pars{\vec{r}} +> &\equiv +> \int\dd^{2}\vec{r}\_{1}\,{\rm p}\pars{\vec{r}\_{1}}\ldots +> \int\dd^{2}\vec{r}\_{N}{\rm p}\pars{\vec{r}\_{N}} +> \delta\pars{\vec{r} - \sum\_{\ell = 1}^{N}\vec{r}\_{\ell}} +> \\[3mm]&= +> \int\dd^{2}\vec{r}\_{1}\,{\rm p}\pars{\vec{r}\_{1}}\ldots +> \int\dd^{2}\vec{r}\_{N}{\rm p}\pars{\vec{r}\_{N}} +> \int\exp\pars{\ic\vec{k}\cdot\bracks{\vec{r} - \sum\_{\ell = 1}^{N}\vec{r}\_{\ell}}} +> \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} +> \\[3mm]&= +> \int\expo{\ic\vec{k}\cdot\vec{r}} +> \bracks{\int\dd^{2}\vec{R}\,{\rm p}\pars{\vec{R}}\expo{-\ic\vec{k}\cdot\vec{R}}}^{N} +> \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} +> = +> \int\expo{\ic\vec{k}\cdot\vec{r}} +> \bracks{\int\_{0}^{2\pi}\expo{-\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi}}^{N} +> \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} +> \end{align} +> + +However +$$ +\int\_{0}^{2\pi}\expo{-\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi} += +\int\_{-\pi}^{\pi}\expo{\ic k\cos\pars{\theta}}\,{\dd\theta \over 2\pi} += +{1 \over \pi}\int\_{0}^{\pi}\expo{\ic k\cos\pars{\theta}}\,\dd\theta += +{\rm J}\_{0}\pars{k} +$$ +where ${\rm J}\_{\nu}\pars{k}$ is the +$\nu$-$\it\mbox{order Bessel Function of the First Kind}$. + +> +> \begin{align} +> \pp\_{N}\pars{\vec{r}} +> &= +> \int\expo{\ic\vec{k}\cdot\vec{r}}{\rm J}\_{0}^{N}\pars{k} +> \,{\dd^{2}\vec{k} \over \pars{2\pi}^{2}} +> = +> {1 \over 2\pi}\int\_{0}^{\infty}\dd k\,k\,{\rm J}\_{0}^{N}\pars{k}\int\_{0}^{2\pi} +> \expo{\ic kr\cos\pars{\theta}}\,{\dd\theta \over 2\pi} +> \end{align} +> $$ +> \color{#ff0000}{\pp\_{N}\pars{\vec{r}} +> = +> {1 \over 2\pi}\int\_{0}^{\infty}{\rm J}\_{0}\pars{kr}{\rm J}\_{0}^{N}\pars{k}k +> \,\dd k} +> $$ +> + +The probability ${\rm P}\_{N{\Huge\circ}}$ that it returns to the unit circle after $N$ steps is given by: +\begin{align} +\color{#0000ff}{\large{\rm P}\_{N{\Huge\circ}}} +&= +\int\_{r\ <\ 1}\pp\_{N}\pars{\vec{r}}\,\dd^{2}\vec{r} += +\int\_{0}^{\infty}\overbrace{\bracks{\int\_{0}^{1}{\rm J}\_{0}\pars{kr}r\,\dd r}} +^{{\rm J}\_{1}\pars{k}/k} +{\rm J}\_{0}^{N}\pars{k}k\,\dd k +\\[3mm]&= +\color{#0000ff}{\large\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +{\rm J}\_{0}^{N}\pars{k}\,\dd k} +\end{align} +We compute a few values with Wolfram Alpha: +$$ +\begin{array}{rclrcl} +{\rm P}\_{0{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +\,\dd k & = & 1\,,\quad +{\rm P}\_{1{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +{\rm J}\_{0}\pars{k}\,\dd k & = & \half +\\ +{\rm P}\_{2{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{2}\pars{k} +\,\dd k & = & {1 \over 3}\,,\quad +{\rm P}\_{3{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +{\rm J}\_{0}^{3}\pars{k}\,\dd k & = & {1 \over 4} +\\ +{\rm P}\_{4{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{4}\pars{k} +\,\dd k & = & {1 \over 5}\,,\quad +{\rm P}\_{5{\Huge\circ}} =\int\_{0}^{\infty}{\rm J}\_{1}\pars{k} +{\rm J}\_{0}^{5}\pars{k}\,\dd k & = & {1 \over 6} +\end{array} +$$ + +It $\tt\large seems$ the exact result is +$\ds{% +{\rm P}\_{N{\Huge\circ}} += +\int\_{0}^{\infty}{\rm J}\_{1}\pars{k}{\rm J}\_{0}^{N}\pars{k} \,\dd k += +{1 \over N + 1}}$ + +Mathematica can solve this integral and it yields the $\ul{\mbox{exact result}}$ $\color{#0000ff}{\Large{1 \over N + 1}}$ when $\color{#ff0000}{\large\Re N > -1}$.","This addresses the t=3 case: + +Assume you start at origin ($P\_0$), and without loss of generality, assume first move is to $P\_1=(1, 0)$. Your second move will be to $P\_2=(1 + cos(\theta), sin(\theta))$, where theta is uniform [0, $\pi$] (can ignore the [$\pi,2\pi$] range due to symmetry). Density function of $\theta$ is just $f(\theta)=\frac{1}{\pi}$ + +Draw unit-circles around $P\_0$ and $P\_2$, and let X be the second intersection point of these two circles (aside from $P\_1$). + +Now draw the quadrilateral $\overline{P\_0P\_1P\_2X}$. Turns out this is actually a rhombus, with each side of length 1. From geometry of parallel-lines, one can see that the angle $\angle P\_1P\_2X$ equals theta. Also, this angle $\theta$ subtends the arc of the $P\_2$ circle that is inside the $P\_0$ circle. + +Therefore, for any given $\theta$, the probability that a chosen point on the $P\_2$ circle will be inside the $P\_0$ circle is simply $\frac{\theta}{2\pi}$. + +Putting this all together, the probability that we return to the unit-circle after 3 moves is: +$\int^\pi\_0(1/\pi) \* (\theta/2\pi) d\theta = 1/4$" +612405,"Let $E:\mathbb{R} \to \mathbb{R}$ be an infinitely continuously differentiable function and $E$ is not zero function +such that $$E(u+v)=E(u)E(v).$$ +Show that $E(x)=e^{ax}$ for some $a\in \mathbb{R}$. + +My partial answer: + +The function $x\mapsto e^{ax}$ satisfies the properties immediately. +For $y=0$, we have $E(x)=E(x)E(0)$. Thus, $E(0)=1$. Let $y\in \mathbb{R}$ is fixed, then +$$E'(x+y)=E(y)E'(x)$$. + +I don't know how to continue the answer. +Could you give me some hint? +Thanks.",2013/12/19,"['https://math.stackexchange.com/questions/612405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27594/']","This is a classic problem, first solved by the Dutch mathematician J.C. Kluyver in 1905. He derives the result given in the [answer](https://math.stackexchange.com/a/612395/87355) of Felix Marin, that the probability to return to the unit disc after $n$ steps is $1/(n+1)$: + +![](https://ilorentz.org/beenakker/MO/Kluyver1.png) + +![](https://ilorentz.org/beenakker/MO/Kluyver2.png) + +For a purely geometric derivation, see [arXiv:1007.4870](https://arxiv.org/abs/1007.4870). (There the result is attributed to Rayleigh, but it appears Rayleigh only considered the large-$n$ limit.) See also this [MO posting.](https://mathoverflow.net/a/347336/11260)","You can create a probility dristribution for the location after one step (the unit circle with a certain constant prbability). After two steps, I think that should be doable too. You can also carculate for each point the probability of entering de unit disk in the next step. Then, by combining the probability distribution ($P\_1(x,y)$) and the probability of ending in the disk $P\_2(x,y)$, you get +$$ +\int P\_1(x,y)P\_2(x,y) \,dx\,dy +$$" +612405,"Let $E:\mathbb{R} \to \mathbb{R}$ be an infinitely continuously differentiable function and $E$ is not zero function +such that $$E(u+v)=E(u)E(v).$$ +Show that $E(x)=e^{ax}$ for some $a\in \mathbb{R}$. + +My partial answer: + +The function $x\mapsto e^{ax}$ satisfies the properties immediately. +For $y=0$, we have $E(x)=E(x)E(0)$. Thus, $E(0)=1$. Let $y\in \mathbb{R}$ is fixed, then +$$E'(x+y)=E(y)E'(x)$$. + +I don't know how to continue the answer. +Could you give me some hint? +Thanks.",2013/12/19,"['https://math.stackexchange.com/questions/612405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27594/']","This is a classic problem, first solved by the Dutch mathematician J.C. Kluyver in 1905. He derives the result given in the [answer](https://math.stackexchange.com/a/612395/87355) of Felix Marin, that the probability to return to the unit disc after $n$ steps is $1/(n+1)$: + +![](https://ilorentz.org/beenakker/MO/Kluyver1.png) + +![](https://ilorentz.org/beenakker/MO/Kluyver2.png) + +For a purely geometric derivation, see [arXiv:1007.4870](https://arxiv.org/abs/1007.4870). (There the result is attributed to Rayleigh, but it appears Rayleigh only considered the large-$n$ limit.) See also this [MO posting.](https://mathoverflow.net/a/347336/11260)","This is not a complete answer, but is kind of long for a comment. + +For $t=2$, draw a picture. It's pretty easy to see the answer is $1/3$. + +For the $t=3$ case, let the angles be $\theta\_1$, $\theta\_2$, and $\theta\_3$. By symmetry, you can assume without loss of generality that $\theta\_1 = 0$. So you need to find the probability that +$\|\langle 1, 0 \rangle + \langle \cos\theta\_2, \sin\theta\_2 \rangle +\langle \cos\theta\_3,\sin\theta\_3\rangle \|<1$. A little computation shows that this is equals +$P(1+\cos\theta\_2+\cos\theta\_3+\cos(\theta\_2-\theta\_3)<0)$, where $\theta\_2$ and $\theta\_3$ are chosen independently from the uniform distribution on $[0,2\pi]$. That's as far as I got. + +This is the probability that the particle is in the unit disc *at time* $t=3$ (not $t$ equals 2 or 3)." +612405,"Let $E:\mathbb{R} \to \mathbb{R}$ be an infinitely continuously differentiable function and $E$ is not zero function +such that $$E(u+v)=E(u)E(v).$$ +Show that $E(x)=e^{ax}$ for some $a\in \mathbb{R}$. + +My partial answer: + +The function $x\mapsto e^{ax}$ satisfies the properties immediately. +For $y=0$, we have $E(x)=E(x)E(0)$. Thus, $E(0)=1$. Let $y\in \mathbb{R}$ is fixed, then +$$E'(x+y)=E(y)E'(x)$$. + +I don't know how to continue the answer. +Could you give me some hint? +Thanks.",2013/12/19,"['https://math.stackexchange.com/questions/612405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27594/']","This is a classic problem, first solved by the Dutch mathematician J.C. Kluyver in 1905. He derives the result given in the [answer](https://math.stackexchange.com/a/612395/87355) of Felix Marin, that the probability to return to the unit disc after $n$ steps is $1/(n+1)$: + +![](https://ilorentz.org/beenakker/MO/Kluyver1.png) + +![](https://ilorentz.org/beenakker/MO/Kluyver2.png) + +For a purely geometric derivation, see [arXiv:1007.4870](https://arxiv.org/abs/1007.4870). (There the result is attributed to Rayleigh, but it appears Rayleigh only considered the large-$n$ limit.) See also this [MO posting.](https://mathoverflow.net/a/347336/11260)","This addresses the t=3 case: + +Assume you start at origin ($P\_0$), and without loss of generality, assume first move is to $P\_1=(1, 0)$. Your second move will be to $P\_2=(1 + cos(\theta), sin(\theta))$, where theta is uniform [0, $\pi$] (can ignore the [$\pi,2\pi$] range due to symmetry). Density function of $\theta$ is just $f(\theta)=\frac{1}{\pi}$ + +Draw unit-circles around $P\_0$ and $P\_2$, and let X be the second intersection point of these two circles (aside from $P\_1$). + +Now draw the quadrilateral $\overline{P\_0P\_1P\_2X}$. Turns out this is actually a rhombus, with each side of length 1. From geometry of parallel-lines, one can see that the angle $\angle P\_1P\_2X$ equals theta. Also, this angle $\theta$ subtends the arc of the $P\_2$ circle that is inside the $P\_0$ circle. + +Therefore, for any given $\theta$, the probability that a chosen point on the $P\_2$ circle will be inside the $P\_0$ circle is simply $\frac{\theta}{2\pi}$. + +Putting this all together, the probability that we return to the unit-circle after 3 moves is: +$\int^\pi\_0(1/\pi) \* (\theta/2\pi) d\theta = 1/4$" +41073364,"how can I ignore all the duplicating records and get only those which do not have a tie in mysql for example; from the following data set; + +``` +1|item1| data1 +2|item1| data2 +3|item2| data3 +4|item3| data4 + +``` + +I want to get this get this kind of results; + +``` +3|item2| data3 +4|item3| data4 + +```",2016/12/10,"['https://Stackoverflow.com/questions/41073364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6870393/']","before call third function you need to call first two functions that will assign values to $this->a & $this->b + +try below code : + +``` +protected $a; +protected $b; + +function fast() +{ + $a=10; + $this->a = $a; +} +function slow() +{ + $b=20; + $this->b = $b; +} +function avg() +{ + $c=$this->a+$this->b; + echo $c; +} + +} +$relay = new race(); +$relay->fast(); +$relay->slow(); +$relay->avg(); + +```","Firstly, you are using object properties incorrectly. You need to first specify the scope of the property; in this case, I used protected scopes so you can extend the class as and when you need to use the properties directly. + +Also, note if you're trying to add an **unset** variable, it will not work, you can either add this instance to your `__construct()` or set them to equal to 0 in the property instance. + +``` +class Speed { + + protected $_a = 0; + protected $_b = 0; + + public function fast() + { + $this->_a = 20; + return $this; + } + + public function slow() + { + $this->_b = 10; + return $this; + } + + public function avg() + { + return $this->_a + $this->_b; + } + +} + +``` + +This can then be used like this: + +``` +$s = new Speed(); +$s->fast()->slow(); + +// todo: add logic + +echo $s->avg(); + +``` + +--- + +**Update:** + +Just side note, try **not** to output directly to a view in a method closure. Use templates, return the values from your methods and output them to a template." +3090509,"--- + +I have been trying to simplify the following summation with the intention of breaking it into less complex summations, but I keep getting stuck no matter what I try: + +$$\sum\_{i=0}^{k-1} 3^{i} \cdot \frac{\sqrt{\frac{n}{3^i}}}{\log\_{2}\frac{n}{3^i}}$$ + +Among the things I tried was raising to the power of $1/2$\* the upper part of the fraction to cancel out the $3^i$, but after that I'm left with $\sqrt{n\,3^i}$ anyways without any clear steps to simplify further. Also tried putting the lower part of the fraction as a difference of logarithms, but got stuck in the same way. I even tried to use the change of base identity to put the lower part of the fraction in terms of $\log\_3(2)$ and see if I could have canceled something but no luck. + +Just simplifying the sum would be good enough since I can try to take it from there by substituting $k\; (k = \log\_3(n)$ in case that is useful).",2019/01/28,"['https://math.stackexchange.com/questions/3090509', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/635189/']","The issue expression can be presented in the form of +$$S={\large\sum\limits\_{i=0}^{k-1}}3^i\dfrac{\sqrt{\dfrac n{3^i}}}{\log\_2\dfrac{n}{3^i}} += \sqrt n \log\_32{\large\sum\limits\_{i=0}^{k-1}}\dfrac{(\sqrt3)^i}{\log\_3{n}-i},$$ +so +$$S=\sqrt n \log\_32\left(3^{k/2}\Phi(\sqrt3,1,k-\log\_3n)-\Phi(\sqrt3,1,-\log\_3n)\right)$$ +(see also [Wolfram Alpha](https://www.wolframalpha.com/input/?i=sum_(i%3D0,k-1)%20a%5Ei%2F(b-i))), where + +> +> $$\Phi(z,s,a) = {\large\sum\limits\_{m=0}^\infty\,\dfrac +> {z^m}{(m+a)^s}}$$ +> is [Lerch transcendent](http://mathworld.wolfram.com/LerchTranscendent.html). +> +> +> + +Assuming $k=\lceil\log\_3n -1\rceil,$ can be built the plots [for the issue sums](https://www.wolframalpha.com/input/?i=plot%20table%20sum_(j%3D0,%20ceil(log_3(n)%20-2))%20(sqrt(n)%20%20log_3(2)%203.0%5E(j%2F2)%20%2F(log_3(n)-j)),%20%7Bn,3,99%7D) + +[![The issue sums](https://i.stack.imgur.com/oUqlQ.png)](https://i.stack.imgur.com/oUqlQ.png) + +and [via Lerch transcendent](https://www.wolframalpha.com/input/?i=plot%20%7Bsqrt(n)%20%20log_3(2)%20(3%5E(ceil(log_3%20n%20-1)%2F2)%20HurwitzLerchPhi(sqrt3,%201,%20ceil(log_3%20n%20-1)%20-%20log_3(n))%20-%20HurwitzLerchPhi(sqrt3,%201,%20%20-%20log_3%20(n)))%7D,%20n%3D3,%2099) + +[![Lerch transcendent sums](https://i.stack.imgur.com/3jXyV.png)](https://i.stack.imgur.com/3jXyV.png) + +Easy to see that summation via Lerch transcendent is correct.","If I plug +$$ +\sum\_{i=0}^{\log\_3(n)-1}3^i \frac{\sqrt{\frac{n}{3^i}}}{\log\_2(\frac{n}{3^i})} +$$ +into Wolfram Mathematica, then I get no simplification, so an nice simplification probably does not exist. The best we can probably do is, with thanks to @NoChance, +$$ +\sum\_{i=0}^{\log\_3(n)-1}3^i \frac{\sqrt{\frac{n}{3^i}}}{\log\_2(\frac{n}{3^i})} = \sum\_{i=0}^{\log\_3(n)-1}3^i \frac{\sqrt{\frac{n}{3^i}}}{\log\_2(n)-\log\_2(3^i))} \\ +=\sum\_{i=0}^{\log\_3(n)-1} 3^i\frac{\sqrt{\frac{n}{3^i}}}{\log\_2(n)-i\log\_2(3))} \\ +=\sum\_{i=0}^{\log\_3(n)-1} \sqrt{n}\frac{3^i\sqrt{\frac{1}{3^i}}}{\log\_2(n)-i\log\_2(3))} \\ += \sqrt{n}\sum\_{i=0}^{\log\_3(n)-1}\frac{\sqrt{3^i}}{\log\_2(n)-i\log\_2(3))} \\ +$$ +If I plug this into Wolfram Mathematica, then we see that we get something +$$ +\sqrt{n}\sum\_{i=0}^{\log\_3(n)-1}\frac{\sqrt{3^i}}{\log\_2(n)-i\log\_2(3))} = -\frac{n\bigg(\log(3-\sqrt{3})-\log(3)\bigg)}{\log\_2(3)}-\frac{\sqrt{n}HyperGeometric2F1\bigg(1,\log\_3(3n),2+\log\_3(n),\frac{1}{\sqrt{3}}\bigg)}{\sqrt{3}\log\_2{3n}} +$$ +If we look at Wikipedia, , for some more info on the Hypergeometric2F1 we see that there are no further simplifications listed." +50219323,"My project is very similar to the famous ATM problem. I have to create a hotel check in/check out system. I have to get the user input for the last name and confirm it. However when I try to return the string, it tells me it cant convert string to int. + +``` +import java.util.Scanner; + +public class Keyboard { + private Scanner input; + String lastName; + + public Keyboard() { + input = new Scanner( System.in); + } + + public int getInput() { + lastName = input.nextLine(); + return lastName; + } + +} + +```",2018/05/07,"['https://Stackoverflow.com/questions/50219323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9732237/']","The problem is that your server time is different from Google server time. And when you validate received token from google it might be that token will be valid in 1 or n seconds. That's why you get an error `JWT not yet valid` + +To fix it you can synchronize time of your server with google server time. Google doc how to do this is ","You can configure the system time as per google or if your computer is part of a domain and you don't want to change the domain controller config, then you can pass a clock object in the Validateasync method like this: + +``` +var googleUser = await GoogleJsonWebSignature.ValidateAsync(token, new GoogleJsonWebSignature.ValidationSettings() + { + Clock = new clock(), + Audience = new[] { ""your client id"" } + }); + +``` + +For this, you need to make a class implementing the IClock interface as below: + +``` + public class clock : IClock + { + public DateTime Now => DateTime.Now.AddMinutes(5); + + public DateTime UtcNow => DateTime.UtcNow.AddMinutes(5); + } + +``` + +In this, you can set the time accordingly like if my system time is 5 min. ahead of google time, I'll add 5 min., then your token will be successfully validated. + +And to check the google time, you can make use of JwtSecurityTokenHandler class like: + +``` +var handler = new JwtSecurityTokenHandler(); +var tokenS = handler.ReadToken(token) as JwtSecurityToken; + +``` + +in tokenS, you will have a property as issued at which will provide the UTC time, if you want local time then you can use `toLocal()` method on that property and compare that time to your system's time." +23341774,"I am trying to create a form that updates user information stored in an Oracle database, the updates are not going through correctly and I can't see a problem as I have the form printing out the SQL being submitted to oracle and it all checks out. + +Here is the php that forms the connection: + +``` + + +``` + +Here is the form with an example or two of the forms inputs: + +``` +
+
+ > + + + + + + + + + + +``` + +And here is the handler php: + +``` +""; +print $sql; +oci_free_statement($stmt); +oci_close($conn); +?> + +``` + +I am very new to php and using it with Oracle so it is likely to be something obvious... + +Thanks in advance! + +Bob P",2014/04/28,"['https://Stackoverflow.com/questions/23341774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3548774/']","Try this: + +``` +$conn = oci_connect(""user"",""pass"", ""conn""); + +$sql = ""UPDATE Members SET firstname=:firstname, lastname=:lastname, dob=:dob, membertype=:membertype, groupid=:groupid, houseno=:houseno, street=:street, town=:town, county=:county, postcode=:postcode where memberid=:memberid;""; +$stmt = oci_parse($conn, $update); +oci_bind_by_name($stmt, ':firstname', $firstname); +oci_bind_by_name($stmt, ':lastname', $lastname); +oci_bind_by_name($stmt, ':dob', $dob); +oci_bind_by_name($stmt, ':membertype', $membertype); +oci_bind_by_name($stmt, ':groupid', $groupid); +oci_bind_by_name($stmt, ':houseno', $houseno); +oci_bind_by_name($stmt, ':street', $street); +oci_bind_by_name($stmt, ':county', $county); +oci_bind_by_name($stmt, ':postcode', $postcode); +oci_bind_by_name($stmt, ':memberid', $memberid); + +$result = oci_execute($stmt, OCI_DEFAULT); +if (!$result) { + echo oci_error(); +} + +oci_commit($conn); + +``` + +This way of working will reduce your sql injection a little aswell.. I wrote this just out of my head.. Havn't had the chance of testing this, because I don't have the oracle DB for it. But try it.","You haven't enclosed $memberid variable in qoutes in query + +.... `where memberid='$memberid';""`" +39871505,"``` +public static void main(String[] args) throws Exception { + Connection connection = getMySqlConnection(); + CallableStatement proc = connection.prepareCall(""{ call LCD_GetDispInfoAllTimeTable() }""); + proc.registerOutParameter(1, Types.INTEGER); + proc.execute(); + int returnValue = proc.getInt(1); + System.out.println(returnValue + """"); +// conn.close(); + } + + public static Connection getMySqlConnection() throws Exception { + String driver = ""com.mysql.jdbc.Driver""; + String url = """"; + String username = """"; + String password = """"; + + Class.forName(driver); + Connection conn = DriverManager.getConnection(url, username, password); + return conn; + } + } + +``` + +When I run this code I see a Exception in thread ""main"" java.sql.SQLException: Parameter index of 1 is out of range (1, 0) , why ? + +This procedure return : + +``` +Niemstów 07 pętla 10 05:33:00 3673114 11558169 754378 1 +NŻ Niemstów 05 16 05:35:00 3669905 11556510 754379 3 +NŻ Niemstów 03 16 05:37:00 3666969 11555665 754380 3 + +``` + +My procedure ; + +``` +CREATE DEFINER=`root`@`%` PROCEDURE `LCD_GetDispInfoAllTimeTable`() +BEGIN + + SELECT bs.name as bsName, tt.busstoptype as bsType, tt.time as ttTime, bs.longitude as lon, bs.latitude as lat, tt.timetable_id as ttID, + Bus_Stop_Status_GET( tt.timetable_id, bst.timetable_id, bst.busstate_id ) as bus_stop_status -- 0 zrobiony, 1 - aktualny, 2- pomiędzy, 3 następne + FROM (SELECT * FROM mpk_currentbusstate ORDER BY changestime desc LIMIT 1 )bst + join mpk_timetable t ON( bst.timetable_id = t.timetable_id ) + join mpk_timetable tt ON ( t.linelogin_id = tt.linelogin_id AND t.line_id = tt.line_id AND t.brigade = tt.brigade AND t.rate = tt.rate + and t.schedudle_id = tt.schedudle_id) + LEFT JOIN mpk_busstop bs ON (bs.busstop_id = tt.busstop_id) + LEFT JOIN mpk_busstate bt ON( bst.busstate_id = bt.busstate_id ); + +END + +```",2016/10/05,"['https://Stackoverflow.com/questions/39871505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","You need to specify the parameter in your call String: + +`CallableStatement proc = connection.prepareCall(""{ call LCD_GetDispInfoAllTimeTable(?) }"");` + +Notice that `?`, it says that there is a parameter to be set. Now it knows that there is a parameter to be set, just like methods in Java or some other language. If you wanted to use multiple parameters you can write multiple `?`, like: `...LCD_GetDispInfoAllTimeTable(?, ?, ?)`.","as far as your procedecure declaration is concerned, its code is: + +``` + CREATE DEFINER=`root`@`%` PROCEDURE `LCD_GetDispInfoAllTimeTable`() + BEGIN + SELECT bs.name as bsName, tt.busstoptype as bsType, tt.time as ttTime, + bs.longitude as lon, bs.latitude as lat, tt.timetable_id as ttID, + Bus_Stop + +``` + +where the procedure definition does NOT contain any parameter definition, +so setParameter or registerOutParameter, cannot be applied for this procedure" +8412710,"I want to make a custom include tag (like `{% smart_include something %}` ), which realize what kind a thing we want to include and then call regular `{% include %}` tag. That's should be something like this: + +``` +@register.simple_tag +def smart_include(something): + if something == ""post"": + template_name = ""post.html"" + return regular_include_tag(template_name) + +``` + +Is there a way to use `{% include %}` tag in python code, and how exactly? + +**UPD.** turn's out, the best way to solve this problem is just use `render_to_string` shortcut",2011/12/07,"['https://Stackoverflow.com/questions/8412710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/277262/']","I assume there is a reason why you are not doing: + +``` +{% if foo %} + {% include 'hello.html' %} +{% endif %} + +``` + +If `something` is a fixed number, you can use [inclusion tags](https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags-inclusion-tags). In your template instead of `{% smart_tag something %}`, you have `{% something %}`, then your tag library looks like this: + +``` +@register.inclusion_tag('post.html') +def something(): + return {} # return an empty dict + +``` + +Finally, you can replicate the functionality of the include tag. This snippet should point you in the right direction: + +``` +filepath = '/full/path/to/your/template/%s' % something +try: + fp = open(filepath, 'r') + output = fp.read() + fp.close() +except IOError: + output = '' +try: + t = Template(output, name=filepath) + return t.render(context) +except TemplateSyntaxError, e: + return '' # Fail silently. +return output + +```","If you look into the **django.template.loader\_tags** you fill find a function **do\_include** which is basically the function that is called when we use {% include %}. + +So you should be able to import it call the function itself in python. + +I have not tried this but I think it should work" +8412710,"I want to make a custom include tag (like `{% smart_include something %}` ), which realize what kind a thing we want to include and then call regular `{% include %}` tag. That's should be something like this: + +``` +@register.simple_tag +def smart_include(something): + if something == ""post"": + template_name = ""post.html"" + return regular_include_tag(template_name) + +``` + +Is there a way to use `{% include %}` tag in python code, and how exactly? + +**UPD.** turn's out, the best way to solve this problem is just use `render_to_string` shortcut",2011/12/07,"['https://Stackoverflow.com/questions/8412710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/277262/']","I assume there is a reason why you are not doing: + +``` +{% if foo %} + {% include 'hello.html' %} +{% endif %} + +``` + +If `something` is a fixed number, you can use [inclusion tags](https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags-inclusion-tags). In your template instead of `{% smart_tag something %}`, you have `{% something %}`, then your tag library looks like this: + +``` +@register.inclusion_tag('post.html') +def something(): + return {} # return an empty dict + +``` + +Finally, you can replicate the functionality of the include tag. This snippet should point you in the right direction: + +``` +filepath = '/full/path/to/your/template/%s' % something +try: + fp = open(filepath, 'r') + output = fp.read() + fp.close() +except IOError: + output = '' +try: + t = Template(output, name=filepath) + return t.render(context) +except TemplateSyntaxError, e: + return '' # Fail silently. +return output + +```","`render_to_string` will render the given template\_name to an html string + +```py +from django.template.loader import render_to_string + +template_name = 'post.html' +optional_context = {} +html = render_to_string(template_name, optional_context) + +```" +73394,"This guy put money into my bank account and wanted me to send some of it to another person in Nigeria. 500.00 to be exact. But since he wired money into my account I was unable to touch the money. + +He told me it was a donation to UNICEF. Since I was unable to take the money out he threatened to get the police involved and said he was going to. I got a bunch of missed calls from an unknown number and a really unprofessional email from a guy who supposedly worked for UNICEF saying I had 4 hours until I am suppose to be visited by police and that there was nowhere I could run to. The money is still in my account I have not touched it. + +He has my bank account info, and I just want to know where I stand legally.",2016/12/06,"['https://money.stackexchange.com/questions/73394', 'https://money.stackexchange.com', 'https://money.stackexchange.com/users/51081/']","> +> He has my bank account info, and I just want to know where I stand legally. +> +> +> + +Legally you can't keep the money. It would either go back to the originator or to Government unclaimed department. + +> +> I got a bunch of missed calls from an unknown number and a really unprofessional email from a guy who supposedly worked for UNICEF saying I had 4 hours until I am suppose to be visited by police and that there was nowhere I could run to. +> +> +> + +These are common tactics employed to ensure you take some action and transfer the real money somewhere. Do not succumb to such tactics. + +> +> The money is still in my account I have not touched it. +> +> +> + +Advise your Bank immediately that there is this deposit into your account that is not your's. Let the bank take appropriate action. + +Do not authorize Bank to debit your account. The max you can do is authorize the bank to reverse this transaction. The best is stick to statement that said transaction is not yours and Bank is free to do what is right. + +There is a small difference and very important. If you authorize bank to debit, you have initiated a payment. So if the original payment were revered by originator bank, you are left short of money. However if your instructions are very clear, that this specific transaction can be reversed, you cannot be additionally debited if this transaction is reversed. + +> +> He has my bank account info, +> +> +> + +Depending on how easy / difficult, my suggestion would be monitor this account closely, best is if you can close it out and open a new one.","To add to @Dheer's answer, this is almost certainly a scam. The money deposited into your account is not from a person that made an honest mistake with account numbers. It's coming from someone that has access to ""send"" money that isn't their own. I don't know exactly what they're doing to ""send"" the money but at some point in the near future your bank will claw that money back from you on the grounds that it was illegitimately transferred to you in the first place. If you send someone money on the premise that you're returning this money then that will be a separate transaction which won't be undone when the deposit in question is undone. + +Another possibility is that this person has gained access to an account from which they can send domestic wires but not international wires. Their hope is to send money to someone domestically (you) and that this person will then send the money on to Nigeria. If you comply with them; you, in a worst case scenario, could be seen as a money laundering accomplice in addition to having the deposit taken back from you. It's not very likely you wouldn't be seen as another victim of a scam but people have been thrown in jail for less. + +You should not respond to this person at all. Don't answer the phone when they call and ignore their emails. Don't delete the emails, it's possible that someone at the bank or LE want them. Call your bank immediately and tell them what's up." +176688,"I am converting RPG files in NTF\_Lambert\_II\_etendu to wgs\_84 using: + +``` +ogr2ogr -t_srs EPSG:4326 ilot_2008_027_wgs84_2.shp ilot_2008_027.shp + +``` + +but the result is off by about 30 meters. Surprisingly, the same conversion using Qgis works fine. Could anybody tell me how to correct that or how to investigate the exact transformation qgis is doing? + +The proj file of the intial file is : + +``` +PROJCS[""NTF_Lambert_II_etendu"",GEOGCS[""GCS_NTF"",DATUM[""D_NTF"",SPHEROID[""Clarke_1880_IGN"",6378249.2,293.46602]],PRIMEM[""Greenwich"",0.0],UNIT[""Degree"",0.0174532925199433]],PROJECTION[""Lambert_Conformal_Conic""],PARAMETER[""False_Easting"",600000.0],PARAMETER[""False_Northing"",2200000.0],PARAMETER[""Central_Meridian"",2.3372291667],PARAMETER[""Standard_Parallel_1"",45.8989188889],PARAMETER[""Standard_Parallel_2"",47.6960144444],PARAMETER[""Scale_Factor"",1.0],PARAMETER[""Latitude_Of_Origin"",46.8],UNIT[""Meter"",1.0]] + +```",2016/01/13,"['https://gis.stackexchange.com/questions/176688', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/49290/']","NTF Lambert II has a `towgs84` datum shift, but that is not included in the .prj file. + +The .prj file uses a different naming for the projection, so the EPSG code finder might fail. + +I assume QGIS assigns the correct EPSG code (maybe in the .qpj file), and makes a standard transformation from one EPSG code to another using full towgs84 parameters. + +You should get the same result with ogr2ogr using EPSG codes 27572, 7411, 7412 or 7421 as `-s_srs`.","As mentioned by @AndreJ specifying the EPSG code makes it work. Specifically the following work: + +``` +ogr2ogr -t_srs EPSG:4326 -s_srs EPSG:7421 ilot_2008_027_wgs84_2.shp ilot_2008_027.shp + +``` + +Alternatively, I was trying to use the qgis python API to do it all in python using qgis but could not get it to work." +3909,"Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. +We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. +I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. +Would I be able to use a fishing kayak like a regular touring/recreation kayak? + +Thanks",2013/04/01,"['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']","I have used a touring kayak for fishing, and it works out ok. You can rig up a rod holder in your cockpit, but paddling is a bit awkward, though this is probably also a problem with any kayak used for fishing. + +It might be somewhat difficult to use a fishing kayak on overnight trips given that most fishing kayaks are sit on top (SOT) and have no internal storage.","I would recommend checking out something like Hobie's Mirage pedal driven kayaks. With their spiffy pedal drive, you can trivially outrun(outpedal?) just about anyone while hardly breaking a sweat. Additionally, because you power yourself with your feet, your hands are free for fishing. The mirage drive is also quiet as a corpse. No splashing sounds from your paddles, whatsoever. + +A guy I know has one of their fishing-specific models, and loves it. + +However, if you ever want to go on an overnight camping adventure via your kayaks, the storage capacity of the Hobies is pretty bad, and while in general portaging kayaks is no fun, portaging a Hobie kayak would be especially miserable. + +Otherwise, you could try getting a tandem traditional kayak. Perhaps you can sweet-talk your wife into paddling while you fish?" +3909,"Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. +We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. +I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. +Would I be able to use a fishing kayak like a regular touring/recreation kayak? + +Thanks",2013/04/01,"['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']","Yes, there is definitely a performance difference between different types of kayaks. In fact, there are performance differences among the same types of kayaks. For example, a 14-foot kayak will always track more straightly than a 10-foot kayak. A wide recreational kayak will always have more primary stability than a narrower touring kayak. + +Even if you both get the same type of kayak I suspect you'll find they work differently for each of you. No doubt you both do not weigh the same -- if you're heavier, a given kayak will sit lower in the water than for her. That may result in increased stability, or it could mean that you capsize easily. Alternatively, consider height and armspan: if she's short she may find it difficult to paddle in a wide rec kayak where the paddle is constantly bumping the edge of the boat. + +In short: you should each look for a kayak that suits you. That means you will see performance differences between the two kayaks, but if the boats really do suit each of you, that won't be a problem because you've found something that fits well. As to a fishing kayak specifically, if you get a longer kayak than her you'll likely be able to keep up with her on a day trip (though at the expense of maneuverability). + +Of course, keeping up with a partner is about more than the just the kayak. The paddle will also make a difference (especially its weight as it relates to your fatigue), and paddling technique can be a big difference between feeling good at the end of an outing and feeling whipped.","I have used a touring kayak for fishing, and it works out ok. You can rig up a rod holder in your cockpit, but paddling is a bit awkward, though this is probably also a problem with any kayak used for fishing. + +It might be somewhat difficult to use a fishing kayak on overnight trips given that most fishing kayaks are sit on top (SOT) and have no internal storage." +3909,"Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. +We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. +I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. +Would I be able to use a fishing kayak like a regular touring/recreation kayak? + +Thanks",2013/04/01,"['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']","I have used a touring kayak for fishing, and it works out ok. You can rig up a rod holder in your cockpit, but paddling is a bit awkward, though this is probably also a problem with any kayak used for fishing. + +It might be somewhat difficult to use a fishing kayak on overnight trips given that most fishing kayaks are sit on top (SOT) and have no internal storage.","I have been considering just the same. I have come up with two kayacks that I like. The first is a fishing kayak by kudo. It tracks well and speed is good. I have a strong upper body so it makes it easier for me but its all in the core. Try different techniques as you will get tired just doing one. + +The other kayak is a 14 foot looksha by Necky. I have been eyeing that one for 3 years now. It is a sit in oh the kudo is a sit on top which I stood up in and tried paddle boarding on it. Great stability. The looksha tracks and maneuvers great. + +Not stable enough for fishing, what are you going to do when you land the mother of all fishes? How you bring that into the boat? Consider what you do more spending time with the wife or fishing in a kayak?" +3909,"Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. +We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. +I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. +Would I be able to use a fishing kayak like a regular touring/recreation kayak? + +Thanks",2013/04/01,"['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']","Yes, there is definitely a performance difference between different types of kayaks. In fact, there are performance differences among the same types of kayaks. For example, a 14-foot kayak will always track more straightly than a 10-foot kayak. A wide recreational kayak will always have more primary stability than a narrower touring kayak. + +Even if you both get the same type of kayak I suspect you'll find they work differently for each of you. No doubt you both do not weigh the same -- if you're heavier, a given kayak will sit lower in the water than for her. That may result in increased stability, or it could mean that you capsize easily. Alternatively, consider height and armspan: if she's short she may find it difficult to paddle in a wide rec kayak where the paddle is constantly bumping the edge of the boat. + +In short: you should each look for a kayak that suits you. That means you will see performance differences between the two kayaks, but if the boats really do suit each of you, that won't be a problem because you've found something that fits well. As to a fishing kayak specifically, if you get a longer kayak than her you'll likely be able to keep up with her on a day trip (though at the expense of maneuverability). + +Of course, keeping up with a partner is about more than the just the kayak. The paddle will also make a difference (especially its weight as it relates to your fatigue), and paddling technique can be a big difference between feeling good at the end of an outing and feeling whipped.","I would recommend checking out something like Hobie's Mirage pedal driven kayaks. With their spiffy pedal drive, you can trivially outrun(outpedal?) just about anyone while hardly breaking a sweat. Additionally, because you power yourself with your feet, your hands are free for fishing. The mirage drive is also quiet as a corpse. No splashing sounds from your paddles, whatsoever. + +A guy I know has one of their fishing-specific models, and loves it. + +However, if you ever want to go on an overnight camping adventure via your kayaks, the storage capacity of the Hobies is pretty bad, and while in general portaging kayaks is no fun, portaging a Hobie kayak would be especially miserable. + +Otherwise, you could try getting a tandem traditional kayak. Perhaps you can sweet-talk your wife into paddling while you fish?" +3909,"Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. +We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. +I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. +Would I be able to use a fishing kayak like a regular touring/recreation kayak? + +Thanks",2013/04/01,"['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']","There are a few differences between the SOT kayaks and a touring kayak that you'll want to consider. + +**Length** + +SOT kayaks tend to be shorter and wider than touring boats. This can make SOT's a little more stable but a longer boat will track better (go straight). The more rough the water you want to travel in the longer boat you want. + +**Storage** + +Touring boats will have much more storage in them as that's what they're meant to do. It's usually covered storage in the bow and stern of the boat. Sometimes SOT's have storage but most of the time it's sitting on top of the boat with you. Having gear on top of the boat makes it more accessible but easier to lose in the waves. + +**Ease of Use** + +SOT's are easy to use. Just sit on them and go. Touring boats take a little practice getting into and out of. A nylon or neoprene skirt to go around the cockpit and around your waist is a good thing to have in rough water or just to prevent drips from the paddle falling onto your lap. Using a skirt makes them a little more complicated to get into an out of though. + +**Cost** + +Touring boats tend to be longer and have more features so they'll probably cost you more. All the SOT's I've seen are made out of roto-molded plastic which is the least expensive to make. You can get touring boats out of roto-molded plastic, thermoformed plastic or fiberglass. Roto-molded is cheaper, heavier but very durable. Thermoformed is lighter and faster but more expensive. Fibreglass is the most expensive, the fastest but the most fragile. + +**Weather conditions** + +Rougher conditions in the water will warrant a longer boat and probably one of the touring variety. The longer boats will be more stable and you'll be much more dry being inside the touring boat with a skirt covering the cockpit. + +Hope that helps.","I would recommend checking out something like Hobie's Mirage pedal driven kayaks. With their spiffy pedal drive, you can trivially outrun(outpedal?) just about anyone while hardly breaking a sweat. Additionally, because you power yourself with your feet, your hands are free for fishing. The mirage drive is also quiet as a corpse. No splashing sounds from your paddles, whatsoever. + +A guy I know has one of their fishing-specific models, and loves it. + +However, if you ever want to go on an overnight camping adventure via your kayaks, the storage capacity of the Hobies is pretty bad, and while in general portaging kayaks is no fun, portaging a Hobie kayak would be especially miserable. + +Otherwise, you could try getting a tandem traditional kayak. Perhaps you can sweet-talk your wife into paddling while you fish?" +3909,"Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. +We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. +I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. +Would I be able to use a fishing kayak like a regular touring/recreation kayak? + +Thanks",2013/04/01,"['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']","Yes, there is definitely a performance difference between different types of kayaks. In fact, there are performance differences among the same types of kayaks. For example, a 14-foot kayak will always track more straightly than a 10-foot kayak. A wide recreational kayak will always have more primary stability than a narrower touring kayak. + +Even if you both get the same type of kayak I suspect you'll find they work differently for each of you. No doubt you both do not weigh the same -- if you're heavier, a given kayak will sit lower in the water than for her. That may result in increased stability, or it could mean that you capsize easily. Alternatively, consider height and armspan: if she's short she may find it difficult to paddle in a wide rec kayak where the paddle is constantly bumping the edge of the boat. + +In short: you should each look for a kayak that suits you. That means you will see performance differences between the two kayaks, but if the boats really do suit each of you, that won't be a problem because you've found something that fits well. As to a fishing kayak specifically, if you get a longer kayak than her you'll likely be able to keep up with her on a day trip (though at the expense of maneuverability). + +Of course, keeping up with a partner is about more than the just the kayak. The paddle will also make a difference (especially its weight as it relates to your fatigue), and paddling technique can be a big difference between feeling good at the end of an outing and feeling whipped.","There are a few differences between the SOT kayaks and a touring kayak that you'll want to consider. + +**Length** + +SOT kayaks tend to be shorter and wider than touring boats. This can make SOT's a little more stable but a longer boat will track better (go straight). The more rough the water you want to travel in the longer boat you want. + +**Storage** + +Touring boats will have much more storage in them as that's what they're meant to do. It's usually covered storage in the bow and stern of the boat. Sometimes SOT's have storage but most of the time it's sitting on top of the boat with you. Having gear on top of the boat makes it more accessible but easier to lose in the waves. + +**Ease of Use** + +SOT's are easy to use. Just sit on them and go. Touring boats take a little practice getting into and out of. A nylon or neoprene skirt to go around the cockpit and around your waist is a good thing to have in rough water or just to prevent drips from the paddle falling onto your lap. Using a skirt makes them a little more complicated to get into an out of though. + +**Cost** + +Touring boats tend to be longer and have more features so they'll probably cost you more. All the SOT's I've seen are made out of roto-molded plastic which is the least expensive to make. You can get touring boats out of roto-molded plastic, thermoformed plastic or fiberglass. Roto-molded is cheaper, heavier but very durable. Thermoformed is lighter and faster but more expensive. Fibreglass is the most expensive, the fastest but the most fragile. + +**Weather conditions** + +Rougher conditions in the water will warrant a longer boat and probably one of the touring variety. The longer boats will be more stable and you'll be much more dry being inside the touring boat with a skirt covering the cockpit. + +Hope that helps." +3909,"Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. +We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. +I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. +Would I be able to use a fishing kayak like a regular touring/recreation kayak? + +Thanks",2013/04/01,"['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']","Yes, there is definitely a performance difference between different types of kayaks. In fact, there are performance differences among the same types of kayaks. For example, a 14-foot kayak will always track more straightly than a 10-foot kayak. A wide recreational kayak will always have more primary stability than a narrower touring kayak. + +Even if you both get the same type of kayak I suspect you'll find they work differently for each of you. No doubt you both do not weigh the same -- if you're heavier, a given kayak will sit lower in the water than for her. That may result in increased stability, or it could mean that you capsize easily. Alternatively, consider height and armspan: if she's short she may find it difficult to paddle in a wide rec kayak where the paddle is constantly bumping the edge of the boat. + +In short: you should each look for a kayak that suits you. That means you will see performance differences between the two kayaks, but if the boats really do suit each of you, that won't be a problem because you've found something that fits well. As to a fishing kayak specifically, if you get a longer kayak than her you'll likely be able to keep up with her on a day trip (though at the expense of maneuverability). + +Of course, keeping up with a partner is about more than the just the kayak. The paddle will also make a difference (especially its weight as it relates to your fatigue), and paddling technique can be a big difference between feeling good at the end of an outing and feeling whipped.","I have been considering just the same. I have come up with two kayacks that I like. The first is a fishing kayak by kudo. It tracks well and speed is good. I have a strong upper body so it makes it easier for me but its all in the core. Try different techniques as you will get tired just doing one. + +The other kayak is a 14 foot looksha by Necky. I have been eyeing that one for 3 years now. It is a sit in oh the kudo is a sit on top which I stood up in and tried paddle boarding on it. Great stability. The looksha tracks and maneuvers great. + +Not stable enough for fishing, what are you going to do when you land the mother of all fishes? How you bring that into the boat? Consider what you do more spending time with the wife or fishing in a kayak?" +3909,"Last year my wife and I rented a couple of SOT kayaks and used them to paddle around our local lake. We enjoyed it so much we have decided to purchase our own this year. +We are looking at some entry level kayaks to use at the lakes and rivers here in Illinois. +I am also an avid fisherman and I would like to get a fishing kayak but I don't know if there is a difference, performance wise, between a fishing kayak and a touring/recreational kayak. I don't want to struggle to keep up with my wife if we decide to kayak for 4 to 5 hours on a river or lake. +Would I be able to use a fishing kayak like a regular touring/recreation kayak? + +Thanks",2013/04/01,"['https://outdoors.stackexchange.com/questions/3909', 'https://outdoors.stackexchange.com', 'https://outdoors.stackexchange.com/users/2174/']","There are a few differences between the SOT kayaks and a touring kayak that you'll want to consider. + +**Length** + +SOT kayaks tend to be shorter and wider than touring boats. This can make SOT's a little more stable but a longer boat will track better (go straight). The more rough the water you want to travel in the longer boat you want. + +**Storage** + +Touring boats will have much more storage in them as that's what they're meant to do. It's usually covered storage in the bow and stern of the boat. Sometimes SOT's have storage but most of the time it's sitting on top of the boat with you. Having gear on top of the boat makes it more accessible but easier to lose in the waves. + +**Ease of Use** + +SOT's are easy to use. Just sit on them and go. Touring boats take a little practice getting into and out of. A nylon or neoprene skirt to go around the cockpit and around your waist is a good thing to have in rough water or just to prevent drips from the paddle falling onto your lap. Using a skirt makes them a little more complicated to get into an out of though. + +**Cost** + +Touring boats tend to be longer and have more features so they'll probably cost you more. All the SOT's I've seen are made out of roto-molded plastic which is the least expensive to make. You can get touring boats out of roto-molded plastic, thermoformed plastic or fiberglass. Roto-molded is cheaper, heavier but very durable. Thermoformed is lighter and faster but more expensive. Fibreglass is the most expensive, the fastest but the most fragile. + +**Weather conditions** + +Rougher conditions in the water will warrant a longer boat and probably one of the touring variety. The longer boats will be more stable and you'll be much more dry being inside the touring boat with a skirt covering the cockpit. + +Hope that helps.","I have been considering just the same. I have come up with two kayacks that I like. The first is a fishing kayak by kudo. It tracks well and speed is good. I have a strong upper body so it makes it easier for me but its all in the core. Try different techniques as you will get tired just doing one. + +The other kayak is a 14 foot looksha by Necky. I have been eyeing that one for 3 years now. It is a sit in oh the kudo is a sit on top which I stood up in and tried paddle boarding on it. Great stability. The looksha tracks and maneuvers great. + +Not stable enough for fishing, what are you going to do when you land the mother of all fishes? How you bring that into the boat? Consider what you do more spending time with the wife or fishing in a kayak?" +652362,"Consider the differential equation +$$x^2y''+3(x-x^2)y'-3y=0$$ + +$(a)$ Find the recurrence equation and first three nonzero terms of the series solution in powers of $$ corresponding to the larger root of the indicial equation. + +$(b)$ What would be the form of a second linearly independent solution of this differential equation? + +I found the indicial equation to be $r(r-1)+3r-3 = 0$, so the two roots are $r\_1=-3$ and $r\_2=1$. + +And the recurrence relation is $a\_n = \dfrac{3(n-1+r)a\_{n-1}}{(n+r)(n+r-1)+3(n+r)-3}$ + +set $r=1$, then $a\_n = \dfrac{3na\_{n-1}}{(n+3)(n+1)-3}$. And I can figure out first linearly independent solution. + +But for $r=-3$,then $a\_n = \dfrac{3(n-4)a\_{n-1}}{(n-3)(n-1)-3}$, if let $a\_0$ be an arbitrary constant, then $a\_1 =\dfrac{3(-3)a\_0}{(-2)(0)}$, which doesn't work. + +Then how do I figure out the second linearly independent solution?",2014/01/26,"['https://math.stackexchange.com/questions/652362', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59036/']","Here is the procedure. + +Denote the two roots by $r\_1$ and $r\_2$, with $r\_1 \gt r\_2$. + +The Method of Frobenius will always generate a solution corresponding to $r\_1$, but **may** generate a solution for the smaller second root $r\_2$ of the indicial equation. + +If the method fails for $r\_2$, then an approach is to keep the recursion solution in terms of $r$ and use it to find the coefficients $a\_n$ (for $n \ge 1$), in terms of both $r$ and $a\_0$, where $a\_0 \ne 0$. For ease, $a\_0$ is typically chose to be one. + +Using this more general form and the coefficients, the two independent solutions can be written as: + +$$y\_1(r, x) = x^r \sum\_{n=0}^\infty ~ a\_n(r)x^n = \sum\_{n=0}^\infty ~ a\_n(r)x^{n+r} \\y\_2(r,x) = \dfrac{\partial}{\partial r}[(r - r\_2)y\_1(r, x)]~\Bigr|\_{r=r\_2}$$ + +You should be able to use this approach and show: + +$$y(x) = y\_1(x) + y\_2(x) = \dfrac{c\_1(3x(3x^2 + 3x+ 2) + 2)}{x^3} + \dfrac{c\_2e^{3x}}{x^3}$$","Let me rewrite your ODE as follows: + +$$L[y] = p\_0 y'' + p\_1 y' + p\_2 y = 0,$$ where $p\_i(x)$ are the coefficients of the equation. If you know one of the two linear indepent solutions of the homogenous part (indeed the whole ode is homogenouse), say $y\_1$, you can obtain $y\_2$ ($y = A y\_1+B y\_2$) by using the method of *variation of parameters*. + +Let me show you. + +Set $y = A(x)y\_1$ and substitute back into the original ode: + +$$p\_0 (A''y\_1 + 2A'y\_1' + A y\_1'') + p\_1 (A'y\_1 + A y\_1') + p\_2 A y\_1 = 0,$$ + +arrange terms in order to get a ODE-1 for $A(x)$: + +$$ A'' + \left(\frac{2y'\_1}{y\_1} + \frac{p\_1 y\_1}{p\_0} \right) A' + \frac{1}{p\_0} L[y\_1] A= 0,$$ + +since $L[y\_1]=0$, $A$ can be obtained by solving this equation in terms of an integrating factor as follows: + +$$\frac{d}{dx} (u A') = u \cdot 0 = 0,$$ + +where $u = e^{\int \left(\frac{2y'\_1}{y\_1} + \frac{p\_1 y\_1}{p\_0} \right) \, dx}$. It yields: + +$$uA' = a\_2 \Rightarrow A = a\_1 + a\_2 \int \frac{dx}{u},$$ + +and hence the solution, $y = a\_1 y\_1 + a\_2 y\_1 \int \frac{dx}{u}$, being $a\_i$ constants of integration. + +I hope this is useful to you. + +Cheers!" +652362,"Consider the differential equation +$$x^2y''+3(x-x^2)y'-3y=0$$ + +$(a)$ Find the recurrence equation and first three nonzero terms of the series solution in powers of $$ corresponding to the larger root of the indicial equation. + +$(b)$ What would be the form of a second linearly independent solution of this differential equation? + +I found the indicial equation to be $r(r-1)+3r-3 = 0$, so the two roots are $r\_1=-3$ and $r\_2=1$. + +And the recurrence relation is $a\_n = \dfrac{3(n-1+r)a\_{n-1}}{(n+r)(n+r-1)+3(n+r)-3}$ + +set $r=1$, then $a\_n = \dfrac{3na\_{n-1}}{(n+3)(n+1)-3}$. And I can figure out first linearly independent solution. + +But for $r=-3$,then $a\_n = \dfrac{3(n-4)a\_{n-1}}{(n-3)(n-1)-3}$, if let $a\_0$ be an arbitrary constant, then $a\_1 =\dfrac{3(-3)a\_0}{(-2)(0)}$, which doesn't work. + +Then how do I figure out the second linearly independent solution?",2014/01/26,"['https://math.stackexchange.com/questions/652362', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59036/']","Here is the procedure. + +Denote the two roots by $r\_1$ and $r\_2$, with $r\_1 \gt r\_2$. + +The Method of Frobenius will always generate a solution corresponding to $r\_1$, but **may** generate a solution for the smaller second root $r\_2$ of the indicial equation. + +If the method fails for $r\_2$, then an approach is to keep the recursion solution in terms of $r$ and use it to find the coefficients $a\_n$ (for $n \ge 1$), in terms of both $r$ and $a\_0$, where $a\_0 \ne 0$. For ease, $a\_0$ is typically chose to be one. + +Using this more general form and the coefficients, the two independent solutions can be written as: + +$$y\_1(r, x) = x^r \sum\_{n=0}^\infty ~ a\_n(r)x^n = \sum\_{n=0}^\infty ~ a\_n(r)x^{n+r} \\y\_2(r,x) = \dfrac{\partial}{\partial r}[(r - r\_2)y\_1(r, x)]~\Bigr|\_{r=r\_2}$$ + +You should be able to use this approach and show: + +$$y(x) = y\_1(x) + y\_2(x) = \dfrac{c\_1(3x(3x^2 + 3x+ 2) + 2)}{x^3} + \dfrac{c\_2e^{3x}}{x^3}$$","Let $y=\sum\limits\_{n=0}^\infty a\_nx^{n+r}$ , + +Then $y'=\sum\limits\_{n=0}^\infty(n+r)a\_nx^{n+r-1}$ + +$y''=\sum\limits\_{n=0}^\infty(n+r)(n+r-1)a\_nx^{n+r-2}$ + +$\therefore x^2\sum\limits\_{n=0}^\infty(n+r)(n+r-1)a\_nx^{n+r-2}+3(x-x^2)\sum\limits\_{n=0}^\infty(n+r)a\_nx^{n+r-1}-3\sum\limits\_{n=0}^\infty a\_nx^{n+r}=0$ + +$\sum\limits\_{n=0}^\infty(n+r)(n+r-1)a\_nx^{n+r}+\sum\limits\_{n=0}^\infty3(n+r)a\_nx^{n+r}-\sum\limits\_{n=0}^\infty3(n+r)a\_nx^{n+r+1}-\sum\limits\_{n=0}^\infty 3a\_nx^{n+r}=0$ + +$\sum\limits\_{n=0}^\infty(n+r+3)(n+r-1)a\_nx^{n+r}-\sum\limits\_{n=1}^\infty3(n+r-1)a\_{n-1}x^{n+r}=0$ + +$(r+3)(r-1)a\_0x^r+\sum\limits\_{n=1}^\infty((n+r+3)(n+r-1)a\_n-3(n+r-1)a\_{n-1})x^{n+r}=0$ + +The indicial equation is $(r+3)(r-1)=0$ , the two roots are $r\_1=-3$ and $r\_2=1$ . + +The recurrence relation is $(n+r+3)(n+r-1)a\_n-3(n+r-1)a\_{n-1}=0$ , i.e. $(n+r+3)(n+r-1)a\_n=3(n+r-1)a\_{n-1}$ + +Each root from the indical equations may not always only find one group of the linearly independent solutions, sometimes we can find more than one group of the linearly independent solutions at the same time. + +When we choose $r=-3$ , the recurrence relation becomes $n(n-4)a\_n=3(n-4)a\_{n-1}$ , which has a value of $n$ at $n=4$ so that it is independent to the recurrence relation. Besides $a\_0$ can chooes arbitrary, $a\_4$ can also chooes arbitrary. This makes the effect that we can find two groups of the linearly independent solutions that basing on $n=0$ to $n=3$ and $n=4$ to $n=+\infty$ respectively." +14653177,"I would like to create an array containing static methods (or containing references to static methods). I have tried to create an array of classes which implement an interface with the method. With this method, I would get the object and then call the method on it. This does not work for static methods. Is there a way of doing it in Java? + +EDIT: +Here is the method I have used so far: + +``` +interface TableElement{ + public Integer lookup(int value); +} + +TableElement[] table = new TableElement[] +{ + new TableElement() { public Integer lookup(int value) { return 0; } }, + new TableElement() { public Integer lookup(int value) { return value * 3; } }, + new TableElement() { public Integer lookup(int value) { return value * value + 3; } }, +}; + +public Integer find(int i, int value) { + return table[i].lookup(value); +} + +``` + +I would like the find method to be static.",2013/02/01,"['https://Stackoverflow.com/questions/14653177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1571830/']","Of course, you can have an array of `Method` and then you can call it using invoke, check these examples: [How do I invoke a private static method using reflection (Java)?](https://stackoverflow.com/questions/4770425/how-do-i-invoke-a-private-static-method-using-reflection-java)","If you can meet the following conditions: + +1. You know all of the keys at code generation time. +2. You know all of the values (methods) at code generation time. + +You can use code like this: + +``` +public class Table { + public static int hash(String key) { + /* you can use any type of key and whatever hash function is + * appropriate; this just meant as a simple example. + */ + return key.length(); + } + + public static Integer find(String s, int value) { + int h = hash(s); + + switch (h) { + case 4: // ""zero"" + if (s.equals(""zero"")) + return methodZero(value); + + case 6: // ""triple"" + if (s.equals(""triple"")) + return methodTriple(value); + + case 11: // ""squarePlus3"" + if (s.equals(""squarePlus3"")) + return methodSquarePlus3(value); + + default: + throw new UnsupportedOperationException(s); + } + } + + private static Integer methodZero(int value) { return 0; }; + private static Integer methodTriple(int value) { return value * 3; }; + private static Integer methodSquarePlus3(int value) { return value * value + 3; }; + + /** + * Just a demo. + */ + public static void main(String arguments[]) { + System.out.println(""Zero(5): "" + find(""zero"", 5)); + System.out.println(""Triple(5): "" + find(""triple"", 5)); + System.out.println(""SquarePlus3(5): "" + find(""squarePlus3"", 5)); + System.out.println(""boom!""); + find(""missingcode"", 5); + } +} + +``` + +If you need to relax either of the requirements I don't believe you can do everything statically. + +If you want to be able to add new keys, you'll have to create a normal hash table at adding time to store them. (You can check it in the `default` code.) + +If you want to be able to replace values, you'll have to use a level of indirection there, probably using `Method` objects or implementations of `Callable` (You can call these from within the body of the `methodZero` methods)." +29714078,"I am creating an application that takes input from user and save it permanently in form of table. + +``` + Console.Write(""\n\tEnter roll no\n\t""); + v= Convert.ToInt32(Console.ReadLine()); + a[i].setroll(v); + Console.Write(""\n\tEnter name\n\t""); + k = Console.ReadLine(); + a[i].setname(k); + Console.Write(""\n\tEnter father name\n\t""); + k = Console.ReadLine(); + a[i].setfname(k); + Console.Write(""\n\tEnter CNIC NO\n\t ""); + k = Console.ReadLine(); + a[i].setcnic(k); + Console.Write(""\n\tEnter permanent address\n\t""); + k = Console.ReadLine(); + a[i].setpaddress(k); + Console.Write(""\n\tEnter present address\n\t""); + k = Console.ReadLine(); + +``` + +I want to save all this info entered by user to be used later. How can I do this?",2015/04/18,"['https://Stackoverflow.com/questions/29714078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4663076/']","Refer to [System.IO.File](https://msdn.microsoft.com/en-us/library/System.IO.File(v=vs.110).aspx) + +And this may be a quick help: + +``` +using System; +public class Test +{ + public static void Main() + { + String Str = """"; + + for(int i =0;i<10;i++) + { + Str += i.ToString(); + } + Console.WriteLine(Str); + System.IO.File.WriteAllText(@""C:\SaveInfo.Txt"",Str); + } +} + +```","First you have to create an string array with your data then you can write it to the txt file + +``` +string[] lines = { ""First line"", ""Second line"", ""Third line"" }; + +``` + +WriteAllLines creates a file, writes a collection of strings to the file,and then closes the file. + +``` +System.IO.File.WriteAllLines(@""C:\Users\Public\TestFolder\WriteLines.txt"",lines); + +``` + +[How to: Write to a Text File (C# Programming Guide)](https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx)" +552323,"In PHP, will these always return the same values? + +``` +//example 1 + +$array = array(); + +if ($array) { + echo 'the array has items'; + +} + +// example 2 + +$array = array(); + +if (count($array)) { + echo 'the array has items'; + +} + +``` + +Thank you!",2009/02/16,"['https://Stackoverflow.com/questions/552323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31671/']","From , it says that an empty array is considered FALSE. + +--- + +(Quoted): +When converting to boolean, the following values are considered FALSE: + +* the boolean FALSE itself +* the integer 0 (zero) +* the float 0.0 (zero) +* the empty string, and the string ""0"" +* **an array with zero elements** +* an object with zero member variables (PHP 4 only) +* the special type NULL (including unset variables) +* SimpleXML objects created from empty tags + +--- + +Since + +* a count() of > 0 IS NOT FALSE +* a filled array IS NOT FALSE + +then both cases illustrated in the question will always work as expected.","Indeed they will. Converting an array to a bool will give you true if it is non-empty, and the count of an array is true with more than one element. + +See also: " +552323,"In PHP, will these always return the same values? + +``` +//example 1 + +$array = array(); + +if ($array) { + echo 'the array has items'; + +} + +// example 2 + +$array = array(); + +if (count($array)) { + echo 'the array has items'; + +} + +``` + +Thank you!",2009/02/16,"['https://Stackoverflow.com/questions/552323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31671/']","From , it says that an empty array is considered FALSE. + +--- + +(Quoted): +When converting to boolean, the following values are considered FALSE: + +* the boolean FALSE itself +* the integer 0 (zero) +* the float 0.0 (zero) +* the empty string, and the string ""0"" +* **an array with zero elements** +* an object with zero member variables (PHP 4 only) +* the special type NULL (including unset variables) +* SimpleXML objects created from empty tags + +--- + +Since + +* a count() of > 0 IS NOT FALSE +* a filled array IS NOT FALSE + +then both cases illustrated in the question will always work as expected.","Note that the second example (using `count()`) is significantly slower, by at least 50% on my system (over 10000 iterations). `count()` actually counts the elements of an array. I'm not positive, but I imagine casting an array to a boolean works much like `empty()`, and stops as soon as it finds at least one element." +552323,"In PHP, will these always return the same values? + +``` +//example 1 + +$array = array(); + +if ($array) { + echo 'the array has items'; + +} + +// example 2 + +$array = array(); + +if (count($array)) { + echo 'the array has items'; + +} + +``` + +Thank you!",2009/02/16,"['https://Stackoverflow.com/questions/552323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31671/']","From , it says that an empty array is considered FALSE. + +--- + +(Quoted): +When converting to boolean, the following values are considered FALSE: + +* the boolean FALSE itself +* the integer 0 (zero) +* the float 0.0 (zero) +* the empty string, and the string ""0"" +* **an array with zero elements** +* an object with zero member variables (PHP 4 only) +* the special type NULL (including unset variables) +* SimpleXML objects created from empty tags + +--- + +Since + +* a count() of > 0 IS NOT FALSE +* a filled array IS NOT FALSE + +then both cases illustrated in the question will always work as expected.","Those will always return the same value, but I find + +``` +$array = array(); + +if (empty($array)) { + echo 'the array is empty'; +} + +``` + +to be a lot more readable." +552323,"In PHP, will these always return the same values? + +``` +//example 1 + +$array = array(); + +if ($array) { + echo 'the array has items'; + +} + +// example 2 + +$array = array(); + +if (count($array)) { + echo 'the array has items'; + +} + +``` + +Thank you!",2009/02/16,"['https://Stackoverflow.com/questions/552323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31671/']","Note that the second example (using `count()`) is significantly slower, by at least 50% on my system (over 10000 iterations). `count()` actually counts the elements of an array. I'm not positive, but I imagine casting an array to a boolean works much like `empty()`, and stops as soon as it finds at least one element.","Indeed they will. Converting an array to a bool will give you true if it is non-empty, and the count of an array is true with more than one element. + +See also: " +552323,"In PHP, will these always return the same values? + +``` +//example 1 + +$array = array(); + +if ($array) { + echo 'the array has items'; + +} + +// example 2 + +$array = array(); + +if (count($array)) { + echo 'the array has items'; + +} + +``` + +Thank you!",2009/02/16,"['https://Stackoverflow.com/questions/552323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31671/']","Those will always return the same value, but I find + +``` +$array = array(); + +if (empty($array)) { + echo 'the array is empty'; +} + +``` + +to be a lot more readable.","Indeed they will. Converting an array to a bool will give you true if it is non-empty, and the count of an array is true with more than one element. + +See also: " +552323,"In PHP, will these always return the same values? + +``` +//example 1 + +$array = array(); + +if ($array) { + echo 'the array has items'; + +} + +// example 2 + +$array = array(); + +if (count($array)) { + echo 'the array has items'; + +} + +``` + +Thank you!",2009/02/16,"['https://Stackoverflow.com/questions/552323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31671/']","Those will always return the same value, but I find + +``` +$array = array(); + +if (empty($array)) { + echo 'the array is empty'; +} + +``` + +to be a lot more readable.","Note that the second example (using `count()`) is significantly slower, by at least 50% on my system (over 10000 iterations). `count()` actually counts the elements of an array. I'm not positive, but I imagine casting an array to a boolean works much like `empty()`, and stops as soon as it finds at least one element." +46975929,"I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? + +[This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).",2017/10/27,"['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']","For Python 3: + +``` +def jaccard_similarity(list1, list2): + s1 = set(list1) + s2 = set(list2) + return float(len(s1.intersection(s2)) / len(s1.union(s2))) +list1 = ['dog', 'cat', 'cat', 'rat'] +list2 = ['dog', 'cat', 'mouse'] +jaccard_similarity(list1, list2) +>>> 0.5 + +``` + +For Python2 use `return len(s1.intersection(s2)) / float(len(s1.union(s2)))`","If you'd like to include repeated elements, you can use `Counter`, which I would imagine is relatively quick since it's just an extended `dict` under the hood: + +``` +from collections import Counter +def jaccard_repeats(a, b): + """"""Jaccard similarity measure between input iterables, + allowing repeated elements"""""" + _a = Counter(a) + _b = Counter(b) + c = (_a - _b) + (_b - _a) + n = sum(c.values()) + return n/(len(a) + len(b) - n) + +list1 = ['dog', 'cat', 'rat', 'cat'] +list2 = ['dog', 'cat', 'rat'] +list3 = ['dog', 'cat', 'mouse'] + +jaccard_repeats(list1, list3) +>>> 0.75 + +jaccard_repeats(list1, list2) +>>> 0.16666666666666666 + +jaccard_repeats(list2, list3) +>>> 0.5 + +```" +46975929,"I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? + +[This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).",2017/10/27,"['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']","@aventinus I don't have enough reputation to add a comment to your answer, but just to make things clearer, your solution measures the `jaccard_similarity` but the function is misnamed as `jaccard_distance`, which is actually `1 - jaccard_similarity`","You can use the [Distance](https://github.com/doukremt/distance) library + +``` +#pip install Distance + +import distance + +distance.jaccard(""decide"", ""resize"") + +# Returns +0.7142857142857143 + +```" +46975929,"I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? + +[This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).",2017/10/27,"['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']","You can use the [Distance](https://github.com/doukremt/distance) library + +``` +#pip install Distance + +import distance + +distance.jaccard(""decide"", ""resize"") + +# Returns +0.7142857142857143 + +```","To avoid repetition of elements in the union (denominator), and a little bit faster I propose: + +``` +def Jaccar_score(lista1, lista2): + inter = len(list(set(lista_1) & set(lista_2))) + union = len(list(set(lista_1) | set(lista_2))) + return inter/union + +```" +46975929,"I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? + +[This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).",2017/10/27,"['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']","For Python 3: + +``` +def jaccard_similarity(list1, list2): + s1 = set(list1) + s2 = set(list2) + return float(len(s1.intersection(s2)) / len(s1.union(s2))) +list1 = ['dog', 'cat', 'cat', 'rat'] +list2 = ['dog', 'cat', 'mouse'] +jaccard_similarity(list1, list2) +>>> 0.5 + +``` + +For Python2 use `return len(s1.intersection(s2)) / float(len(s1.union(s2)))`","Assuming your usernames don't repeat, you can use the same idea: + +``` +def jaccard(a, b): + c = a.intersection(b) + return float(len(c)) / (len(a) + len(b) - len(c)) + +list1 = ['dog', 'cat', 'rat'] +list2 = ['dog', 'cat', 'mouse'] +# The intersection is ['dog', 'cat'] +# union is ['dog', 'cat', 'rat', 'mouse] +words1 = set(list1) +words2 = set(list2) +jaccard(words1, words2) +>>> 0.5 + +```" +46975929,"I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? + +[This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).",2017/10/27,"['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']","@Aventinus (I also cannot comment): Note that Jaccard *similarity* is an operation on sets, so in the denominator part it should also use sets (instead of lists). So for example `jaccard_similarity('aa', 'ab')` should result in `0.5`. + +``` +def jaccard_similarity(list1, list2): + intersection = len(set(list1).intersection(list2)) + union = len(set(list1)) + len(set(list2)) - intersection + + return intersection / union + +``` + +Note that in the intersection, there is no need to cast to list first. Also, the cast to float is not needed in Python 3.","Creator of the [Simphile NLP text similarity](https://github.com/brianrisk/simphile) package here. Simphile contains several text similarity methods, Jaccard being one of them. + +In the terminal install the package: + +``` +pip install simphile + +``` + +Then your code could be something like: + +``` +from simphile import jaccard_list_similarity + +list_a = ['cat', 'cat', 'dog'] +list_b = ['dog', 'dog', 'cat'] + +print(f""Jaccard Similarity: {jaccard_list_similarity(list_a, list_b)}"") + +``` + +The output being: + +``` +Jaccard Similarity: 0.5 + +``` + +Note that this solution accounts for repeated elements -- critical for text similarity; without it, the above example would show 100% similarity due to the fact that both lists as sets would reduce to {'dog', 'cat'}." +46975929,"I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? + +[This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).",2017/10/27,"['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']","I ended up writing my own solution after all: + +``` +def jaccard_similarity(list1, list2): + intersection = len(list(set(list1).intersection(list2))) + union = (len(set(list1)) + len(set(list2))) - intersection + return float(intersection) / union + +```","If you'd like to include repeated elements, you can use `Counter`, which I would imagine is relatively quick since it's just an extended `dict` under the hood: + +``` +from collections import Counter +def jaccard_repeats(a, b): + """"""Jaccard similarity measure between input iterables, + allowing repeated elements"""""" + _a = Counter(a) + _b = Counter(b) + c = (_a - _b) + (_b - _a) + n = sum(c.values()) + return n/(len(a) + len(b) - n) + +list1 = ['dog', 'cat', 'rat', 'cat'] +list2 = ['dog', 'cat', 'rat'] +list3 = ['dog', 'cat', 'mouse'] + +jaccard_repeats(list1, list3) +>>> 0.75 + +jaccard_repeats(list1, list2) +>>> 0.16666666666666666 + +jaccard_repeats(list2, list3) +>>> 0.5 + +```" +46975929,"I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? + +[This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).",2017/10/27,"['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']","Assuming your usernames don't repeat, you can use the same idea: + +``` +def jaccard(a, b): + c = a.intersection(b) + return float(len(c)) / (len(a) + len(b) - len(c)) + +list1 = ['dog', 'cat', 'rat'] +list2 = ['dog', 'cat', 'mouse'] +# The intersection is ['dog', 'cat'] +# union is ['dog', 'cat', 'rat', 'mouse] +words1 = set(list1) +words2 = set(list2) +jaccard(words1, words2) +>>> 0.5 + +```","You can use the [Distance](https://github.com/doukremt/distance) library + +``` +#pip install Distance + +import distance + +distance.jaccard(""decide"", ""resize"") + +# Returns +0.7142857142857143 + +```" +46975929,"I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? + +[This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).",2017/10/27,"['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']","I ended up writing my own solution after all: + +``` +def jaccard_similarity(list1, list2): + intersection = len(list(set(list1).intersection(list2))) + union = (len(set(list1)) + len(set(list2))) - intersection + return float(intersection) / union + +```","For Python 3: + +``` +def jaccard_similarity(list1, list2): + s1 = set(list1) + s2 = set(list2) + return float(len(s1.intersection(s2)) / len(s1.union(s2))) +list1 = ['dog', 'cat', 'cat', 'rat'] +list2 = ['dog', 'cat', 'mouse'] +jaccard_similarity(list1, list2) +>>> 0.5 + +``` + +For Python2 use `return len(s1.intersection(s2)) / float(len(s1.union(s2)))`" +46975929,"I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? + +[This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).",2017/10/27,"['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']","Assuming your usernames don't repeat, you can use the same idea: + +``` +def jaccard(a, b): + c = a.intersection(b) + return float(len(c)) / (len(a) + len(b) - len(c)) + +list1 = ['dog', 'cat', 'rat'] +list2 = ['dog', 'cat', 'mouse'] +# The intersection is ['dog', 'cat'] +# union is ['dog', 'cat', 'rat', 'mouse] +words1 = set(list1) +words2 = set(list2) +jaccard(words1, words2) +>>> 0.5 + +```","If you'd like to include repeated elements, you can use `Counter`, which I would imagine is relatively quick since it's just an extended `dict` under the hood: + +``` +from collections import Counter +def jaccard_repeats(a, b): + """"""Jaccard similarity measure between input iterables, + allowing repeated elements"""""" + _a = Counter(a) + _b = Counter(b) + c = (_a - _b) + (_b - _a) + n = sum(c.values()) + return n/(len(a) + len(b) - n) + +list1 = ['dog', 'cat', 'rat', 'cat'] +list2 = ['dog', 'cat', 'rat'] +list3 = ['dog', 'cat', 'mouse'] + +jaccard_repeats(list1, list3) +>>> 0.75 + +jaccard_repeats(list1, list2) +>>> 0.16666666666666666 + +jaccard_repeats(list2, list3) +>>> 0.5 + +```" +46975929,"I have two lists with usernames and I want to calculate the Jaccard similarity. Is it possible? + +[This](https://stackoverflow.com/questions/11911252/python-jaccard-distance-using-word-intersection-but-not-character-intersection) thread shows how to calculate the Jaccard Similarity between two strings, however I want to apply this to two lists, where each element is one word (e.g., a username).",2017/10/27,"['https://Stackoverflow.com/questions/46975929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873309/']","For Python 3: + +``` +def jaccard_similarity(list1, list2): + s1 = set(list1) + s2 = set(list2) + return float(len(s1.intersection(s2)) / len(s1.union(s2))) +list1 = ['dog', 'cat', 'cat', 'rat'] +list2 = ['dog', 'cat', 'mouse'] +jaccard_similarity(list1, list2) +>>> 0.5 + +``` + +For Python2 use `return len(s1.intersection(s2)) / float(len(s1.union(s2)))`","@aventinus I don't have enough reputation to add a comment to your answer, but just to make things clearer, your solution measures the `jaccard_similarity` but the function is misnamed as `jaccard_distance`, which is actually `1 - jaccard_similarity`" +4252818,"I have in trouble to trigger a click event when enter key is pressed. +When I use below codes, the live('click') event is triggered 3 times (which means the alert message is shown 3 thmes) when I press an enter key. Thanks in advance!! - KS from Korea + +``` +$('.searchWord').live('keypress', function(e) { + if(e.keyCode == 13) { + $('.bBtnSearchBoard').trigger('click'); + } +}); + +$('.bBtnSearchBoard').live('click', function() { + alert('a'); + +}); + +```",2010/11/23,"['https://Stackoverflow.com/questions/4252818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516975/']","It looks like you either have multiple `.searchWord` elements nested within each other, or, you have multiple `.bBtnSearchBoard` elements.","try keydown + +``` +$('.searchWord').live('keydown', function(e) { + if(e.keyCode == 13) { + $('.bBtnSearchBoard').trigger('click'); + } +}); + +```" +4252818,"I have in trouble to trigger a click event when enter key is pressed. +When I use below codes, the live('click') event is triggered 3 times (which means the alert message is shown 3 thmes) when I press an enter key. Thanks in advance!! - KS from Korea + +``` +$('.searchWord').live('keypress', function(e) { + if(e.keyCode == 13) { + $('.bBtnSearchBoard').trigger('click'); + } +}); + +$('.bBtnSearchBoard').live('click', function() { + alert('a'); + +}); + +```",2010/11/23,"['https://Stackoverflow.com/questions/4252818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516975/']","It looks like you either have multiple `.searchWord` elements nested within each other, or, you have multiple `.bBtnSearchBoard` elements.",It looks fine on [this test](http://jsfiddle.net/DjASs/). Maybe your problem is that `.bBtnSearchBoard` returns more than one element. +4252818,"I have in trouble to trigger a click event when enter key is pressed. +When I use below codes, the live('click') event is triggered 3 times (which means the alert message is shown 3 thmes) when I press an enter key. Thanks in advance!! - KS from Korea + +``` +$('.searchWord').live('keypress', function(e) { + if(e.keyCode == 13) { + $('.bBtnSearchBoard').trigger('click'); + } +}); + +$('.bBtnSearchBoard').live('click', function() { + alert('a'); + +}); + +```",2010/11/23,"['https://Stackoverflow.com/questions/4252818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516975/']","It looks like you either have multiple `.searchWord` elements nested within each other, or, you have multiple `.bBtnSearchBoard` elements.","``` +$('.searchWord').live('keypress', function(e) { + if(e.keyCode == 13) { + $('.bBtnSearchBoard').click(); + } +}); + +$('.bBtnSearchBoard').live('click', function() { + //do your stuff here + $(this).die(""click""); //The first time this method executes unbinds the click handler from matched elements + return false; //to prevent bubbling up of this event higher up the DOM +}); + +```" +41694421,"I'm calling my Java Servlet with an AJAX call, but I'm not able to read the input parameter from the request. I've tried two ways but with no luck: + +``` +var id; +$(""#scan"").click(function() { + id = 1; + $.ajax({ + type: ""POST"", + data: id, + url: ""http://10.1.42.249:8080/test-notifier-web/RestLayer"" + }); +}); + +``` + +And: + +``` +id = 1; +$.post('http://10.1.42.249:8080/test-notifier-web/RestLayer', { + reqValue: id +}, function(responseText) { + // $('#welcometext').text(responseText); + alert(""OK!!!""); +}); + +``` + +My servlet code is a simple log print of the request parameter, but the return value is always null: + +``` +String reqID = """"; +log.info(""Servlet called""); +reqID = request.getParameter(""reqValue""); +log.info(""reqID = "" + reqID); + +``` + +How can I get this working? + +The only way I've found to get the code working is manually add the parameter to servlet url, like `http://10.1.42.249:8080/test-notifier-web/RestLayer?reqValue=1`",2017/01/17,"['https://Stackoverflow.com/questions/41694421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3991150/']","i have check you code.this is my working code. + +``` + <%@ page language=""java"" contentType=""text/html; charset=ISO-8859-1"" + pageEncoding=""ISO-8859-1""%> + + + + +Insert title here + + + + + + + + + +``` + +//Servlet + +``` +@WebServlet(urlPatterns = {""/callAjax"",}) +public class Test extends HttpServlet { + private static final long serialVersionUID = 1L; + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + System.out.println(request.getParameter(""reqValue"")); + } + +} + +```","``` +var id; + +$(""#scan"").click(function() { + + id = 1; + + $.ajax({ + type: ""POST"", + data: { reqValue : id}, + url: ""http://10.1.42.249:8080/test-notifier-web/RestLayer"" + }); +}); + +``` + +There are different methods you need to override in servlet. Those are doPost(), doGet(), service() and etc. + +I suspect you are using doGet() method that's why when you add parameter to the URL your java code is working and in other two cases as you are using `type : ""POST""` java code is unable to read the data from Request Body( in post method the data will be added to Request Body). + +I suggest you to use `doPost()` or `service()` methods instead doGet()." +37357896,"I am using sublime to automatically word-wrap python code-lines that go beyond 79 Characters as the Pep-8 defines. Initially i was doing return to not go beyond the limit. + +The only downside with that is that anyone else not having the word-wrap active wouldn't have the limitation. So should i strive forward of actually word-wrapping or is the visual word-wrap ok? + +[![enter image description here](https://i.stack.imgur.com/Wz4ko.png)](https://i.stack.imgur.com/Wz4ko.png)",2016/05/21,"['https://Stackoverflow.com/questions/37357896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1767754/']","PEP8 wants you to perform an actual word wrap. The point of PEP8’s stylistic rules is that the file looks the same in every editor, so you cannot rely on editor visualizations to satisfy PEP8. + +This also makes you choose the point where to break deliberately. For example, Sublime will do a pretty basic job in wrapping that line; but you could do it in a more readable way, e.g.: + +``` +x = os.path.split(os.path.split(os.path.split( + os.path.split(os.path.split(path)[0])[0] + )[0])[0]) + +``` + +Of course that’s not necessarily pretty (I blame that mostly on this example code though), but it makes clear what belongs to what. + +That being said, a good strategy is to simply avoid having to wrap lines. For example, you are using `os.path.split` over and over; so you could change your import: + +``` +from os.path import split +x = split(split(split(split(split(path)[0])[0])[0])[0]) + +``` + +And of course, if you find yourself doing something over and over, maybe there’s a better way to do this, for example using Python 3.4’s `pathlib`: + +``` +import pathlib +p = pathlib.Path(path).parents[2] +print(p.parent.absolute(), p.name) + +```","In-file word wrapping would let your code conform to Pep-8 most consistently, even if other programmers are looking at your code using different coding environments. That seems to me to be the best solution to keeping to the standard, particularly if you are expecting that others will, at some point, be looking at your code. + +If you are working with a set group of people on a project, or even in a company, it may be possible to coordinate with the other programmers to find what solution you are all most satisfied with. + +For personal projects that you really aren't expecting anyone else to ever look at, I'm sure it's fine to use the visual word wrapping, but enforcing it yourself would certainly help to build on a good habit." +31768349,"I tried an SSE (Server-Sent-Events) using java on tomcat 8.0. Here are few things I noticed. + +I click a button that automatically makes a request to the servlet. Servlet's GET method gets executed which returns an event stream. Once the full stream is received, the page again automatically makes another request which receives the same data again!!! I don't have an infinite loop there!!! + +1. What is actually happening on the server? In normal scenarios, tomcat creates a thread to handle every request. What is happening now? +2. What is the correct way to ensure that the event stream is sent only once to the same connection/browser session? +3. What is the correct way to ensure that the event stream is closed and no resource overhead incurs on the server? +4. How to differentiate between GET and POST requests. Why did it choose GET? +5. Is it too early to use SSE on Tomcat? Any performance issues? + +Here is the code for the curious, + +``` +@WebServlet(""/TestServlet"") +public class TestServlet extends HttpServlet { + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + //content type must be set to text/event-stream + response.setContentType(""text/event-stream""); + //cache must be set to no-cache + response.setHeader(""Cache-Control"", ""no-cache""); + //encoding is set to UTF-8 + response.setCharacterEncoding(""UTF-8""); + + PrintWriter writer = response.getWriter(); + + for(int i=0; i<10; i++) { + System.out.println(i); + writer.write(""data: ""+ i +""\n\n""); + writer.flush(); + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + writer.close(); + } +} + +``` + +Javascript on the page (I don't have anything else on the page), + +``` + + + + +``` + +Tried this using CURL. And the response came just once. I'm using chrome, so this must be a issue with chorme?? + +**EDIT:** + +What I have learned and learning is now documented in my blog - [Server Sent Events](http://www.cs-repository.info/2016/08/server-sent-events.html)",2015/08/02,"['https://Stackoverflow.com/questions/31768349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548634/']","Change this line + +``` +writer.write(""data: ""+ i +""\n\n""); + +``` + +to + +``` +writer.write(""data: ""+ i +""\r\n""); + +``` + +BTW, your code will have a serious performance issue because it will hold a thread until all events are sent.Please use Asynchronous processing API instead. e.g. + +``` +protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + AsyncContext actx = req.startAsync(); + actx.setTimeout(30*1000); + //save actx and use it when we need sent data to the client. +} + +``` + +Then we can use AsyncContext later + +``` +//write some data to client when a certain event happens +actx.getResponse().getWriter().write(""data: "" + mydata + ""\r\n""); +actx.getResponse().getWriter().flush(); + +``` + +if all events sent we can close it + +``` +actx.complete(); + +``` + +**UPDATE 1:** + +We need close the event source at browser if we do not want browser reconnect the server again when server completes the response. + +``` +eventSource.close(); + +``` + +Another method maybe helps, viz. we set a quite large retry time but I have not tried it, e.g. + +``` +protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + AsyncContext actx = req.startAsync(); + actx.getResponse().getWriter().write(""retry: 36000000000\r\n""); // 10000 hours! + actx.getResponse().getWriter().flush(); + //save actx and use it when we need sent data to the client. +} + +``` + +**UPDATE 2:** + +I think Websocket maybe is better for your case. + +**UPDATE 3: (answer the questions)** + +> +> 1. What is actually happening on the server? In normal scenarios, tomcat creates a thread to handle every request. What is happening now? +> +> +> + +If use NIO connector which is default in Tomcat 8.0.X, within the whole processing cycle HTTP I/O about a request won't hold a thread. If use BIO a thread will be hold until the whole processing cycle completes. All threads are from a thread pool, tomcat won't create a thread for each request. + +> +> 2. What is the correct way to ensure that the event stream is sent only once to the same connection/browser session? +> +> +> + +Do `eventSource.close()` at browser side is the best choice. + +> +> 3. What is the correct way to ensure that the event stream is closed and no resource overhead incurs on the server? +> +> +> + +Do not forget to invoke AsyncContext.complete() at server side. + +> +> 4. How to differentiate between GET and POST requests. Why did it choose GET? +> +> +> + +The EventSource API in a browser only supports GET requests but at the server side there 's no such restriction. +SSE is mainly used to receive events data from server. If a event happens the browser can receive it in time and no need to create a new request to poll it. +If you need full-duplex communication try WebSocket instread of SSE. + +> +> 5. Is it too early to use SSE on Tomcat? Any performance issues? +> +> +> + +There should be no performance issues if we use NIO connector & Asynchronous processing API. I don't know whether Tomcat NIO connector is mature or not but something will never be known unless we try it.","I highly recommend first to read [Stream Updates with Server-Sent Events](http://www.html5rocks.com/en/tutorials/eventsource/basics/) to get a good general understanding of the technology. +Then follow [Server-Sent Events with Async Servlet By Example](https://weblogs.java.net/blog/swchan2/archive/2014/05/21/server-sent-events-async-servlet-example) to see how SSE can be used specifically with the Servlet technology." +31768349,"I tried an SSE (Server-Sent-Events) using java on tomcat 8.0. Here are few things I noticed. + +I click a button that automatically makes a request to the servlet. Servlet's GET method gets executed which returns an event stream. Once the full stream is received, the page again automatically makes another request which receives the same data again!!! I don't have an infinite loop there!!! + +1. What is actually happening on the server? In normal scenarios, tomcat creates a thread to handle every request. What is happening now? +2. What is the correct way to ensure that the event stream is sent only once to the same connection/browser session? +3. What is the correct way to ensure that the event stream is closed and no resource overhead incurs on the server? +4. How to differentiate between GET and POST requests. Why did it choose GET? +5. Is it too early to use SSE on Tomcat? Any performance issues? + +Here is the code for the curious, + +``` +@WebServlet(""/TestServlet"") +public class TestServlet extends HttpServlet { + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + //content type must be set to text/event-stream + response.setContentType(""text/event-stream""); + //cache must be set to no-cache + response.setHeader(""Cache-Control"", ""no-cache""); + //encoding is set to UTF-8 + response.setCharacterEncoding(""UTF-8""); + + PrintWriter writer = response.getWriter(); + + for(int i=0; i<10; i++) { + System.out.println(i); + writer.write(""data: ""+ i +""\n\n""); + writer.flush(); + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + writer.close(); + } +} + +``` + +Javascript on the page (I don't have anything else on the page), + +``` + + + + +``` + +Tried this using CURL. And the response came just once. I'm using chrome, so this must be a issue with chorme?? + +**EDIT:** + +What I have learned and learning is now documented in my blog - [Server Sent Events](http://www.cs-repository.info/2016/08/server-sent-events.html)",2015/08/02,"['https://Stackoverflow.com/questions/31768349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548634/']","Change this line + +``` +writer.write(""data: ""+ i +""\n\n""); + +``` + +to + +``` +writer.write(""data: ""+ i +""\r\n""); + +``` + +BTW, your code will have a serious performance issue because it will hold a thread until all events are sent.Please use Asynchronous processing API instead. e.g. + +``` +protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + AsyncContext actx = req.startAsync(); + actx.setTimeout(30*1000); + //save actx and use it when we need sent data to the client. +} + +``` + +Then we can use AsyncContext later + +``` +//write some data to client when a certain event happens +actx.getResponse().getWriter().write(""data: "" + mydata + ""\r\n""); +actx.getResponse().getWriter().flush(); + +``` + +if all events sent we can close it + +``` +actx.complete(); + +``` + +**UPDATE 1:** + +We need close the event source at browser if we do not want browser reconnect the server again when server completes the response. + +``` +eventSource.close(); + +``` + +Another method maybe helps, viz. we set a quite large retry time but I have not tried it, e.g. + +``` +protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + AsyncContext actx = req.startAsync(); + actx.getResponse().getWriter().write(""retry: 36000000000\r\n""); // 10000 hours! + actx.getResponse().getWriter().flush(); + //save actx and use it when we need sent data to the client. +} + +``` + +**UPDATE 2:** + +I think Websocket maybe is better for your case. + +**UPDATE 3: (answer the questions)** + +> +> 1. What is actually happening on the server? In normal scenarios, tomcat creates a thread to handle every request. What is happening now? +> +> +> + +If use NIO connector which is default in Tomcat 8.0.X, within the whole processing cycle HTTP I/O about a request won't hold a thread. If use BIO a thread will be hold until the whole processing cycle completes. All threads are from a thread pool, tomcat won't create a thread for each request. + +> +> 2. What is the correct way to ensure that the event stream is sent only once to the same connection/browser session? +> +> +> + +Do `eventSource.close()` at browser side is the best choice. + +> +> 3. What is the correct way to ensure that the event stream is closed and no resource overhead incurs on the server? +> +> +> + +Do not forget to invoke AsyncContext.complete() at server side. + +> +> 4. How to differentiate between GET and POST requests. Why did it choose GET? +> +> +> + +The EventSource API in a browser only supports GET requests but at the server side there 's no such restriction. +SSE is mainly used to receive events data from server. If a event happens the browser can receive it in time and no need to create a new request to poll it. +If you need full-duplex communication try WebSocket instread of SSE. + +> +> 5. Is it too early to use SSE on Tomcat? Any performance issues? +> +> +> + +There should be no performance issues if we use NIO connector & Asynchronous processing API. I don't know whether Tomcat NIO connector is mature or not but something will never be known unless we try it.","The browser attempts to reconnect to the source roughly 3 seconds after each connection is closed. You can change that timeout by including a line beginning with ""retry:"", followed by the number of milliseconds to wait before trying to reconnect." +31768349,"I tried an SSE (Server-Sent-Events) using java on tomcat 8.0. Here are few things I noticed. + +I click a button that automatically makes a request to the servlet. Servlet's GET method gets executed which returns an event stream. Once the full stream is received, the page again automatically makes another request which receives the same data again!!! I don't have an infinite loop there!!! + +1. What is actually happening on the server? In normal scenarios, tomcat creates a thread to handle every request. What is happening now? +2. What is the correct way to ensure that the event stream is sent only once to the same connection/browser session? +3. What is the correct way to ensure that the event stream is closed and no resource overhead incurs on the server? +4. How to differentiate between GET and POST requests. Why did it choose GET? +5. Is it too early to use SSE on Tomcat? Any performance issues? + +Here is the code for the curious, + +``` +@WebServlet(""/TestServlet"") +public class TestServlet extends HttpServlet { + + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + //content type must be set to text/event-stream + response.setContentType(""text/event-stream""); + //cache must be set to no-cache + response.setHeader(""Cache-Control"", ""no-cache""); + //encoding is set to UTF-8 + response.setCharacterEncoding(""UTF-8""); + + PrintWriter writer = response.getWriter(); + + for(int i=0; i<10; i++) { + System.out.println(i); + writer.write(""data: ""+ i +""\n\n""); + writer.flush(); + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + writer.close(); + } +} + +``` + +Javascript on the page (I don't have anything else on the page), + +``` + + + + +``` + +Tried this using CURL. And the response came just once. I'm using chrome, so this must be a issue with chorme?? + +**EDIT:** + +What I have learned and learning is now documented in my blog - [Server Sent Events](http://www.cs-repository.info/2016/08/server-sent-events.html)",2015/08/02,"['https://Stackoverflow.com/questions/31768349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548634/']","I highly recommend first to read [Stream Updates with Server-Sent Events](http://www.html5rocks.com/en/tutorials/eventsource/basics/) to get a good general understanding of the technology. +Then follow [Server-Sent Events with Async Servlet By Example](https://weblogs.java.net/blog/swchan2/archive/2014/05/21/server-sent-events-async-servlet-example) to see how SSE can be used specifically with the Servlet technology.","The browser attempts to reconnect to the source roughly 3 seconds after each connection is closed. You can change that timeout by including a line beginning with ""retry:"", followed by the number of milliseconds to wait before trying to reconnect." +36656845,"I don't understand why an empty array, or an array with only 1 ""numerical"" value can be used in certain calculations. + +``` +[] * [] === 0 //true + +[2] * [2] === 4 //true + +[""2""] * [""2""] === 4 //true + +``` + +However, it does not seem that is always the case with every operator. + +``` +[2] + [1] === 3 // false, actual result is ""21"" + +[2] - [1] === 1 // true + +``` + +I also checked these, and saw expected results: + +``` +[4] === ""4"" // false +[4] === 4 // false + +``` + +In most cases, I would expect `NaN` in any of these mathematical operations. What is it about JavaScript arrays that allows this? Is it because the array `toString` method is being used somehow internally?",2016/04/15,"['https://Stackoverflow.com/questions/36656845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2056157/']","The arrays are coerced into strings, such that `[] == """"`, `[1] == ""1""`, and `[1, 2] == ""1,2""`. + +When you do certain mathematical operations on strings, they are coerced into `Number` types. + +For example, when you do `[2] * [2]` it becomes `""2"" * ""2""` which becomes `2 * 2`. You can even mix types and do `[2] * 2` or `""2"" * [2]`. + +When you try to use `+`, it attempts to concatenate the strings instead of coercing the strings to numbers. That's why `""2"" + ""2""`, `""2"" + [2]`, and `[2] + [2]` each give you `""22""`.","The same ol'problem of having `+` as string concatenation operator. + +An array in Javascript is an Object. When you try to coerce objects into primitive values, there is an order to follow: + +1. `.toString()` +2. `.toNumber()` +3. `.toBoolean()` + +If you're using the `*` operator, coerce into string is not possible, so the interpreter goes to `toNumber()`. + +When you're using the `+` operator, the first attempt will be `toString()`. Since `+` is also the string concat operator, then the expression will be evaluated as an array. + +Yeah, [javascript](/questions/tagged/javascript ""show questions tagged 'javascript'"") can get ugly. + +Edit: +----- + +Some further details can be found [here](https://www.safaribooksonline.com/library/view/you-dont-know/9781491905159/ch04.html)." +36656845,"I don't understand why an empty array, or an array with only 1 ""numerical"" value can be used in certain calculations. + +``` +[] * [] === 0 //true + +[2] * [2] === 4 //true + +[""2""] * [""2""] === 4 //true + +``` + +However, it does not seem that is always the case with every operator. + +``` +[2] + [1] === 3 // false, actual result is ""21"" + +[2] - [1] === 1 // true + +``` + +I also checked these, and saw expected results: + +``` +[4] === ""4"" // false +[4] === 4 // false + +``` + +In most cases, I would expect `NaN` in any of these mathematical operations. What is it about JavaScript arrays that allows this? Is it because the array `toString` method is being used somehow internally?",2016/04/15,"['https://Stackoverflow.com/questions/36656845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2056157/']","The arrays are coerced into strings, such that `[] == """"`, `[1] == ""1""`, and `[1, 2] == ""1,2""`. + +When you do certain mathematical operations on strings, they are coerced into `Number` types. + +For example, when you do `[2] * [2]` it becomes `""2"" * ""2""` which becomes `2 * 2`. You can even mix types and do `[2] * 2` or `""2"" * [2]`. + +When you try to use `+`, it attempts to concatenate the strings instead of coercing the strings to numbers. That's why `""2"" + ""2""`, `""2"" + [2]`, and `[2] + [2]` each give you `""22""`.","In regards to `+`, [`+` is a coercive operator on `Strings`](http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.1), irrespective of it being the `lvalue` and `rvalue`, I'll quote the specification here: + +> +> If `Type(lprim`) is String or `Type(rprim`) is `String`, then Return the +> `String` that is the result of concatenating `ToString(lprim`) followed by +> `ToString(rprim`) +> +> +> + +[Multiplication however doesn't follow the same rules](http://www.ecma-international.org/ecma-262/5.1/#sec-11.5), it does however apply [`ToNumber`](http://www.ecma-international.org/ecma-262/5.1/#sec-9.3), which as you've noticed, casts a `[Number]` to -> `Number` (`+` does this as well, but it is a later step in the operator's definition) + +Your last statement is answered by two rules of the `SameValue` algorithm defined in the spec, namely, if two values are of a different type, return `false`, alternatively, if two objects refer to the ptr, return true. Thus + +``` +a = [1]; +b = [1]; +a === b; // false + +```" +36656845,"I don't understand why an empty array, or an array with only 1 ""numerical"" value can be used in certain calculations. + +``` +[] * [] === 0 //true + +[2] * [2] === 4 //true + +[""2""] * [""2""] === 4 //true + +``` + +However, it does not seem that is always the case with every operator. + +``` +[2] + [1] === 3 // false, actual result is ""21"" + +[2] - [1] === 1 // true + +``` + +I also checked these, and saw expected results: + +``` +[4] === ""4"" // false +[4] === 4 // false + +``` + +In most cases, I would expect `NaN` in any of these mathematical operations. What is it about JavaScript arrays that allows this? Is it because the array `toString` method is being used somehow internally?",2016/04/15,"['https://Stackoverflow.com/questions/36656845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2056157/']","The arrays are coerced into strings, such that `[] == """"`, `[1] == ""1""`, and `[1, 2] == ""1,2""`. + +When you do certain mathematical operations on strings, they are coerced into `Number` types. + +For example, when you do `[2] * [2]` it becomes `""2"" * ""2""` which becomes `2 * 2`. You can even mix types and do `[2] * 2` or `""2"" * [2]`. + +When you try to use `+`, it attempts to concatenate the strings instead of coercing the strings to numbers. That's why `""2"" + ""2""`, `""2"" + [2]`, and `[2] + [2]` each give you `""22""`.","When you do mathematical operations on the arrays JavaScript converts them to the **strings**. But **string** doesn't have multiply operator and then JavaScript converts them to the **numbers** because you try to multiply them: + +``` +[] * [] === 0 // [] -> '' -> 0, result is 0 * 0 + +[2] * [2] === 4 // [2] -> '2' -> 2, result is 4 * 4 + +[""2""] * [""2""] === 4 // [""2""] -> '2' -> 2, result is 4 * 4 + +``` + +**String** has a `+` operator: + +``` +[2] + [1] === 3 // '2' + '1', result is ""21"" + +``` + +but doesn't have a `-` operator, therefore JavaScript converts them to the **numbers** too: + +``` +[2] - [1] === 1 // true, because they are numbers + +``` + +`===` it's *strict equality*, means that the objects being compared must have the same type. + +``` +[4] === ""4"" // false, you are comparing array with a string +[4] === 4 // false, you are comparing array with a number + +```" +15029537,"I am creating a custom type calendar and I am trying to see if it is possible to store dates in an array without statically assigning each one. For example the 1st date in the array would be the day it was first created and it would save the next week lets say into the relevant indexes in the array. + +``` +NSMutableArray *thisWeek = [today, tomorrow, sunday(Feb 24), monday (Feb 25), etc]; + +``` + +What would be the best way to go about storing the future dates?",2013/02/22,"['https://Stackoverflow.com/questions/15029537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1220097/']","``` +NSMutableArray *days; +days = [[NSMutableArray alloc] init]; + +NSDate *todayDate = [NSDate Date]; +[days addObject:todayDate]; + +for (int i = 1; i <= 6; i++) +{ + NSDate *newDate = [[NSDate date] dateByAddingTimeInterval:60*60*24*i]; + + [days addObject:newDate]; + +} + +``` + +In this way, you can add days in array.",Take a look at `dateByAddingTimeInterval:` in the `NSDate` docs ([link](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html)). It lets you add a given amount of seconds to a date. +15029537,"I am creating a custom type calendar and I am trying to see if it is possible to store dates in an array without statically assigning each one. For example the 1st date in the array would be the day it was first created and it would save the next week lets say into the relevant indexes in the array. + +``` +NSMutableArray *thisWeek = [today, tomorrow, sunday(Feb 24), monday (Feb 25), etc]; + +``` + +What would be the best way to go about storing the future dates?",2013/02/22,"['https://Stackoverflow.com/questions/15029537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1220097/']","``` +NSMutableArray *days = [[NSMutableArray alloc] init]; +NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar]; +NSDateComponents *tempCop = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit + fromDate:[NSDate date]]; +NSDate *today = [cal dateFromComponents:tempCop]; + +for (int i = 0; i < 8; i++) +{ + NSDateComponents *comps = [[NSDateComponents alloc]init]; + [comps setDay:i]; + [days addObject:[cal dateByAddingComponents:comps toDate:today options:0]]; +} + +```",Take a look at `dateByAddingTimeInterval:` in the `NSDate` docs ([link](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html)). It lets you add a given amount of seconds to a date. +15029537,"I am creating a custom type calendar and I am trying to see if it is possible to store dates in an array without statically assigning each one. For example the 1st date in the array would be the day it was first created and it would save the next week lets say into the relevant indexes in the array. + +``` +NSMutableArray *thisWeek = [today, tomorrow, sunday(Feb 24), monday (Feb 25), etc]; + +``` + +What would be the best way to go about storing the future dates?",2013/02/22,"['https://Stackoverflow.com/questions/15029537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1220097/']","``` +NSMutableArray *days = [[NSMutableArray alloc] init]; +NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar]; +NSDateComponents *tempCop = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit + fromDate:[NSDate date]]; +NSDate *today = [cal dateFromComponents:tempCop]; + +for (int i = 0; i < 8; i++) +{ + NSDateComponents *comps = [[NSDateComponents alloc]init]; + [comps setDay:i]; + [days addObject:[cal dateByAddingComponents:comps toDate:today options:0]]; +} + +```","``` +NSMutableArray *days; +days = [[NSMutableArray alloc] init]; + +NSDate *todayDate = [NSDate Date]; +[days addObject:todayDate]; + +for (int i = 1; i <= 6; i++) +{ + NSDate *newDate = [[NSDate date] dateByAddingTimeInterval:60*60*24*i]; + + [days addObject:newDate]; + +} + +``` + +In this way, you can add days in array." +40147118,"I am building an application for which i am using nodejs express to do rest api services. +I hosted that application on windows server 2012 using iisnode module.Everything works perfect. +The issue is that when i am returning 404(unauthorized) message from node application the end point is recieving the 401 http status with the error page of iis. +Is there any other way to overcome this issue. + +here is my webconfig file + +``` + + + + + + + + + + + + + + + + +``` + +My code in nodejs app is the following + +``` + if(clienttoken!=servertoken) +{ + res.json(401, 'unauthorized'); + res.end(); +} + +``` + +[![enter image description here](https://i.stack.imgur.com/AdTI1.png)](https://i.stack.imgur.com/AdTI1.png) + +Thanks in advance",2016/10/20,"['https://Stackoverflow.com/questions/40147118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3079776/']","Using IIS, if you want to return the errors straight from your Node app to the requester without IIS intercepting them with default Error Pages, use the `` element with the `existingResponse` attribute set to `PassThrough` + +``` + + + + + + +```","IIS is obscuring the ""detail"" of the error (your json response) because by default errors are set to `DetailedLocalOnly`, meaning that the error detail will be shown for requests from the machine the website is running on, but show the generic IIS error page for that error code for any external requests. + +Setting the 401 error to `Detailed` instead should allow your json response through: + +``` + + + + + + + + + +``` + +See for details." +8081268,"I've different divboxes and some pictures below them. If I hover the divboxes, they expand from 200px to 400px and the picture below slide. + +So I've the function ""theRotation"" and i call two external function in it like this: + +``` +function theRotation(){ +opendivs(); //this expand the divbox to 400 px +rotatePicture(); //this rotate the picture +} + +``` + +now my problem is, that I want the pictures to slide if the divbox is about 300px NOT before!! (remember it expand from 200px to 400px) + +So i need a event listener who tell me when the divbox.width() == 300px +Is this possible? + +Kind Regards",2011/11/10,"['https://Stackoverflow.com/questions/8081268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/831022/']","I had some issues with this process as well. I don't exactly recall what resolved this error, but I followed [This Tutorial](http://net.tutsplus.com/tutorials/php/how-to-authenticate-users-with-twitter-oauth/) (albeit a bit out of date) and made sure I explicitly set the callback URL in the twitter panel for my app. Also, and I believe this one also caused the `int 0` return for me, make sure that if you are going with a hosting provider they allow `CURL` requests.","step 1: or go to your app setting + +step 2: Unchecked the (Enable Callback Locking (It is recommended to enable callback locking to ensure apps cannot overwrite the callback url)) This box.. + +save and exit and check.. + +ThankYou..!" +40625869,"we started to develope an application with swift for iOS. +when we started it latest version was developer target 9.3. +now there is developer target 10 available. Can I install application that created with developer target 9.3 on iOS 10 ?",2016/11/16,"['https://Stackoverflow.com/questions/40625869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4433550/']","In short - YES. You won't be able to do the opposite - install targeted as iOS 10 app to device, running with iOS 9.3 + +EDITED + +So, your purposes, I think, maintain as small version, as possible. If you maintain 9.3 version, for example, your app will be available for iPhone 4s, which is not updates to iOS 10. With this ver you will cover more users","**Deployment Target** is the **minimum required iOS version you application needs to run**. + +You can build an application with SDK 10 that runs under iOS 9. But then you have to take care to not use any function or method that is not available on iOS 9. + +Also Always check to see if you are using deprecated APIs; though still available, deprecated APIs are not guaranteed to be available in the future." +40625869,"we started to develope an application with swift for iOS. +when we started it latest version was developer target 9.3. +now there is developer target 10 available. Can I install application that created with developer target 9.3 on iOS 10 ?",2016/11/16,"['https://Stackoverflow.com/questions/40625869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4433550/']","Yes, You can install lower developer target on higher iOS version.","**Deployment Target** is the **minimum required iOS version you application needs to run**. + +You can build an application with SDK 10 that runs under iOS 9. But then you have to take care to not use any function or method that is not available on iOS 9. + +Also Always check to see if you are using deprecated APIs; though still available, deprecated APIs are not guaranteed to be available in the future." +3326203,"I'm having a little difficulty wrapping my head around the difference between these two terms, so could someone verify if this is correct? I've struggle to find an answers or reference in a book or online. + +Component sequence: + +If you have a set $X \subset \mathbb{R}^m$ and a sequence $x \in X^\infty$ such that + +$$x = (x\_1, x\_2, \dots ) \in X^\infty = (\mathbb{R}^m)^\infty$$ + +Each $x\_i$ is itself a vector of $m$-terms, + +e.g., $x\_1 = (x\_{1,1}, x\_{1,2}, ... x\_{1,m})$, or for another notation: $x\_1 = (x\_1(1), x\_2(1), ... x\_m(1))$ + +i.e., each term of the sequence is itself an m-tuple. Then, a component sequence is defined as the $k-th$ component of each term $x(n)$, and hence, there are $m$ of these component sequences, a sequence for each component. + +But what does that actually mean, practically? If I have a sequence: + +$$ S = (x\_1, x\_2, x\_3 , ...)$$ +where $x\_1 = (1,3,5,7,9)$, is one such component sequence of $S$ just $(1,3,5,7,9)$? + +As opposed to a subsequence which could be $(x\_1, x\_3, x\_5, ...) $ ?",2019/08/17,"['https://math.stackexchange.com/questions/3326203', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/466286/']","Component sequences are projections of your sequences on the one dimensional axes of your space. Each component sequence is an infinite sequence of picking the sequence of terms in one dimension of the original sequence . +For example if $$\{(1,4,5),(3,2,4),(5,3,6),...\}$$ is a sequence in $R^3$, then you have three component sequences namely $$\{1,3,5,....\}, \{4,2,3,....\},\{5,4,6,...\}$$","The answer to you example-question is no. A component-sequence takes only one component per term, always from the same position, and so for each term. + +So, if $x\_1 = (1,3,5,7,9)$ like you suggest, then there are exactly five component sequences of $x$, one of them starts with $1$ and takes the first coordinate of each term, another starts with $3$ and takes the second coordinate of each term, etc." +59465212,"I recently migrated from c# to .net core. In c# I use to get CPU usage with this: + +``` +PerformanceCounter cpuCounter; +PerformanceCounter ramCounter; + +cpuCounter = new PerformanceCounter(""Processor"", ""% Processor Time"", ""_Total""); + +public string getCurrentCpuUsage(){ + return cpuCounter.NextValue()+""%""; +} + +``` + +but in .net core `PerformanceCounter` is not available what is the solution ? please give me an advice.",2019/12/24,"['https://Stackoverflow.com/questions/59465212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11589744/']","Performance counters are not in Linux thus not in NET Core. Alternative way: + +``` +private async Task GetCpuUsageForProcess() +{ + var startTime = DateTime.UtcNow; + var startCpuUsage = Process.GetProcesses().Sum(a => a.TotalProcessorTime.TotalMilliseconds); + await Task.Delay(500); + + var endTime = DateTime.UtcNow; + var endCpuUsage = Process.GetProcesses().Sum(a => a.TotalProcessorTime.TotalMilliseconds); + var cpuUsedMs = endCpuUsage - startCpuUsage; + var totalMsPassed = (endTime - startTime).TotalMilliseconds; + var cpuUsageTotal = cpuUsedMs / (Environment.ProcessorCount * totalMsPassed); + return cpuUsageTotal * 100; +} + +```","On Mac, I went the same route as [you already have to go to get memory usage](https://apple.stackexchange.com/questions/317483/how-to-calculate-used-memory-on-mac-os-by-command-line): shell out to a command-line utility, such as `top`, and parse the output. + +Here's my code: + +``` + + private static string[] GetOsXTopOutput() + { + var info = new ProcessStartInfo(""top""); + info.Arguments = ""-l 1 -n 0""; + info.RedirectStandardOutput = true; + + string output; + using (var process = Process.Start(info)) + { + output = process.StandardOutput.ReadToEnd(); + } + + return output.Split('\n'); + } + + public static double GetOverallCpuUsagePercentage() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + var lines = GetOsXTopOutput(); + + // Example: ""CPU usage: 8.69% user, 21.73% sys, 69.56% idle"" + var pattern = @""CPU usage: \d+\.\d+% user, \d+\.\d+% sys, (\d+\.\d+)% idle""; + Regex r = new Regex(pattern, RegexOptions.IgnoreCase); + foreach (var line in lines) + { + Match m = r.Match(line); + if (m.Success) + { + var idle = double.Parse(m.Groups[1].Value); + var used = 100 - idle; + return used; + } + } + + // Or throw an exception + return -1.0; + } + else + { + // E.g., Melih Altıntaş's solution: https://stackoverflow.com/a/59465268/132042 + ... + } + } + +```" +26469017,"I'm recreating the classic game 'Snake'. My idea is to firstly make a grid of 50 x 50 cells where each cell is a label of 10 x 10 pixels. + +However, I can't get this to work. I'm using GridLayout but somehow this doesn't really work, as I apparently can't set the site of each grid. + +I watched a video on Youtube where a guy made a tic tac toe game in which each the size of each grid automatically adapted to the size of the added images. What should I do if I use labels instead of images? + +Basically, what should I do to make each cell 10 by 10 pixels big, and put them in a grid of 50x50 cells? + +``` +import java.awt.*; +import javax.swing.*; + +public class MainSnake { + JFrame frame; + JLabel[][] cells; + +MainSnake() { + //Frame initializion + frame = new JFrame(""Snake""); + frame.getContentPane().setBackground(Color.BLACK); + frame.setSize(500, 500); + frame.setVisible(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setResizable(false); + frame.setLayout(new GridLayout(50, 50)); + + createCells(); + +} //End MainSnake + +public static void main(String[]a) { + new MainSnake(); +} //End main + +public void createCells(){ + int a = 0; + int i; + cells = new JLabel[50][50]; + for (i = 0; i < 50; i++){ + if(i < 50){ + cells[i][a] = new JLabel(""""); + cells[i][a].setOpaque(true); + cells[i][a].setBackground(Color.white); + cells[i][a].setBorder(BorderFactory.createLineBorder(Color.BLUE, 1)); + cells[i][a].setPreferredSize(new Dimension(10,10)); + frame.add(cells[i][a]); + } if(i==49){ + i = 0; + aa++; + } + } //End for +} + +} //End Class + +``` + +This is what I get (I only added the borders to ble able to see how each cell looks like): + +![enter image description here](https://i.stack.imgur.com/AKFNY.jpg)",2014/10/20,"['https://Stackoverflow.com/questions/26469017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4017593/']","I found an solution my self, and sharing it here for some one else to use. The following codes should be placed inside the Wordpress loop. + +``` + + + + + + ID); ?> + ID); ?> + ID); ?> + ID); ?> + +

+ + "" alt=""""/> + + + +
+ + + + +```","I understand, you want to set connection two different post types. You can this with custom fields. Create a selectbox and there options is post of your other custom post type. +For be easy you can use Rilwis's meta box plugin (). + +Your option value must post id. If you want get selected post, can use this: + +``` +$getIdWithField = get_post_meta($post->ID, 'custom_personel_field', true); +$post = get_post($getIdWithField); + +```" +59972802,"My aim was to use ajax to retrieve some data from my controller and append this to a table element in my view. However the javascript code only works until ""$.ajax("" at which point it just stops. I placed some break points after the above mentioned point but the code never ""broke"" at those points. + +This is the javascript code + +``` +$(document).ready(function () +{ + $(""#DivisionId"").change(function () { + var OptionId = $('#DivisionId').val(); + var position = 0; + $.ajax( + { + type: 'POST', + url: '@URL.Action(""Division"")', + dataType: 'json', + data: { DivisionId: OptionId }, + success: function (data) { + var LogStandings = ''; + $.each(data, function (i, log) { + position++; + var Logs = ""
"" + + """" + + """" + + """" + + """" + + """" + + """" + + """" + + """" + + """" + + """" + + """"; + $('#TheLog').append(Logs); + }); + + }, + error: function (ex) { + var r = jQuery.parseJSON(response.responseText); + alert(""Message: "" + r.Message); + alert(""StackTrace: "" + r.StackTrace); + alert(""ExceptionType: "" + r.ExceptionType); + } + }); + return false; + + }); // end of Division on change function + +})//End of document.ready function + +``` + +This is the code in my controller + +``` + public JsonResult Division(int DivisionId) + { + int UnderId = db.Under.FirstOrDefault().UnderID; + MainDivisionId = id; + + List Fixtures = db.Fixtures.Where(f => f.TeamModel.DivisionId == id && f.TeamModel.UnderId == UnderId).ToList(); + List Results = db.Results.Where(r => r.Fixtures.TeamModel.DivisionId == id && r.Fixtures.TeamModel.UnderId == UnderId).ToList(); + List Logs = db.Logs.Where(l => l.Team.DivisionId == id && l.Team.UnderId == UnderId).ToList(); + + IndexViewModel IndexPage = new IndexViewModel(Fixtures, Results, Logs); + + return Json(IndexPage , JsonRequestBehavior.AllowGet); + } + +``` + +I searched a little on the internet and one source suggested that I place my jquery CDN at the top of my view within the head tag, this did not solve my problem though. Besides that I have not been able to find any other solutions after an hour of searching.",2020/01/29,"['https://Stackoverflow.com/questions/59972802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12765810/']","You have 2 issues that I can see. + +First, you're making a `POST` request to a controller action that does not have the `[HttpPost]` annotation. It seems to me that you're getting/selecting data and a `GET` request would be more appropriate so I've used that in the example below. + +Second, you cannot use `@URL.Action(""Division"")` in a javascript string (or in javascript in general. If you really needed to then you could store some data in a hidden div and get the value with javascript/jquery) like you're attempting to do. On the script itself, this will render as you're making a request directly to `localhost:12345/@URL.Action(""Division"")` which is not a valid path. See the example below: + +Script: + +``` +$(document).ready(function () { + $(""#testButton"").on(""click"", function () { + var OptionId = 1; + + $.ajax( + { + type: 'GET', + //this url assumes your controller action is in HomeController.cs + url: '/Home/Division/' + OptionId, + dataType: 'json', + data: { DivisionId: OptionId }, + success: function (data) { + alert(""success""); + + }, + error: function (ex) { + var r = jQuery.parseJSON(response.responseText); + alert(""Message: "" + r.Message); + alert(""StackTrace: "" + r.StackTrace); + alert(""ExceptionType: "" + r.ExceptionType); + } + }); + }); +}); + +``` + +HomeController.cs action: + +``` +public JsonResult Division(int DivisionId) +{ + return Json(1, JsonRequestBehavior.AllowGet); +} + +``` + +and in my view for testing: + +`` + +The above test works as expected (receives the `DivisionID` param, returns data from the controller action and alerts success to the client). With the changed outlined above, breakpoints in your controller action will be hit as you're specifying a valid path and making the appropriate request type. Hope this helps.",I also had same problem like that. I did that in a `script` tag placed inside `head` tag. But I had to place that inside `body` tag. Then it worked fine. Try to use. It might help. +25352105,"The following code doesn't loop: + +``` +-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView +{ + NSLog(@""Inside method, before for loop""); + + NSLog(@""dayBarArray.count = %lu"", (unsigned long)dayBarArray.count); + + for (int i = 0; i < dayBarArray.count; i++) //*** I've tried it this way + +// for (DayChartBar *bar in dayBarArray) //*** I've tried it this way + { + NSLog(@""Inside for loop""); + + DayChartBar *bar = [dayBarArray objectAtIndex:i]; + + UIView *thisLabel = [self.scroller viewWithTag:(bar.tag + 100)]; + + CGRect visibleRect; + visibleRect.origin = self.scroller.frame.origin; + visibleRect.size = self.scroller.bounds.size; + + NSLog(@""bar.frame = %@"",NSStringFromCGRect(bar.frame)); + NSLog(@""visibleRect.frame = %@"",NSStringFromCGRect(visibleRect)); + + if (CGRectIntersectsRect(visibleRect,bar.frame)) + { + NSLog(@""Inside if statement""); + + CGRect intersection = CGRectIntersection(visibleRect,bar.frame); + NSLog(@""bar.Frame is %@"",NSStringFromCGRect(bar.frame)); + + thisLabel.center = CGPointMake((thisLabel.center.x), CGRectGetMidY(intersection)); + } + + else + { + thisLabel.center = thisLabel.center; + NSLog(@""Inside else statement""); + } + } + NSLog(@""Still inside method, after for loop""); + +} + +``` + +Here are the results of the strategically placed `NSLog` statements: + +``` +2014-08-17 10:07:37.221 WMDGx[54442:90b] Inside method, before for loop +2014-08-17 10:07:37.222 WMDGx[54442:90b] dayBarArray.count = 0 +2014-08-17 10:07:37.223 WMDGx[54442:90b] Still inside method, after for loop + +``` + +As you can see, I've tried both a traditional `for loop` and fast enumeration. Neither will execute. As the `NSLogs` indicate, I enter the method, but skip the loop, regardless of the approach I've taken. + +I'm pretty sure I've written good code since I've successfully used very similar syntax (both types) in many other places around this same app. And yes, I've looked at dozens of similar questions on SO, as well as consulting basic texts on Objective C `for` loops, but without resolution. + +As always, I'm open to the possibility that I've made a stupid mistake, but, if so, it eludes me. The code inside the `for` loop (I'm trying to relocate a `UILabel` in response to the scrolling of an associated `UIView`) is probably irrelevant, but I included it just in case. + +All help and observations appreciated! + +**Edit:** + +As kindly pointed out below, the answer to this question is that the relevant dayBarArray is empty. I just checked the code that adds the objects, and am perplexed. I certainly should have seen the obvious answer in my NSLogs, and have no excuse except that I had checked the add code before and the bars appeared to be added. I'll report back when I've straightened out whatever is wrong there. + +**Second edit:** + +OK, it was a dumbass mistake on my part--I hadn't initialized the array. Just the same, had I not posted the question, and since I believed I had checked the contents of the array (actually, I was checking to see if tags had been applied to the UIViews), I don't know how long it would have taken me to realize what the logs were telling me. Thanks to everyone who replied!",2014/08/17,"['https://Stackoverflow.com/questions/25352105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2671035/']","`dayBarArray.count` is zero, and the condition in the loop is `i < dayBarArray.count`. Before entering the loop body, it tests `0 < 0`, which is false, so it never enters the body.","dayBarArray.count should return a number greater than 0, to be able for the loop to execute at least once. In you case, because (dayBarArray.count == 0), the condition-expression for the for loop: + +``` +i < dayBarArray.count + +``` + +is false (because i == 0), + +and the the execution of the program will not go inside the loop." +25352105,"The following code doesn't loop: + +``` +-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView +{ + NSLog(@""Inside method, before for loop""); + + NSLog(@""dayBarArray.count = %lu"", (unsigned long)dayBarArray.count); + + for (int i = 0; i < dayBarArray.count; i++) //*** I've tried it this way + +// for (DayChartBar *bar in dayBarArray) //*** I've tried it this way + { + NSLog(@""Inside for loop""); + + DayChartBar *bar = [dayBarArray objectAtIndex:i]; + + UIView *thisLabel = [self.scroller viewWithTag:(bar.tag + 100)]; + + CGRect visibleRect; + visibleRect.origin = self.scroller.frame.origin; + visibleRect.size = self.scroller.bounds.size; + + NSLog(@""bar.frame = %@"",NSStringFromCGRect(bar.frame)); + NSLog(@""visibleRect.frame = %@"",NSStringFromCGRect(visibleRect)); + + if (CGRectIntersectsRect(visibleRect,bar.frame)) + { + NSLog(@""Inside if statement""); + + CGRect intersection = CGRectIntersection(visibleRect,bar.frame); + NSLog(@""bar.Frame is %@"",NSStringFromCGRect(bar.frame)); + + thisLabel.center = CGPointMake((thisLabel.center.x), CGRectGetMidY(intersection)); + } + + else + { + thisLabel.center = thisLabel.center; + NSLog(@""Inside else statement""); + } + } + NSLog(@""Still inside method, after for loop""); + +} + +``` + +Here are the results of the strategically placed `NSLog` statements: + +``` +2014-08-17 10:07:37.221 WMDGx[54442:90b] Inside method, before for loop +2014-08-17 10:07:37.222 WMDGx[54442:90b] dayBarArray.count = 0 +2014-08-17 10:07:37.223 WMDGx[54442:90b] Still inside method, after for loop + +``` + +As you can see, I've tried both a traditional `for loop` and fast enumeration. Neither will execute. As the `NSLogs` indicate, I enter the method, but skip the loop, regardless of the approach I've taken. + +I'm pretty sure I've written good code since I've successfully used very similar syntax (both types) in many other places around this same app. And yes, I've looked at dozens of similar questions on SO, as well as consulting basic texts on Objective C `for` loops, but without resolution. + +As always, I'm open to the possibility that I've made a stupid mistake, but, if so, it eludes me. The code inside the `for` loop (I'm trying to relocate a `UILabel` in response to the scrolling of an associated `UIView`) is probably irrelevant, but I included it just in case. + +All help and observations appreciated! + +**Edit:** + +As kindly pointed out below, the answer to this question is that the relevant dayBarArray is empty. I just checked the code that adds the objects, and am perplexed. I certainly should have seen the obvious answer in my NSLogs, and have no excuse except that I had checked the add code before and the bars appeared to be added. I'll report back when I've straightened out whatever is wrong there. + +**Second edit:** + +OK, it was a dumbass mistake on my part--I hadn't initialized the array. Just the same, had I not posted the question, and since I believed I had checked the contents of the array (actually, I was checking to see if tags had been applied to the UIViews), I don't know how long it would have taken me to realize what the logs were telling me. Thanks to everyone who replied!",2014/08/17,"['https://Stackoverflow.com/questions/25352105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2671035/']","`dayBarArray.count` is zero, and the condition in the loop is `i < dayBarArray.count`. Before entering the loop body, it tests `0 < 0`, which is false, so it never enters the body.","Your for loop will only execute when dayBarArray.count is greater than i and your log is telling you that dayBarArray.count equals 0 when i also equals 0. + +Your code is working correctly. Check where you are adding items to dayBarArray." +18849257,"I need to pass a model value item.ID to one of my javascript function how can I do that ? + +I tried`function(""@item.ID"")` but its not working",2013/09/17,"['https://Stackoverflow.com/questions/18849257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1858684/']","It generally works this way, you just have to omit the `""""` otherwise it gets interpreted as string. So you can write something like that in your JS: + +``` +var myinteger = @item.ID; + +``` + +which renders as + +``` +var myinteger = 123; //for example + +``` + +Edit: This makes sense when you id is an integer, of course, for strings you need to encapsulate it in `''` or `""""`. And don't get annoyed by any syntax errors reported by intellisense, it seems to have a problem with that but it works out just nicely.","Try this...mind single quotes on parameter value while calling js function + +``` +function MyJsFunction(modelvalue) +{ + alert(""your model value: "" + modelvalue); +} + + +OR + + +```" +18849257,"I need to pass a model value item.ID to one of my javascript function how can I do that ? + +I tried`function(""@item.ID"")` but its not working",2013/09/17,"['https://Stackoverflow.com/questions/18849257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1858684/']","It generally works this way, you just have to omit the `""""` otherwise it gets interpreted as string. So you can write something like that in your JS: + +``` +var myinteger = @item.ID; + +``` + +which renders as + +``` +var myinteger = 123; //for example + +``` + +Edit: This makes sense when you id is an integer, of course, for strings you need to encapsulate it in `''` or `""""`. And don't get annoyed by any syntax errors reported by intellisense, it seems to have a problem with that but it works out just nicely.","The best solution is pass your textbox ID to javascrpit function and then in function retrieve the value form the ID, + +``` + @Html.TextBoxFor(model => model.DatemailedStart, new {id = ""MailStartDate"", placeholder = ""MM/DD/YYYY"", maxlength = ""40"", @class = ""TextboxDates"", @onblur = ""isValidDate('MailStartDate');"" }) + + function isValidDate(id) { + var dateString = $('#'+id+'').val(); + } + +```" +18849257,"I need to pass a model value item.ID to one of my javascript function how can I do that ? + +I tried`function(""@item.ID"")` but its not working",2013/09/17,"['https://Stackoverflow.com/questions/18849257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1858684/']","You can pass the model data into the java script file in these ways +(1). Just set the value in hidden field and access the value of hidden field in java script. +(2). And pass the value using function parameter. +(3). + +``` + var LoginResourceKeyCollection = { + UserName_Required: '<%= Model.UserName%>', + Password_Required: '<%= Model.Password%>' + + } + + +```","Try this...mind single quotes on parameter value while calling js function + +``` +function MyJsFunction(modelvalue) +{ + alert(""your model value: "" + modelvalue); +} + + +OR + + +```" +18849257,"I need to pass a model value item.ID to one of my javascript function how can I do that ? + +I tried`function(""@item.ID"")` but its not working",2013/09/17,"['https://Stackoverflow.com/questions/18849257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1858684/']","You can pass the model data into the java script file in these ways +(1). Just set the value in hidden field and access the value of hidden field in java script. +(2). And pass the value using function parameter. +(3). + +``` + var LoginResourceKeyCollection = { + UserName_Required: '<%= Model.UserName%>', + Password_Required: '<%= Model.Password%>' + + } + + +```","The best solution is pass your textbox ID to javascrpit function and then in function retrieve the value form the ID, + +``` + @Html.TextBoxFor(model => model.DatemailedStart, new {id = ""MailStartDate"", placeholder = ""MM/DD/YYYY"", maxlength = ""40"", @class = ""TextboxDates"", @onblur = ""isValidDate('MailStartDate');"" }) + + function isValidDate(id) { + var dateString = $('#'+id+'').val(); + } + +```" +18849257,"I need to pass a model value item.ID to one of my javascript function how can I do that ? + +I tried`function(""@item.ID"")` but its not working",2013/09/17,"['https://Stackoverflow.com/questions/18849257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1858684/']","Try this...mind single quotes on parameter value while calling js function + +``` +function MyJsFunction(modelvalue) +{ + alert(""your model value: "" + modelvalue); +} + + +OR + + +```","The best solution is pass your textbox ID to javascrpit function and then in function retrieve the value form the ID, + +``` + @Html.TextBoxFor(model => model.DatemailedStart, new {id = ""MailStartDate"", placeholder = ""MM/DD/YYYY"", maxlength = ""40"", @class = ""TextboxDates"", @onblur = ""isValidDate('MailStartDate');"" }) + + function isValidDate(id) { + var dateString = $('#'+id+'').val(); + } + +```" +33772472,"After someone has logged off (*Start button→Logoff*) for the night, at a certain time in the morning I want to have the Task Scheduler automatically log into the Windows 7 user account (the opposite of *Start button→Logoff*) that is password protected. The machine is 64 bit. I am doing this so systems (vbs, vba, etc.) can prep files prior to the user showing up to work. + +I was pretty sure this was possible, but I can't find it anywhere online, so I am wondering if it really is possible. + +I have to this in a VBScript. + +For security reasons I need to log him off at night, but I figured that part out (vbs from SO): + +``` +Set = wshell = Wscript.CreateObject(Wscript.Shell"") +wschell.exec(""shutdown.exe -L -F"") 'logoff and force shutdown programs + +``` + +Edit1: +Using an answer from Sujith, I attempted to set this up. First I must point out that this is NOT a remote computer or connection. I'm trying to get the local computer to log back in to the user account. + +I created logon.vbs with this vbs code: + +``` +Set = wshell = Wscript.CreateObject(Wscript.Shell"") +wschell.exec(""shutdown.exe -L -F"") 'logoff and force shutdown programs + +WScript.Sleep(5000) + +computer = ""computername"" +username = ""OTHERDOMAIN\user"" +password = ""password"" + +Set locator = CreateObject(""WbemScripting.SWbemLocator"") +Set wmi = locator.ConnectServer(computer, ""root\default"", username, password) +wmi.Security_.ImpersonationLevel = 3 + +``` + +In other words, I am logging off and right back on (avoiding the Task Scheduler so things are simplified). I also tried a lot of variations on this trying to get it to work. It logs me off just fine, but nothing happens after that. I have to login manually. + +I also tried the Task Scheduler setting mentioned in Sujith's answer, but it never turned on that I could tell. + +Edit2: Or please tell me what you need to provide an answer?",2015/11/18,"['https://Stackoverflow.com/questions/33772472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3524158/']","Please minus the half the stroke width from x position. +you will get the correct path. +eg. if stroke width is 20 mean minus the 10 from second MoveTo. + +**calculation** 254-(storkeWidth/2) = 244. if strokeWidth is 20. + +``` + + + + +``` + +[Fiddle](http://jsfiddle.net/3t8rspd1/3/)","[stroke-linejoin](http://www.w3.org/TR/SVG/painting.html#StrokeLinejoinProperty ""Take this"") + +``` + + + + +```" +50589825,"I am currently looking at IdentityServer4 as an option for our web services. However, due to corporate compiler level policy, I am only able to use VisualStudio 15.0 which does not support .Net Core 2 (and ASP.NET core 2 therefore). So I am stuck with ASP.Net Core 1.x for the moment. Changing the compiler version is out of the question for the time being. + +IdentityServer4 does have a version based on ASP.NEt Core 1.x but doesn't seem to be maintained anymore. + +**My question is:** Will security vulnerabilities be fixed in Identityserver4 (ASP.NET Core 1.x)? +The Github repository seemed to be still active 2 months ago. So I am wondering what kind of maintenance will be provided by the developers.",2018/05/29,"['https://Stackoverflow.com/questions/50589825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1704574/']",Security vulnerabilities would be fixed on the 1.x branch - but no more feature work,"Here is Brock Allen's answer : + +> +> [...] if there are any security vulnerabilities reported we will fix them. But we won't be adding new features to the ASP.NET Core 1.x branch, as Microsoft themselves have moved on to ASP.NET Core 2.x and (in their eyes) ASP.NET Core 1.x is essentially deprecated. +> +> +>" +3015046,"This question comes from a Chinese high school olympiad training program. It seems remarkably more difficult (and indeed, interesting!) than all other problems arising in the same program, especially since an elementary (high-school level) solution is probably available. + +> +> Show that there exists integers $a,b,c,d,e>2018$ so that the equation $$a^2+b^2+c^2+d^2+e^2+65=abcde$$ is satisfied. +> +> +> + +For what it's worth, here's what I have tried. Rewriting the equation as a quadratic polynomial in $a$, +$$a^2-(bcde)a+b^2+c^2+d^2+e^2+65=0.$$ +For there to be integer solutions, the discriminant must be a perfect square. Hence +$$ b^2c^2d^2e^2-4b^2-4c^2-4d^2-4e^2-4\cdot5\cdot13=n^2.$$ +I don't however see how I can solve this equation, especially due to the large number of unknowns. Any ideas? + +--- + +**Edit:** Ivan Neretin presents an excellent answer by Vieta Jumping, which I'm sure will yield results. However, the training program I mentioned has not discussed such advanced tactics as Vieta Jumping yet, and only covered $\gcd$, $\operatorname{lcm}$, factorisation of polynomials, discriminants, modular arithmetic, divisibility and quadratic residues. Hence despite Ivan's excellent solution, I would still be extremely appreciative of a more elementary solution.",2018/11/26,"['https://math.stackexchange.com/questions/3015046', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/496634/']","You are supposed to bruteforce or guess $(a,b,c,d,e)=(1,2,3,4,5)$ or any other small solution, and then go up by [Vieta jumping](https://en.wikipedia.org/wiki/Vieta_jumping). That is, once you have a solution, you rewrite it as a quadratic polynomial in $a$ (just like you did), and since one root is integer, so is the other. Then you do the same to $b,\;c...$ and repeat until the roots are big enough.","Here is the output of the [Maxima](http://maxima.sourceforge.net/) commands I used to calculate a solution according to [Ivan Neretin's answer](https://math.stackexchange.com/a/3015056/11206). + +``` +(%i2) ev(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x = 1,b = 2,c = 3,d = 4,e = 5) + +(%o2) 0 + +(%i3) ev(solve(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x),b = 2,c = 3,d = 4,e = 5) + +(%o3) [x = 1, x = 119] + +(%i4) ev(solve(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x),b = 119,c = 3,d = 4,e = 5) + +(%o4) [x = 7138, x = 2] + +(%i5) ev(solve(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x),b = 119,c = 7138,d = 4,e + + = 5) + +(%o5) [x = 3, x = 16988437] + +(%i6) ev(solve(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x),b = 119,c = 7138, + + d = 16988437,e = 5) + +(%o6) [x = 72151760667066, x = 4] + +(%i7) ev(solve(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x),b = 119,c = 7138, + + d = 16988437,e = 72151760667066) + +(%o7) [x = 1041175313471572184867943319, x = 5] + +(%i8) ev(solve(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65,x), + + b = 1041175313471572184867943319,c = 7138,d = 16988437, + + e = 72151760667066) + +(%o8) [x = 9109630532627114315851511163018235051842553960810405, x = 119] + +(%i9) ev(x^2-b*c*d*e*x+b^2+c^2+d^2+e^2+65, + + x = 9109630532627114315851511163018235051842553960810405, + + b = 1041175313471572184867943319,c = 7138,d = 16988437, + + e = 72151760667066) + +(%o9) 0 + +```" +3015046,"This question comes from a Chinese high school olympiad training program. It seems remarkably more difficult (and indeed, interesting!) than all other problems arising in the same program, especially since an elementary (high-school level) solution is probably available. + +> +> Show that there exists integers $a,b,c,d,e>2018$ so that the equation $$a^2+b^2+c^2+d^2+e^2+65=abcde$$ is satisfied. +> +> +> + +For what it's worth, here's what I have tried. Rewriting the equation as a quadratic polynomial in $a$, +$$a^2-(bcde)a+b^2+c^2+d^2+e^2+65=0.$$ +For there to be integer solutions, the discriminant must be a perfect square. Hence +$$ b^2c^2d^2e^2-4b^2-4c^2-4d^2-4e^2-4\cdot5\cdot13=n^2.$$ +I don't however see how I can solve this equation, especially due to the large number of unknowns. Any ideas? + +--- + +**Edit:** Ivan Neretin presents an excellent answer by Vieta Jumping, which I'm sure will yield results. However, the training program I mentioned has not discussed such advanced tactics as Vieta Jumping yet, and only covered $\gcd$, $\operatorname{lcm}$, factorisation of polynomials, discriminants, modular arithmetic, divisibility and quadratic residues. Hence despite Ivan's excellent solution, I would still be extremely appreciative of a more elementary solution.",2018/11/26,"['https://math.stackexchange.com/questions/3015046', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/496634/']","You are supposed to bruteforce or guess $(a,b,c,d,e)=(1,2,3,4,5)$ or any other small solution, and then go up by [Vieta jumping](https://en.wikipedia.org/wiki/Vieta_jumping). That is, once you have a solution, you rewrite it as a quadratic polynomial in $a$ (just like you did), and since one root is integer, so is the other. Then you do the same to $b,\;c...$ and repeat until the roots are big enough.","*This expands upon @Ivan Neretin 's answer* + +This is what is meant by Vieta jumping, when it comes to this problem--we can use Vieta jumping to prove the following claim: + +> +> Proposition 1: For any $A \in \mathbb{Z}^+$ there is a solution $(a,b,c,d,e)$; $a,b,c,d,e \in \mathbb{Z}^+$ to the equation $a^2+b^2+c^2+d^2+e^2+65 = abcde$ such that $A \leq \min\{a,b,c,d,e\}$. +> +> +> + +*Proof:* We first claim the following: + +> +> Claim 1: Let us suppose that there is a solution $a^2+b^2+c^2+d^2+e^2+65=120$; $a,b,c,d,e \in \mathbb{Z}^+$, and let us assume WLOG that $a= \min\{a,b,c,d,e\}$. Then +> there is a solution $(a',b',c',d',e')$; $a',b',c',d',e' \in \mathbb{Z}^+$ s.t. $a'>a$ and $b'=b,c'=c,d'=d,e'=e$. +> +> +> + +[*Proof of Claim 1:* Indeed, iff there exists an integer $a'> a$ is that satisfies the following: + +$a'^2 + (b^2+c^2+d^2+e^2)+65 > a'(bcde)$. + +Then Claim 1 will follow. However, the above is a quadratic equation in $a'$ of the form $a'^2 - xa' + z$; both $x$ and $z$ positive integers, that has at least one integer solution, namely $a$, and so the other solution is an integer; as $z$ is at least $b^2+c^2+d^2+e^2+65$ $> 4a^2$ and $aa'=z$ with $a$ positive it follows that $a'$ must be strictly greater than $4a$. So indeed Claim 1 does follow. $\surd$ ] + +We note that Proposition 1 follows immediately from Claim 1, and the existence of at least one solution $(a\_0,b\_0,c\_0,d\_0,e\_0); a\_0,b\_0,c\_0,d\_0,e\_0 \in \mathbb{Z}^+$ +such that the equation $a\_0^2+b\_0^2+c\_0^2+d\_0^2+e\_0^2+65 = a\_0b\_0c\_0d\_0e\_0$ holds; +namely $(a\_0,b\_0,c\_0,d\_0,e\_0) =(1,2,3,4,5)$. $\surd$" +7610254,"My trying to make an Ajax call to a PHP function that pulls out data from my database. I've run into a problem though. + +My query looks like this + +``` +$query = ""SELECT * FROM mytable WHERE field LIKE '%$string%'"" + +``` + +I then check on the number of rows returned by the query, but when i type in æ ø å then i my query returns 0 rows, although I know there are entries in the database that have æ ø å.. why is this",2011/09/30,"['https://Stackoverflow.com/questions/7610254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/626535/']","Set the connection to use UTF-8: + +``` +set_charset(""utf8""); + +// MySQL: +$connection = mysql_connect(/* ... credentials ... */); +mysql_set_charset(""utf8"", $connection); + +?> + +```","in my case, I had to add this line: + +``` +mysqli_set_charset($con,""utf8mb4""); + +```" +37307901,"I was messing around with transitions and I noticed some stuttering and flickering when the transitions are applied to the selection in a different function. If, however, the transition is applied with method chaining, it works exactly as prescribed. + +Below is small example ([Fiddle](https://jsfiddle.net/Fjotten/k8kv4arv/1/)) of simply moving some text. The first, leftmost, string magically teleports down the page before the transition starts. The second, rightmost, string has a smooth transition from the top to the bottom of the page. + +Why does this 'teleport' happen? Obviously applying the transitions in a separate function is not the same as chaining it, but is there a way to achieve this? Say, I want to apply the same transition to many different objects - retrieved from different selects - then is there a way to relegate the transition to its own function without getting this stuttering? + +``` +var svg = d3.select('svg'); +var textElem = svg.append('text') + .data(['hello world']) + .attr('x', 30) + .attr('y', 100) + .attr('fill', '#000') + .attr('id', 'a') + .text(function (d) { + return d; + }); +var textElem2 = svg.append('text') + .data(['some text']) + .attr('x', 230) + .attr('y', 100) + .attr('fill', '#000') + .attr('id', 'a') + .text(function (d) { + return d; + }); +setTimeout(foo, 3000); + +function foo() { + textElem.data(['hello world, again!']); + applyTextTransitions(textElem); + textElem.attr({ + x: 30, + y: 150 + }); + textElem.text(function (d) { + return d; + }); + + textElem2.data(['some more text!']) + .transition() + .duration(1000) + .style('opacity', 0) + .transition() + .duration(1000) + .style('opacity', 1) + .attr({ + x: 230, + y: 150 + }) + .text(function (d) { + return d; + }); +} + +function applyTextTransitions(element) { + element + .transition() + .duration(1000) + .style('opacity', 0) + .transition() + .duration(1000) + .style('opacity', 1); +} + +```",2016/05/18,"['https://Stackoverflow.com/questions/37307901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4231740/']","You could use a simple circle collision detection such as described on msdn website: + +``` +function circlesOverlap(circleA, circleB) { // Returns true if the SVG circles A and B overlap, false otherwise. + var deltaX = circleA.cx.baseVal.value - circleB.cx.baseVal.value; + var deltaY = circleA.cy.baseVal.value - circleB.cy.baseVal.value; + var distance = Math.sqrt( (deltaX*deltaX) + (deltaY*deltaY) ); // The classic distance-between-two-points formula. + var radiusA = circleA.r.baseVal.value; // The radius of circle A. + var radiusB = circleB.r.baseVal.value; // The radius of circle B. + + if (circleA.id == circleB.id) // If true, circleA and circleB are the same circle. + return false; + + return distance <= (radiusA + radiusB); +}; + +``` + +Using your fiddle, this is what it gives: + + +Your animate function is now as simple as: + +``` +function animate () { + var earth = document.getElementById(""Earth""), + sun = document.getElementById(""Sun""); + + planetrotation(""Earth""); + + if( circlesOverlap(earth, sun) ) + { + earth.setAttribute(""fill-opacity"", ""0.0""); + sun.setAttribute(""fill-opacity"", ""0.0""); + } +} + +```","Try using .offset() rather than .position() (check the console, with position, the values are never changing, with offset, they change) + +``` +var positionplanet = $(""#Earth"").offset(); +var positionsun = $(""#Sun"").offset(); + +``` + + + +As far as a good collision detection, you could write something saying if the planet's top offset is greater than the sun's top offset, but less than the sun's top offset + the sun's height and something similar for left offset/height. To trigger just when the planet touches the sun in any direction, you could throw in the planet's height and width to the equation. It would take some playing + +``` +if ( (positionplanet.left > positionsun.left && positionplanet.left < positionsun.left + SUNWIDTH) && (positionplanet.top > positionsun.top && positionplanet.top < positionsun.top + SUNHEIGHT) ) { + //the planet is completely inside of the sun +} + +if ( (positionplanet.left > positionsun.left - PLANETWIDTH && positionplanet.left < positionsun.left + SUNWIDTH - PLANETWIDTH) && (positionplanet.top > positionsun.top - PLANETHEIGHT && positionplanet.top < positionsun.top + SUNHEIGHT - PLANETHEIGHT) ) { + //the planet is touching the sun (will need some fiddling I'm sure..) +} + +```" +37307901,"I was messing around with transitions and I noticed some stuttering and flickering when the transitions are applied to the selection in a different function. If, however, the transition is applied with method chaining, it works exactly as prescribed. + +Below is small example ([Fiddle](https://jsfiddle.net/Fjotten/k8kv4arv/1/)) of simply moving some text. The first, leftmost, string magically teleports down the page before the transition starts. The second, rightmost, string has a smooth transition from the top to the bottom of the page. + +Why does this 'teleport' happen? Obviously applying the transitions in a separate function is not the same as chaining it, but is there a way to achieve this? Say, I want to apply the same transition to many different objects - retrieved from different selects - then is there a way to relegate the transition to its own function without getting this stuttering? + +``` +var svg = d3.select('svg'); +var textElem = svg.append('text') + .data(['hello world']) + .attr('x', 30) + .attr('y', 100) + .attr('fill', '#000') + .attr('id', 'a') + .text(function (d) { + return d; + }); +var textElem2 = svg.append('text') + .data(['some text']) + .attr('x', 230) + .attr('y', 100) + .attr('fill', '#000') + .attr('id', 'a') + .text(function (d) { + return d; + }); +setTimeout(foo, 3000); + +function foo() { + textElem.data(['hello world, again!']); + applyTextTransitions(textElem); + textElem.attr({ + x: 30, + y: 150 + }); + textElem.text(function (d) { + return d; + }); + + textElem2.data(['some more text!']) + .transition() + .duration(1000) + .style('opacity', 0) + .transition() + .duration(1000) + .style('opacity', 1) + .attr({ + x: 230, + y: 150 + }) + .text(function (d) { + return d; + }); +} + +function applyTextTransitions(element) { + element + .transition() + .duration(1000) + .style('opacity', 0) + .transition() + .duration(1000) + .style('opacity', 1); +} + +```",2016/05/18,"['https://Stackoverflow.com/questions/37307901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4231740/']","You could use a simple circle collision detection such as described on msdn website: + +``` +function circlesOverlap(circleA, circleB) { // Returns true if the SVG circles A and B overlap, false otherwise. + var deltaX = circleA.cx.baseVal.value - circleB.cx.baseVal.value; + var deltaY = circleA.cy.baseVal.value - circleB.cy.baseVal.value; + var distance = Math.sqrt( (deltaX*deltaX) + (deltaY*deltaY) ); // The classic distance-between-two-points formula. + var radiusA = circleA.r.baseVal.value; // The radius of circle A. + var radiusB = circleB.r.baseVal.value; // The radius of circle B. + + if (circleA.id == circleB.id) // If true, circleA and circleB are the same circle. + return false; + + return distance <= (radiusA + radiusB); +}; + +``` + +Using your fiddle, this is what it gives: + + +Your animate function is now as simple as: + +``` +function animate () { + var earth = document.getElementById(""Earth""), + sun = document.getElementById(""Sun""); + + planetrotation(""Earth""); + + if( circlesOverlap(earth, sun) ) + { + earth.setAttribute(""fill-opacity"", ""0.0""); + sun.setAttribute(""fill-opacity"", ""0.0""); + } +} + +```","You should be able to use either `position` or `offset` according to jQuery docs - + +> +> The `.position()` method allows us to retrieve the current position of +> an element relative to the offset parent. Contrast this with +> `.offset()`, which retrieves the current position relative to the +> document. When positioning a new element near another one and within +> the same containing DOM element, `.position()` is the more useful. +> +> +> + +So, what your issue is here, is that the position/offset will be different for elements of differing sizes. Even if they are on top of each other. + +The reasoning, is because when you ask for the `left` positioning of the sun, since it's radius is bigger, thus a larger circle, it's left offset/position is less than what the earth would be. + +So now, you just have a simple math problem to solve for concentric circles - aka finding the distance between the edge of the sun and the edge of the earth, then you would need to subtract/add to whichever offset you want to check against. + +The way you find the distance between the two is by subtracting the radii. Now, I know that the `r` value does not refer to pixels, so I wasn't sure how to do that in your situation, but I think this should get you most of the way." +61417816,"I wrote a simple Node.js program with a nice menu system facilitated by [inquirer.js](https://github.com/SBoudrias/Inquirer.js/). However, after selecting an option in the menu and completing some action, the program exits. I need the menu to show again, until I select the Exit [last] option in the menu. I would like to do this using Promise, *instead* of async/await. + +I tried using a function to show the menu and called that function within a forever loop (E.g. `while (true) { ... }`), but that made the program unusable. I changed that to a for-loop just to observe the problem. Below is the simple program and the resulting output. + +**`PROGRAM`** + +``` +""use strict""; + +const inquirer = require('inquirer'); +const util = require('util') + +// Clear the screen +process.stdout.write(""\u001b[2J\u001b[0;0H""); + +const showMenu = () => { + const questions = [ + { + type: ""list"", + name: ""action"", + message: ""What do you want to do?"", + choices: [ + { name: ""action 1"", value: ""Action1"" }, + { name: ""action 2"", value: ""Action2"" }, + { name: ""Exit program"", value: ""quit""} + ] + } + ]; + return inquirer.prompt(questions); +}; + +const main = () => { + for (let count = 0; count < 3; count++) { + showMenu() + .then(answers => { + if (answers.action === 'Action1') { + return Promise.resolve('hello world'); + } + else if (answers.action === 'Action2') { + return new Promise((resolve, reject) => { + inquirer + .prompt([ + { + type: 'input', + name: 'secretCode', + message: ""Enter a secret code:"" + } + ]) + .then(answers => { + resolve(answers); + }) + }); + } + else { + console.log('Exiting program.') + process.exit(0); + } + }) + .then((data) => { console.log(util.inspect(data, { showHidden: false, depth: null })); }) + .catch((error, response) => { + console.error('Error:', error); + }); + } +} + +main() + +``` + +**`OUTPUT`** + +``` +? What do you want to do? (Use arrow keys) +❯ action 1 + action 2 + Exit program ? What do you want to do? (Use arrow keys) +❯ action 1 + action 2 + Exit program ? What do you want to do? (Use arrow keys) +❯ action 1 + action 2 + Exit program (node:983) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 keypress listeners added to [ReadStream]. Use emitter.setMaxListeners() to increase limit + +``` + +How can I block after the first call to generate the menu, wait for an option to be selected and the corresponding action to complete, and then cycle back to the next iteration of showing the menu?",2020/04/24,"['https://Stackoverflow.com/questions/61417816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/371392/']","You can use `async/await` syntax: + +Declare your `main` function `async`, and `await` the returned Promise from inquirer: + +```js +const main = async () => { + for (let count = 0; count < 3; count++) { + await showMenu() + .then(answers => { + [...] + } +}; + +``` + +Your code doesn't work as you expect because, in short, the interpreter executes synchronous code before running any callbacks (from promises). As a consequence your synchronous `for` loop executes before any I/O callbacks are resolved. All calls to `showMenu()` returns promises which are resolved asynchronously, meaning nothing will be printed, and no inputs will be interpreted until after looping. + +Writing `await` blocks succeeding synchronous code inside an `async` function, which is what it seems you're trying to do.","Using your code as a starting point, I hacked together my own library for displaying cli menus. It strips away a lot of Inquirer's boilerplate, letting you declare a menu graph/tree concisely. + +The main.ts file shows how you use it. You declare a dictionary of MenuPrompts, which you add Menus, Actions and LoopActions to. Each prompt has a key, which other prompts can route to. + +```js +// main.ts + +import { Menu, Action, MenuPrompt, openMenuPrompt, LoopAction } from ""./menus""; + +// Set of prompts +let prompts = { + menu_1: new MenuPrompt(""Menu 1 - This list is ordinal - What would like to do?"", 20, true, [ + new Menu(""Menu 2"", ""menu_2""), + new LoopAction(""Action"", () => console.log(""Menu 1 action executed"")), + new Action(""Back"", context => context.last), + new Action(""Exit"", () => process.exit(0)), + ]), + menu_2: new MenuPrompt(""Menu 2 - This list is NOT ordinal - What would like to do?"", 20, false, [ + new Menu(""Menu 1"", ""menu_1""), + new LoopAction(""Action"", () => console.log(""Menu 2 action executed"")), + new Action(""Back"", context => context.last), + new Action(""Exit"", () => process.exit(0)), + ]), +}; + +// Open the ""menu_1"" prompt +openMenuPrompt(""menu_1"", prompts); + +``` + +This is the lib file, which contains types & the function for opening the initial prompt. + +```js +// menus.ts + +import * as inquirer from ""inquirer""; + +// MAIN FUNCTION +export let openMenuPrompt = async (current: string, prompts: Dict, last?: string): Promise => { + let answer: Answer = (await inquirer.prompt([prompts[current]])).value; + let next = answer.execute({current, last}); + if (!next) return; + return await openMenuPrompt(next, prompts, current == next? last : current ); +}; + +// PUBLIC TYPES +export class MenuPrompt { + type = ""list""; + name = ""value""; + message: string; + pageSize: number; + choices: Choice[]; + constructor(message: string, pageSize: number, isOrdinalList: boolean, choices: Choice[]) { + this.message = message; + this.pageSize = pageSize; + this.choices = choices; + if (isOrdinalList) { + this.choices.forEach((choice, i) => choice.name = `${i + 1}: ${choice.name}`) + } + } +} + +export interface Choice { + name: string; + value: Answer; +} +export class Action implements Choice { + name: string; + value: Answer; + constructor(name: string, execute: (context?: MenuContext) => any) { + this.name = name; + this.value = {execute}; + } +} +export class LoopAction implements Choice { + name: string; + value: Answer; + constructor(name: string, execute: (context?: MenuContext) => any) { + this.name = name; + this.value = {execute: context => execute(context) ?? context.current}; + } +} +export class Menu implements Choice { + name: string; + value: Answer; + constructor(name: string, menuKey: string) { + this.name = name; + this.value = {execute: () => menuKey}; + } +} + +// INTERNAL TYPES +type Dict = {[key: string]: T}; + +interface Answer { + execute: (context: MenuContext) => any; +} +interface MenuContext { + current: string; + last: string; +} + +```" +20066413,"Here is what I wanna do: + +1. Check if a folder exists +2. If it does not exists, create the folder +3. If it doest exists do nothing +4. At last create a file in that folder + +Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: + +``` +File folder = new File(""D:\\temp""); +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +String filePath = folder + File.separator; +File file = new File(filePath + ""xxx.xml""); + +StreamResult result = new StreamResult(file); +transformer.transform(source, result); +// more code here + +```",2013/11/19,"['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']","`D:\temp` does not exists in linux systems (what I mean is it interprets it as if it were any other foldername) + +In Linux systems the file seperator is `/` instead of `\` as in case of Windows + +so the solution is to : + +``` +File folder = new File(""/tmp""); + +``` + +instead of + +``` +File folder = new File(""D:\\temp""); + +```","Consider both solutions using the getProperty static method of System class. + +``` +String os = System.getProperty(""os.name""); + +if(os.indexOf(""nix"") >= 0 || os.indexOf(""nux"") >= 0 || os.indexOf(""aix"") > 0 ) // Unix + File folder = new File(""/home/tmp""); +else if(os.indexOf(""win"") >= 0) // Windows + File folder = new File(""D:\\temp""); +else + throw Exception(""your message""); + +```" +20066413,"Here is what I wanna do: + +1. Check if a folder exists +2. If it does not exists, create the folder +3. If it doest exists do nothing +4. At last create a file in that folder + +Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: + +``` +File folder = new File(""D:\\temp""); +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +String filePath = folder + File.separator; +File file = new File(filePath + ""xxx.xml""); + +StreamResult result = new StreamResult(file); +transformer.transform(source, result); +// more code here + +```",2013/11/19,"['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']","You directory (D:\temp) is nos appropriate on Linux. + +Please, consider using linux File System, and the File.SEPARATOR constant : + +``` +static String OS = System.getProperty(""OS.name"").toLowerCase(); +String root = ""/tmp""; + +if (OS.indexOf(""win"") >= 0) { + root=""D:\\temp""; +} else { + root=""/""; +} + +File folder = new File(ROOT + ""dir1"" + File.SEPARATOR + ""dir2""); + +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +``` + +Didn't tried it, but whould work.","Before Java 7 the File API has some possibilities to create a temporary file, utilising the operating system configuration (like temp files on a RAM disk). Since Java 7 use the utility functions class [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createTempDirectory%28java.nio.file.Path,%20java.lang.String,%20java.nio.file.attribute.FileAttribute...%29)." +20066413,"Here is what I wanna do: + +1. Check if a folder exists +2. If it does not exists, create the folder +3. If it doest exists do nothing +4. At last create a file in that folder + +Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: + +``` +File folder = new File(""D:\\temp""); +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +String filePath = folder + File.separator; +File file = new File(filePath + ""xxx.xml""); + +StreamResult result = new StreamResult(file); +transformer.transform(source, result); +// more code here + +```",2013/11/19,"['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']","Linux does not use drive letters (like D:) and uses forward slashes as file separator. + +You can do something like this: + +``` +File folder = new File(""/path/name/of/the/folder""); +folder.mkdirs(); // this will also create parent directories if necessary +File file = new File(folder, ""filename""); +StreamResult result = new StreamResult(file); + +```","Since Java 7, you can use the [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) utility class, with the new [Path](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html) class. **Note that exception handling has been omitted in the examples below.** + +``` +// uses os separator for path/to/folder. +Path file = Paths.get(""path"",""to"",""file""); + +// this creates directories in case they don't exist +Files.createDirectories(file.getParent()); + +if (!Files.exists(file)) { + Files.createFile(file); +} + +StreamResult result = new StreamResult(file.toFile()); +transformer.transform(source, result); + +``` + +this covers the generic case, create a folder if it doesn't exist and a file on that folder. + +--- + +In case you actually want to create a temporary file, as written in your example, then you just need to do the following: + +``` +// this create a temporary file on the system's default temp folder. +Path tempFile = Files.createTempFile(""xxx"", ""xml""); + +StreamResult result = new StreamResult(Files.newOutputStream(file, CREATE, APPEND, DELETE_ON_CLOSE)); +transformer.transform(source, result); + +``` + +Note that with this method, the file name will not correspond exactly to the prefix you used (`xxx`, in this case). + +Still, given that it's a temp file, that shouldn't matter at all. The DELETE\_ON\_CLOSE guarantees that the file will get deleted when closed." +20066413,"Here is what I wanna do: + +1. Check if a folder exists +2. If it does not exists, create the folder +3. If it doest exists do nothing +4. At last create a file in that folder + +Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: + +``` +File folder = new File(""D:\\temp""); +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +String filePath = folder + File.separator; +File file = new File(filePath + ""xxx.xml""); + +StreamResult result = new StreamResult(file); +transformer.transform(source, result); +// more code here + +```",2013/11/19,"['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']","`D:\temp` does not exists in linux systems (what I mean is it interprets it as if it were any other foldername) + +In Linux systems the file seperator is `/` instead of `\` as in case of Windows + +so the solution is to : + +``` +File folder = new File(""/tmp""); + +``` + +instead of + +``` +File folder = new File(""D:\\temp""); + +```","Since Java 7, you can use the [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) utility class, with the new [Path](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html) class. **Note that exception handling has been omitted in the examples below.** + +``` +// uses os separator for path/to/folder. +Path file = Paths.get(""path"",""to"",""file""); + +// this creates directories in case they don't exist +Files.createDirectories(file.getParent()); + +if (!Files.exists(file)) { + Files.createFile(file); +} + +StreamResult result = new StreamResult(file.toFile()); +transformer.transform(source, result); + +``` + +this covers the generic case, create a folder if it doesn't exist and a file on that folder. + +--- + +In case you actually want to create a temporary file, as written in your example, then you just need to do the following: + +``` +// this create a temporary file on the system's default temp folder. +Path tempFile = Files.createTempFile(""xxx"", ""xml""); + +StreamResult result = new StreamResult(Files.newOutputStream(file, CREATE, APPEND, DELETE_ON_CLOSE)); +transformer.transform(source, result); + +``` + +Note that with this method, the file name will not correspond exactly to the prefix you used (`xxx`, in this case). + +Still, given that it's a temp file, that shouldn't matter at all. The DELETE\_ON\_CLOSE guarantees that the file will get deleted when closed." +20066413,"Here is what I wanna do: + +1. Check if a folder exists +2. If it does not exists, create the folder +3. If it doest exists do nothing +4. At last create a file in that folder + +Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: + +``` +File folder = new File(""D:\\temp""); +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +String filePath = folder + File.separator; +File file = new File(filePath + ""xxx.xml""); + +StreamResult result = new StreamResult(file); +transformer.transform(source, result); +// more code here + +```",2013/11/19,"['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']","`D:\temp` does not exists in linux systems (what I mean is it interprets it as if it were any other foldername) + +In Linux systems the file seperator is `/` instead of `\` as in case of Windows + +so the solution is to : + +``` +File folder = new File(""/tmp""); + +``` + +instead of + +``` +File folder = new File(""D:\\temp""); + +```","Before Java 7 the File API has some possibilities to create a temporary file, utilising the operating system configuration (like temp files on a RAM disk). Since Java 7 use the utility functions class [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createTempDirectory%28java.nio.file.Path,%20java.lang.String,%20java.nio.file.attribute.FileAttribute...%29)." +20066413,"Here is what I wanna do: + +1. Check if a folder exists +2. If it does not exists, create the folder +3. If it doest exists do nothing +4. At last create a file in that folder + +Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: + +``` +File folder = new File(""D:\\temp""); +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +String filePath = folder + File.separator; +File file = new File(filePath + ""xxx.xml""); + +StreamResult result = new StreamResult(file); +transformer.transform(source, result); +// more code here + +```",2013/11/19,"['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']","Linux does not use drive letters (like D:) and uses forward slashes as file separator. + +You can do something like this: + +``` +File folder = new File(""/path/name/of/the/folder""); +folder.mkdirs(); // this will also create parent directories if necessary +File file = new File(folder, ""filename""); +StreamResult result = new StreamResult(file); + +```","On Unix-like systems no logical discs. You can try create on `/tmp` or `/home` +Below code for create `temp` dirrectory in your home directory: + +``` +String myPathCandidate = System.getProperty(""os.name"").equals(""Linux"")? System.getProperty(""user.home""):""D:\\""; + System.out.println(myPathCandidate); + //Check write permissions + File folder = new File(myPathCandidate); + if (folder.exists() && folder.isDirectory() && folder.canWrite()) { + System.out.println(""Create directory here""); + } else {System.out.println(""Wrong path"");} + +``` + +or, for `/tmp` - system temp dicecrory. Majority of users can write here: + +``` +String myPathCandidate = System.getProperty(""os.name"").equals(""Linux"")? System.getProperty(""java.io.tmpdir""):""D:\\""; + +```" +20066413,"Here is what I wanna do: + +1. Check if a folder exists +2. If it does not exists, create the folder +3. If it doest exists do nothing +4. At last create a file in that folder + +Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: + +``` +File folder = new File(""D:\\temp""); +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +String filePath = folder + File.separator; +File file = new File(filePath + ""xxx.xml""); + +StreamResult result = new StreamResult(file); +transformer.transform(source, result); +// more code here + +```",2013/11/19,"['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']","Linux does not use drive letters (like D:) and uses forward slashes as file separator. + +You can do something like this: + +``` +File folder = new File(""/path/name/of/the/folder""); +folder.mkdirs(); // this will also create parent directories if necessary +File file = new File(folder, ""filename""); +StreamResult result = new StreamResult(file); + +```","Consider both solutions using the getProperty static method of System class. + +``` +String os = System.getProperty(""os.name""); + +if(os.indexOf(""nix"") >= 0 || os.indexOf(""nux"") >= 0 || os.indexOf(""aix"") > 0 ) // Unix + File folder = new File(""/home/tmp""); +else if(os.indexOf(""win"") >= 0) // Windows + File folder = new File(""D:\\temp""); +else + throw Exception(""your message""); + +```" +20066413,"Here is what I wanna do: + +1. Check if a folder exists +2. If it does not exists, create the folder +3. If it doest exists do nothing +4. At last create a file in that folder + +Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: + +``` +File folder = new File(""D:\\temp""); +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +String filePath = folder + File.separator; +File file = new File(filePath + ""xxx.xml""); + +StreamResult result = new StreamResult(file); +transformer.transform(source, result); +// more code here + +```",2013/11/19,"['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']","You directory (D:\temp) is nos appropriate on Linux. + +Please, consider using linux File System, and the File.SEPARATOR constant : + +``` +static String OS = System.getProperty(""OS.name"").toLowerCase(); +String root = ""/tmp""; + +if (OS.indexOf(""win"") >= 0) { + root=""D:\\temp""; +} else { + root=""/""; +} + +File folder = new File(ROOT + ""dir1"" + File.SEPARATOR + ""dir2""); + +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +``` + +Didn't tried it, but whould work.","Since Java 7, you can use the [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html) utility class, with the new [Path](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html) class. **Note that exception handling has been omitted in the examples below.** + +``` +// uses os separator for path/to/folder. +Path file = Paths.get(""path"",""to"",""file""); + +// this creates directories in case they don't exist +Files.createDirectories(file.getParent()); + +if (!Files.exists(file)) { + Files.createFile(file); +} + +StreamResult result = new StreamResult(file.toFile()); +transformer.transform(source, result); + +``` + +this covers the generic case, create a folder if it doesn't exist and a file on that folder. + +--- + +In case you actually want to create a temporary file, as written in your example, then you just need to do the following: + +``` +// this create a temporary file on the system's default temp folder. +Path tempFile = Files.createTempFile(""xxx"", ""xml""); + +StreamResult result = new StreamResult(Files.newOutputStream(file, CREATE, APPEND, DELETE_ON_CLOSE)); +transformer.transform(source, result); + +``` + +Note that with this method, the file name will not correspond exactly to the prefix you used (`xxx`, in this case). + +Still, given that it's a temp file, that shouldn't matter at all. The DELETE\_ON\_CLOSE guarantees that the file will get deleted when closed." +20066413,"Here is what I wanna do: + +1. Check if a folder exists +2. If it does not exists, create the folder +3. If it doest exists do nothing +4. At last create a file in that folder + +Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: + +``` +File folder = new File(""D:\\temp""); +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +String filePath = folder + File.separator; +File file = new File(filePath + ""xxx.xml""); + +StreamResult result = new StreamResult(file); +transformer.transform(source, result); +// more code here + +```",2013/11/19,"['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']","Linux does not use drive letters (like D:) and uses forward slashes as file separator. + +You can do something like this: + +``` +File folder = new File(""/path/name/of/the/folder""); +folder.mkdirs(); // this will also create parent directories if necessary +File file = new File(folder, ""filename""); +StreamResult result = new StreamResult(file); + +```","Before Java 7 the File API has some possibilities to create a temporary file, utilising the operating system configuration (like temp files on a RAM disk). Since Java 7 use the utility functions class [Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createTempDirectory%28java.nio.file.Path,%20java.lang.String,%20java.nio.file.attribute.FileAttribute...%29)." +20066413,"Here is what I wanna do: + +1. Check if a folder exists +2. If it does not exists, create the folder +3. If it doest exists do nothing +4. At last create a file in that folder + +Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code: + +``` +File folder = new File(""D:\\temp""); +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +String filePath = folder + File.separator; +File file = new File(filePath + ""xxx.xml""); + +StreamResult result = new StreamResult(file); +transformer.transform(source, result); +// more code here + +```",2013/11/19,"['https://Stackoverflow.com/questions/20066413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1966049/']","You directory (D:\temp) is nos appropriate on Linux. + +Please, consider using linux File System, and the File.SEPARATOR constant : + +``` +static String OS = System.getProperty(""OS.name"").toLowerCase(); +String root = ""/tmp""; + +if (OS.indexOf(""win"") >= 0) { + root=""D:\\temp""; +} else { + root=""/""; +} + +File folder = new File(ROOT + ""dir1"" + File.SEPARATOR + ""dir2""); + +if (folder.exists() && folder.isDirectory()) { +} else { + folder.mkdir(); +} + +``` + +Didn't tried it, but whould work.","On Unix-like systems no logical discs. You can try create on `/tmp` or `/home` +Below code for create `temp` dirrectory in your home directory: + +``` +String myPathCandidate = System.getProperty(""os.name"").equals(""Linux"")? System.getProperty(""user.home""):""D:\\""; + System.out.println(myPathCandidate); + //Check write permissions + File folder = new File(myPathCandidate); + if (folder.exists() && folder.isDirectory() && folder.canWrite()) { + System.out.println(""Create directory here""); + } else {System.out.println(""Wrong path"");} + +``` + +or, for `/tmp` - system temp dicecrory. Majority of users can write here: + +``` +String myPathCandidate = System.getProperty(""os.name"").equals(""Linux"")? System.getProperty(""java.io.tmpdir""):""D:\\""; + +```" +1468037,"Using Flex 3, I had created a employer profile application where I could view 10 profiles in a page using repeater, however, when I tried to load 20 profiles in a page, all of the component go haywire, became non-function. + +It would not happen if I set the application height to 100% but due to native scrollbar requirement, I use Swffit to enable web browser scrollbar and hide the Flex scrollbar and set the height of the flex application with exact viewable contents in pixel. + +How do I solve the canvas height issue?",2009/09/23,"['https://Stackoverflow.com/questions/1468037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']","Have you tried placing the Canvas inside of some other container with an explicit height? That might be all you need. + +eg: + +``` + + + + +``` + +I'm not sure if this will work, but it seems like it is worth a try.","I have this part of the code as you have shown me. + +I was think of creating a custom components with canvas and loop with the repeater or another idea is that I might use one of the working solution I have just thought of it to overcome the issue." +59116410,"I'm trying to replace any global variables in my example to a specific value `$var` as shows in the following example: + +(example.php) + +``` + + +``` + +As shown in the example above, I want to change any global variables `$_POST, $_GET, $_REQUEST` automatically in the php file to specific value `$var` in the php file. + +Here is what I did to get each line and check if the line of code have `$_POST` or `$_GET` or `$_REQUEST`, then I'm trying to change any global variables in the file to specific value `$var`. + +(test.php) + +``` + &$value) { + +if(strpos($value, '$_GET') !== false){ + // Replace $_GET['firstname'] and put $var +} +elseif(strpos($value, '$_POST') !== false){ + // Replace $_POST['lastname'] and put $var +} +elseif(strpos($value, '$_REQUEST') !== false){ + // Replace $_REQUEST['age'] and put $var +} + +} +?> + +``` + +The expected results to be after replace any global variables to `$var` is as following: + +(example.php) + +``` + + +``` + +I appreciated if anyone anyone can help me to find a suitable way to replace any `$_GET, $_POST, $_REQUEST` exist in the file by `$var`. + +* note: I want to replace any `$_GET[], $_POST[], $_REQUEST` by `$var`, $var to be stored as following: + +``` + + +``` + +* Note: This is how I hope the php file to be looks like.",2019/11/30,"['https://Stackoverflow.com/questions/59116410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10092475/']","Is that what you want? + +``` +$file = file_get_contents(""example.php""); +$lines = explode(""\n"", $file); + +$var = '$var'; +foreach ($lines as $key => &$value) { + + if(strpos($value, '$_GET') !== false){ + $value = preg_replace('/\$_GET\[.+?\]/', $var, $value); + } + elseif(strpos($value, '$_POST') !== false){ + $value = preg_replace('/\$_POST\[.+?\]/', $var, $value); + } + elseif(strpos($value, '$_REQUEST') !== false){ + $value = preg_replace('/\$_REQUEST\[.+?\]/', $var, $value); + } +} + +```","**Solution:** + +The following code will turn `$_REQUEST['thisvar']` into `$thisvar`, as well as any other `$_GET`/`$_POST` variables you have set. + +As mentioned in the comments `$_REQUEST` covers both `$_GET` and `$_POST`. + +``` +foreach($_REQUEST as $key => $value) $$key = $value; + +``` + +**If I modify your example:** + +``` +$file = file_get_contents(""example.php""); +$lines = explode(""\n"", $file); + +foreach($lines as $key => $value) $$key = $value; + +```" +59116410,"I'm trying to replace any global variables in my example to a specific value `$var` as shows in the following example: + +(example.php) + +``` + + +``` + +As shown in the example above, I want to change any global variables `$_POST, $_GET, $_REQUEST` automatically in the php file to specific value `$var` in the php file. + +Here is what I did to get each line and check if the line of code have `$_POST` or `$_GET` or `$_REQUEST`, then I'm trying to change any global variables in the file to specific value `$var`. + +(test.php) + +``` + &$value) { + +if(strpos($value, '$_GET') !== false){ + // Replace $_GET['firstname'] and put $var +} +elseif(strpos($value, '$_POST') !== false){ + // Replace $_POST['lastname'] and put $var +} +elseif(strpos($value, '$_REQUEST') !== false){ + // Replace $_REQUEST['age'] and put $var +} + +} +?> + +``` + +The expected results to be after replace any global variables to `$var` is as following: + +(example.php) + +``` + + +``` + +I appreciated if anyone anyone can help me to find a suitable way to replace any `$_GET, $_POST, $_REQUEST` exist in the file by `$var`. + +* note: I want to replace any `$_GET[], $_POST[], $_REQUEST` by `$var`, $var to be stored as following: + +``` + + +``` + +* Note: This is how I hope the php file to be looks like.",2019/11/30,"['https://Stackoverflow.com/questions/59116410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10092475/']","[See Regex Demo](https://regex101.com/r/FdiQgh/1/) + +`/\$_(GET|POST|REQUEST)\[[^\]]*\]/'` will match, for example, `$_GET[anything-other-than-a-right-bracket]` and all we have to do is replace it with `$var` and rewrite the file: + +``` + $value) $$key = $value; + +``` + +**If I modify your example:** + +``` +$file = file_get_contents(""example.php""); +$lines = explode(""\n"", $file); + +foreach($lines as $key => $value) $$key = $value; + +```" +59116410,"I'm trying to replace any global variables in my example to a specific value `$var` as shows in the following example: + +(example.php) + +``` + + +``` + +As shown in the example above, I want to change any global variables `$_POST, $_GET, $_REQUEST` automatically in the php file to specific value `$var` in the php file. + +Here is what I did to get each line and check if the line of code have `$_POST` or `$_GET` or `$_REQUEST`, then I'm trying to change any global variables in the file to specific value `$var`. + +(test.php) + +``` + &$value) { + +if(strpos($value, '$_GET') !== false){ + // Replace $_GET['firstname'] and put $var +} +elseif(strpos($value, '$_POST') !== false){ + // Replace $_POST['lastname'] and put $var +} +elseif(strpos($value, '$_REQUEST') !== false){ + // Replace $_REQUEST['age'] and put $var +} + +} +?> + +``` + +The expected results to be after replace any global variables to `$var` is as following: + +(example.php) + +``` + + +``` + +I appreciated if anyone anyone can help me to find a suitable way to replace any `$_GET, $_POST, $_REQUEST` exist in the file by `$var`. + +* note: I want to replace any `$_GET[], $_POST[], $_REQUEST` by `$var`, $var to be stored as following: + +``` + + +``` + +* Note: This is how I hope the php file to be looks like.",2019/11/30,"['https://Stackoverflow.com/questions/59116410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10092475/']","[See Regex Demo](https://regex101.com/r/FdiQgh/1/) + +`/\$_(GET|POST|REQUEST)\[[^\]]*\]/'` will match, for example, `$_GET[anything-other-than-a-right-bracket]` and all we have to do is replace it with `$var` and rewrite the file: + +``` + &$value) { + + if(strpos($value, '$_GET') !== false){ + $value = preg_replace('/\$_GET\[.+?\]/', $var, $value); + } + elseif(strpos($value, '$_POST') !== false){ + $value = preg_replace('/\$_POST\[.+?\]/', $var, $value); + } + elseif(strpos($value, '$_REQUEST') !== false){ + $value = preg_replace('/\$_REQUEST\[.+?\]/', $var, $value); + } +} + +```" +35522805,"Something strange here with Meteor 1.2.1 and Iron Router 1.0.12. + +``` +Router.route('/news/:_id', function() { + this.render('l_basic'); + console.log (newsCollection.findOne().title); +}); + +``` + +This works perfect. I’ve got the title of my last post in the console. + +But there is an unwanted exception too. No matter where I would place database query: into the main router function, to the onAfterAction or any other hook. Doesn't matter, if I'll surround it with `if (this.ready())`. + +If I comment console.log statement, no exception appears. + +This is what I get in console. I've completely broken my head, trying to find out what is going on here. + +``` +Exception in callback of async function: http://localhost:3000/app/both/router.js?4bb8a45e172aaff7cfe3c5a6bff0f87a62d217d0:17:59 +boundNext@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:418:35 +http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:27 +onRerun@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:515:13 +boundNext@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:418:35 +http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:27 +onRun@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:499:15 +boundNext@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:418:35 +http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:27 +dispatch@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:442:7 +_runRoute@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:538:17 +dispatch@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:848:27 +route@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:705:19 +boundNext@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:418:35 +http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:27 +boundNext@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:365:18 +http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:27 +dispatch@http://localhost:3000/packages/iron_middleware-stack.js?3370bd57ef7b310cca3f5dddb11b77fafdcfc1eb:442:7 +http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:385:21 +_compute@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:349:36 +Computation@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:237:18 +autorun@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:588:34 +http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:383:17 +nonreactive@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:615:13 +dispatch@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:382:19 +dispatch@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:1692:22 +onLocationChange@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:1776:33 +_compute@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:349:36 +Computation@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:237:18 +autorun@http://localhost:3000/packages/tracker.js?7776276660c988c38fed448d8262b925dffb5bc3:588:34 +start@http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:1769:43 +http://localhost:3000/packages/iron_router.js?c564289eeaa191561eba900052037432ebfcbe4a:972:21 +withValue@http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:971:21 +http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:428:54 +http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:999:27 +onGlobalMessage@http://localhost:3000/packages/meteor.js?9730f4ff059088b3f7f14c0672d155218a1802d4:365:23 + +```",2016/02/20,"['https://Stackoverflow.com/questions/35522805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2498182/']","Here is some [helpful documentation](https://meteorhacks.com/subscription-manager-for-iron-router/) on managing subscriptions for Iron Router. + +I'm pretty sure your `findOne()` is returning `undefined` at this point, which means your findOne().title is going to throw an exception. You'll want to use `waitOn()` to get your subscriptions ready before querying data.","Thanks to Stephen Woods I found that my initial code printed both the exception and the title just because of reactivity. And everything I had to do is wait for subscriptions from iron:router. + +``` +Router.route('/news/:_id', function() { + this.render('l_basic'); + console.log (newsCollection.findOne().title); +}, { + waitOn: function () { + return Meteor.subscribe('news'); +}); + +```" +12410727,"I have a list of `
  • ` items being generated from a CMS/DB. Each `
  • ` has a `
    ` in it which contains a link to a lightbox (a hidden `
    `). The link targets the id of the hidden `
    ` (#inline-content-print) so the javascript plugin triggers and pulls up the lightbox. + +The problem I'm running into is that all of the `
  • `s on the page generate with the same hidden `div` id (I can change this to classes). So no matter which `
  • ` href is clicked, it always pulls up the lightbox for the first `
  • ` on the page (the first instance of the id). I need a way for the href to say ""open #inline-content-print"" from THIS `div` (the one the link being clicked lives in)"". + +``` +
  • +
    + +PRINT + +
    + CONTENT OF LIGHTBOX +
    + + +
    +
  • + +``` + +Any advice would be greatly appreciated.",2012/09/13,"['https://Stackoverflow.com/questions/12410727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1669207/']","**If I'm not wrong, when a `before` callback returns `false`, the transaction gets rolled back.** +That's probably what's happening. + +``` +def check_new_record + self.is_new = self.new_record? +end + +``` + +When `self.new_record?` returns `false`, it assigns `false` to `self.is_new` and then the method returns `self.is_new`, which is `false` too. + +Try this instead: + +``` +def check_new_record + self.is_new = self.new_record? + true +end + +```","For one thing, you can get rid of the hack you have to detect if the record is new in the after\_save. If the record is new, the .changed? method will return true. + +``` +class Video < ActiveRecord::Base + after_save :index_me + + def index_me + Resque.enqueue(IndexVideo, self.id) if self.changed? + end +end + +```" +11460929,"This is more of a theory question than a programming question. As you know when you instantiate a table view in iOS, you have to account for dequeuing and reusing table cells, when they are scrolled in and out of view. + +The confusing thing to me is, all the data that populates the cells is cached anyway. When you look at a web page in safari, you are scrolling past a lot more images and text that remains after you scroll past it. I have iOS games installed that use many times more data (e.g., Asphalt 6) than a simple table. So I'm just curious why Apple goes to the trouble of dequeuing and reusing table cells. Thanks.",2012/07/12,"['https://Stackoverflow.com/questions/11460929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/591487/']","It's not about the amount of data in the model. It is more so about the amount of memory that is used in creating the Cell views. If I have a table that is going to create over 1000 `UITableViewCell` objects, why would it create them all when only about a dozen or so can appear on the screen? Don't just think about the data that is held and being displayed, think about the memory that is taken up in the objects that are displaying the data, the `UITableViewCell`s.","It's just good memory management. There's no telling how big a table could be, so better safe than sorry. You only ever need the memory for however many cells fit in a view." +1404832,"is it possible to initialize a List with other List's in C#? Say I've got these to lists: + +``` +List set1 = new List() {1, 2, 3}; +List set2 = new List() {4, 5, 6}; + +``` + +What I'd like to have is a shorthand for this code: + +``` +List fullSet = new List(); +fullSet.AddRange(set1); +fullSet.AddRange(set2); + +``` + +Thanks in advance!",2009/09/10,"['https://Stackoverflow.com/questions/1404832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16440/']","``` + static void Main(string[] args) + { + List set1 = new List() { 1, 2, 3 }; + List set2 = new List() { 4, 5, 6 }; + + List set3 = new List(Combine(set1, set2)); + } + + private static IEnumerable Combine(IEnumerable list1, IEnumerable list2) + { + foreach (var item in list1) + { + yield return item; + } + + foreach (var item in list2) + { + yield return item; + } + } + +```","``` +var fullSet = set1.Union(set2); // returns IEnumerable + +``` + +If you want List instead of IEnumerable you could do: + +``` +List fullSet = new List(set1.Union(set2)); + +```" +1404832,"is it possible to initialize a List with other List's in C#? Say I've got these to lists: + +``` +List set1 = new List() {1, 2, 3}; +List set2 = new List() {4, 5, 6}; + +``` + +What I'd like to have is a shorthand for this code: + +``` +List fullSet = new List(); +fullSet.AddRange(set1); +fullSet.AddRange(set2); + +``` + +Thanks in advance!",2009/09/10,"['https://Stackoverflow.com/questions/1404832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16440/']","To allow duplicate elements (as in your example): + +``` +List fullSet = set1.Concat(set2).ToList(); + +``` + +This can be generalized for more lists, i.e. `...Concat(set3).Concat(set4)`. If you want to remove duplicate elements (those items that appear in both lists): + +``` +List fullSet = set1.Union(set2).ToList(); + +```","``` +var fullSet = set1.Union(set2); // returns IEnumerable + +``` + +If you want List instead of IEnumerable you could do: + +``` +List fullSet = new List(set1.Union(set2)); + +```" +1404832,"is it possible to initialize a List with other List's in C#? Say I've got these to lists: + +``` +List set1 = new List() {1, 2, 3}; +List set2 = new List() {4, 5, 6}; + +``` + +What I'd like to have is a shorthand for this code: + +``` +List fullSet = new List(); +fullSet.AddRange(set1); +fullSet.AddRange(set2); + +``` + +Thanks in advance!",2009/09/10,"['https://Stackoverflow.com/questions/1404832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16440/']","``` + static void Main(string[] args) + { + List set1 = new List() { 1, 2, 3 }; + List set2 = new List() { 4, 5, 6 }; + + List set3 = new List(Combine(set1, set2)); + } + + private static IEnumerable Combine(IEnumerable list1, IEnumerable list2) + { + foreach (var item in list1) + { + yield return item; + } + + foreach (var item in list2) + { + yield return item; + } + } + +```","``` +List fullSet = new List(set1.Union(set2)); + +``` + +may work." +1404832,"is it possible to initialize a List with other List's in C#? Say I've got these to lists: + +``` +List set1 = new List() {1, 2, 3}; +List set2 = new List() {4, 5, 6}; + +``` + +What I'd like to have is a shorthand for this code: + +``` +List fullSet = new List(); +fullSet.AddRange(set1); +fullSet.AddRange(set2); + +``` + +Thanks in advance!",2009/09/10,"['https://Stackoverflow.com/questions/1404832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16440/']","To allow duplicate elements (as in your example): + +``` +List fullSet = set1.Concat(set2).ToList(); + +``` + +This can be generalized for more lists, i.e. `...Concat(set3).Concat(set4)`. If you want to remove duplicate elements (those items that appear in both lists): + +``` +List fullSet = set1.Union(set2).ToList(); + +```","``` +List fullSet = new List(set1.Union(set2)); + +``` + +may work." +1404832,"is it possible to initialize a List with other List's in C#? Say I've got these to lists: + +``` +List set1 = new List() {1, 2, 3}; +List set2 = new List() {4, 5, 6}; + +``` + +What I'd like to have is a shorthand for this code: + +``` +List fullSet = new List(); +fullSet.AddRange(set1); +fullSet.AddRange(set2); + +``` + +Thanks in advance!",2009/09/10,"['https://Stackoverflow.com/questions/1404832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16440/']","To allow duplicate elements (as in your example): + +``` +List fullSet = set1.Concat(set2).ToList(); + +``` + +This can be generalized for more lists, i.e. `...Concat(set3).Concat(set4)`. If you want to remove duplicate elements (those items that appear in both lists): + +``` +List fullSet = set1.Union(set2).ToList(); + +```","``` + static void Main(string[] args) + { + List set1 = new List() { 1, 2, 3 }; + List set2 = new List() { 4, 5, 6 }; + + List set3 = new List(Combine(set1, set2)); + } + + private static IEnumerable Combine(IEnumerable list1, IEnumerable list2) + { + foreach (var item in list1) + { + yield return item; + } + + foreach (var item in list2) + { + yield return item; + } + } + +```" +49292885,"I need to have `TabbedPage` throughout the app. In the first page Tab's are displaying fine. When I am starting second page From Tab1, It is hiding all tabs. How can I have Tab's all over the app. + +[![First page with tabs](https://i.stack.imgur.com/A5yVm.png)](https://i.stack.imgur.com/A5yVm.png) +[![Second page without tabs](https://i.stack.imgur.com/pCEH2.png)](https://i.stack.imgur.com/pCEH2.png) + +MainPage.xaml + +``` + + + + + + + + + +``` + +This is the code from starting 2nd page + +``` +btnDemo.Clicked +=async delegate { + await Navigation.PushModalAsync(new Page2()); + }; + +```",2018/03/15,"['https://Stackoverflow.com/questions/49292885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8977696/']","> +> I need to have TabbedPage throughout the app +> +> +> + +You must add a `NavigationPage` as a child page in your TabbedPage in order to open pages inside the tab + +So in your Xaml, you can have a `NavigationPage` inside TabbedPage + +``` + + + + + + + + + +``` + +Then you can add pages like this + +``` +public class MainPageCS : TabbedPage{ + public MainPageCS () + { + var navigationPage = new NavigationPage (new MyPage ()); + + navigationPage.Title = ""Your title""; + + Children.Add (new PageA ()); + Children.Add (navigationPage); + } +} + +``` + +So Navigation can be performed from this second page which is a instance of NavigationPage, like below + +``` +async void OnSomeButtonClicked (object sender, EventArgs e) +{ + await Navigation.PushAsync (new Page2()); +} + +``` + +More info in this [here](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/tabbed-page)","Try to use: + +`Navigation.PushAsync(new Page2());` + +Instead of: + +`Navigation.PushModalAsync(new Page2());`" +1628058,"Ok. this one's a challenge. + +I have a tableview within a navigation controller. + +I push it from the root, where I have an add action that allows me to add a new record. That works fine. + +Now what I've tried to do is add this tableview to a tab bar view (without a tab bar controller cuz that won't work) but within the same navigation controller. + +So what I want to do is this: Root > TabBarView (loads Tableview) > add new record. + +The problem lies in the managed object context, I get the whole ""can't find entity error"" but I have no idea how to fix it. + +I've managed to get the AddRecord modal view controller to show up from the tabBarView, but it presents itself without a navigationbar, whereas if I try to add a record in the solitary tableView (outside of the tabbar) its no problem. + +I'm now calling my methods from the TabBarView's navigationBarbuttons, routing through to the tableviews methods. + +I know my methods have to be called from the tabBarView instead of the actual tableview now, and they do fire, but I don't know how to manage the MOC when its in a tabView. + +Oh, and this is based on coredata recipes and books, so when the add record method is fired, it creates a new MOC to create it, then reintegrates back in the main MOC when you're done. + +Any ideas?",2009/10/27,"['https://Stackoverflow.com/questions/1628058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/188710/']","In the Intellij configuration that you use to start the server, set 'Server host' to the hostname of your machine. If it is set to 'localhost' you can't connect using the actual hostname of the machine.",You should launch Grails with debug parameters (grailsDebug) and create a Remote debug run configuration in IntelliJ IDEA's Run Configurations combobox. Enter your host name and port there and you can connect now. +1803867,"thanks for taking the time to look at my problems. + +I was trying to calculate the norm of $(3, 1 + \sqrt{-17})$ and $(\sqrt{-17})$. +The second one is 17 because of the norm of the element $\sqrt{-17}$, but how does this follow from $|\mathbb{Z}[\sqrt{-17}]/(\sqrt{-17})|$? + +I tried to calculate $|\mathbb{Z}[\sqrt{-17}]/(3, 1+\sqrt{-17})|$ and concluded that $\mathbb{Z}[\sqrt{-17}]/(3, 1+\sqrt{-17}) \cong \mathbb{Z}/3\mathbb{Z}$ such that $|\mathbb{Z}[\sqrt{-17}]/(3, 1+\sqrt{-17})| = 3$. Is this correct? + +Thanks in advance!",2016/05/28,"['https://math.stackexchange.com/questions/1803867', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/296749/']","Your computations are correct. + +Since $-17\equiv3\bmod{4}$ our ring of integers is $\mathbb{Z}[\sqrt{-17}]$, so we may factor the ideal $(3)$ in $\mathbb{Z}[\sqrt{-17}]$ by factoring + +$$x^2 + 17 \equiv x^2 - 1 \equiv (x+1)(x+2) \bmod{3}.$$ + +This yields the ideal $(3,1+\sqrt{-17})$, and since 3 splits the norm of this ideal is 3. + +To see this more directly, we can use the ring isomorphism theorems. We have $(x^2+17) \subseteq (3,1+x) \subseteq \mathbb{Z}[x]$ from above, hence + +$$\mathbb{Z}[\sqrt{-17}]/(3,1+\sqrt{-17}) \cong + \mathbb{Z}[x]/(3,1+x) \cong + \mathbb{Z}/3$$ + +As for $(\sqrt{-17})$, the same argument works.","Given $a+b\sqrt{-17}$, you can subtract $b(1+\sqrt{-17})$ to get a rational integer, then subtract an appropriate multiple of 3 to get 0, 1, or 2. So the quotient ring has at most 3 elements, indeed, has number of elements a divisor of 3, so it now suffices to show it's not 1. + +If it's 1, then 1 is in the ideal, $1=3(a+b\sqrt{-17})+(1+\sqrt{-17})(c+d\sqrt{-17})$. Multiply everything out, and equate rational terms and equate irrational terms, to get the equations, $1=3a+c-17d$, $0=3b+c+d$. Subtraction yields $1=3(a-b-6d)$, a clear impossibility, so it's 3." +1803867,"thanks for taking the time to look at my problems. + +I was trying to calculate the norm of $(3, 1 + \sqrt{-17})$ and $(\sqrt{-17})$. +The second one is 17 because of the norm of the element $\sqrt{-17}$, but how does this follow from $|\mathbb{Z}[\sqrt{-17}]/(\sqrt{-17})|$? + +I tried to calculate $|\mathbb{Z}[\sqrt{-17}]/(3, 1+\sqrt{-17})|$ and concluded that $\mathbb{Z}[\sqrt{-17}]/(3, 1+\sqrt{-17}) \cong \mathbb{Z}/3\mathbb{Z}$ such that $|\mathbb{Z}[\sqrt{-17}]/(3, 1+\sqrt{-17})| = 3$. Is this correct? + +Thanks in advance!",2016/05/28,"['https://math.stackexchange.com/questions/1803867', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/296749/']","Your computations are correct. + +Since $-17\equiv3\bmod{4}$ our ring of integers is $\mathbb{Z}[\sqrt{-17}]$, so we may factor the ideal $(3)$ in $\mathbb{Z}[\sqrt{-17}]$ by factoring + +$$x^2 + 17 \equiv x^2 - 1 \equiv (x+1)(x+2) \bmod{3}.$$ + +This yields the ideal $(3,1+\sqrt{-17})$, and since 3 splits the norm of this ideal is 3. + +To see this more directly, we can use the ring isomorphism theorems. We have $(x^2+17) \subseteq (3,1+x) \subseteq \mathbb{Z}[x]$ from above, hence + +$$\mathbb{Z}[\sqrt{-17}]/(3,1+\sqrt{-17}) \cong + \mathbb{Z}[x]/(3,1+x) \cong + \mathbb{Z}/3$$ + +As for $(\sqrt{-17})$, the same argument works.","You already seem know that the norm of a prinicipal ideal is the norm of its generator. Hence $|\mathbb Z[\sqrt{-17}]/(3)|=9$. + +We have $(3) \subsetneq (3,1+\sqrt{-17}) \subsetneq (1)$, hence $\mathbb Z[\sqrt{-17}]/(3,1+\sqrt{-17})$ is a non-trivial quotient of $\mathbb Z[\sqrt{-17}]/(3)$. A non-trivial quotient of a group with $9$ elements must have $3$ elements, hence we obtain + +$$|\mathbb Z[\sqrt{-17}]/(3,1+\sqrt{-17})|=3$$ + +without having calculated the quotient (Which would be of course an easy task, too, as shown in the other answers)." +19533566,"I have a LinearLayout with a white background,filled with a bunch of LinearLayouts and RelativeLayouts. I've tried to set the parent layout to have a minimum height, but it still seems to be wrapping to the content. + +Here's a picture of what it looks like now. The white space should have a set minimum height that is greater than it is now. +![enter image description here](https://i.stack.imgur.com/SSrnO.png) + +Here's what I think is a relevant section of the xml: + +``` + + + + + + + + + + + + + + + + + + + + + + +``` + +... and many other LinearLayouts, all set to 'GONE' programmatically. + +Can anyone suggest a fix? I can't figure out why that white section is taking up so little space.",2013/10/23,"['https://Stackoverflow.com/questions/19533566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2175846/']","``` +// try this + + + + + + + + + + + + + + + + + + + + + + + + + + + +```","set the height in second linearlayout. now it is set as wrap content.. do like + +``` + + + + + + + +```" +19533566,"I have a LinearLayout with a white background,filled with a bunch of LinearLayouts and RelativeLayouts. I've tried to set the parent layout to have a minimum height, but it still seems to be wrapping to the content. + +Here's a picture of what it looks like now. The white space should have a set minimum height that is greater than it is now. +![enter image description here](https://i.stack.imgur.com/SSrnO.png) + +Here's what I think is a relevant section of the xml: + +``` + + + + + + + + + + + + + + + + + + + + + + +``` + +... and many other LinearLayouts, all set to 'GONE' programmatically. + +Can anyone suggest a fix? I can't figure out why that white section is taking up so little space.",2013/10/23,"['https://Stackoverflow.com/questions/19533566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2175846/']","``` +// try this + + + + + + + + + + + + + + + + + + + + + + + + + + + +```","It can be because of the device size too. I'd definitely suggest using linear layout's weight. That should make it perfect on all the devices irrespective of tablet or phone. + +Let me know if you want any more guidance, or if you have any issues with weight." +18835104,"I have a library in User Space that intercepts socket layer calls such as `socket()`, `connect()`, `accept()`, etc. I'm only dealing with TCP sockets. + +Down in Kernel Space I have a network kernel module, which deals with all the TCP connections. I need to be able to identify in the driver which sockets were intercepted by the User Space library. + +So far I've been using the `priority` field from `struct sock` (Kernel) that I can set with `setsockopt()` in User Space. But that's quite a dirty hack. + +Is there any kind of private field of `struct sock` I could safely use and set from User Space through `setsockopt()`? + +Thanks.",2013/09/16,"['https://Stackoverflow.com/questions/18835104', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1181890/']","There is really no such ""private field"" option that can be used solely by user space and your kernel code. + +Using the `SO_PRIORITY` option seems a little too intrusive, as it can change how the stack processes packets, and it might lead to hard to understand results. A safer option would be to adjust the `SO_RCVBUF` or `SO_SNDBUF` values by some small delta from the usual default. Linux will double the value passed in, but you can look for the delta from the default values and know that the presence of the delta as a signal that this is your ""intercepted"" socket.","Getting to your original question ""I need to be able to identify in the driver which sockets were intercepted by the User Space library."" there are a few functions in fact. + +Firstly you need to know that ALL the existing connections are stored in a global hash table - ""tcp\_hashinfo"", and you can find the address in /proc/kallsyms. + +The main function is \_\_inet\_lookup\_skb(), which called \_\_inet\_lookup(), and split into \_\_inet\_lookup\_established() (looking for any matching sockets that have been established) and \_\_inet\_lookup\_listener() (looking for opened listener, but no established connections yet). + +The main inputs required for lookup is the source/destination ports and IP addresses information, if found the returning pointer is a ""struct sock \*"" to the socket. + +IPv6 has about the same name, and same logic too. + +The function (\_\_inet\_lookup\_skb()) is declared ""static inline"" - it cannot be found from /proc/kallsyms and neither can drivers see it, as it is compiled inline. But no problem for that as this call two other function - inet\_lookup\_listener() and inet\_lookup\_established() which are NOT compiled inline. Symbols for it are exported, so you are safe to use it from a kernel module. + +It is important that reading this hashinfo table is a critical operation - multiple CPUs may be reading/writing to it at the same time, and which is why locking is done at the beginning/end of functions when reading is done, to be prevent it being modified while being read. As it is difficult to access these RCU locks, even though it is global by nature, don't re-implement these functions, just reuse them." +13086869,"I am creating a 12 month calendar using the individual calendar controls for each month. Since I am controlling the calendars (Jan - Dec) via separate next year and previous year buttons, I want to remove the previous and next calendaritem buttons from the individual calendars and disable the ability to change the display mode. + +Since I am new to XAML and more comfortable with doing this in code, I would prefer to change the style at runtime but willing to learn how to make it happen via XAML but I am having a very difficult time finding an example of someone doing something like this. + +Hope someone can help.",2012/10/26,"['https://Stackoverflow.com/questions/13086869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1777028/']","I would refer you to [this](http://msdn.microsoft.com/en-us/magazine/dd882520.aspx) article to get some basic understanding of Calendar control. + +In short, you need to modify CalendarItemStyle and remove PART\_PreviousButton and PART\_NextButton from its template. You can find default template for all parts of Calendar control [here](http://msdn.microsoft.com/en-us/library/ff468218.aspx). + +When you create a new calendar item style without those parts then set it to [CalendarItemStyle](http://msdn.microsoft.com/en-us/library/system.windows.controls.calendar.calendaritemstyle.aspx) property of your calendar in XAML.","Like Chris, I didn't want to mess with a ton a XAML. I also needed to hide/show dynamically. I imagine there is a way to do this with bindings in XAML as well, but I thought this was a pretty simple start. Just add a new class with this code, then use this derived control instead. + +Edit: I updated it to have a property you can set, HidePrevNextBtns. If checked/true, buttons will be hidden. This code does make a couple assumptions. One is that the template will also have prev/next buttons, and other is they will be visible by default. + +``` +class MyCalendar : Calendar +{ + public Button PrevBtn; + public Button NextBtn; + + protected bool _HidePrevNextBtns; + public bool HidePrevNextBtns + { + get + { + return (_HidePrevNextBtns); + } + set + { + _HidePrevNextBtns = value; + if (PrevBtn != null) + { + PrevBtn.Visibility = _HidePrevNextBtns ? Visibility.Hidden : Visibility.Visible; + NextBtn.Visibility = _HidePrevNextBtns ? Visibility.Hidden : Visibility.Visible; + } + } + } + + public override void OnApplyTemplate() + { + base.OnApplyTemplate(); + + var cal = this.Template.FindName(""PART_CalendarItem"", this) as CalendarItem; + + cal.Loaded += new RoutedEventHandler(cal_Loaded); + } + + void cal_Loaded(object sender, RoutedEventArgs e) + { + var cal = sender as CalendarItem; + PrevBtn = cal.Template.FindName(""PART_PreviousButton"", cal) as Button; + NextBtn = cal.Template.FindName(""PART_NextButton"", cal) as Button; + if (_HidePrevNextBtns) + { + PrevBtn.Visibility = Visibility.Hidden; + NextBtn.Visibility = Visibility.Hidden; + } + } +} + +```" +13086869,"I am creating a 12 month calendar using the individual calendar controls for each month. Since I am controlling the calendars (Jan - Dec) via separate next year and previous year buttons, I want to remove the previous and next calendaritem buttons from the individual calendars and disable the ability to change the display mode. + +Since I am new to XAML and more comfortable with doing this in code, I would prefer to change the style at runtime but willing to learn how to make it happen via XAML but I am having a very difficult time finding an example of someone doing something like this. + +Hope someone can help.",2012/10/26,"['https://Stackoverflow.com/questions/13086869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1777028/']","Well, after lots of digging, many examples and Dodsky pointing me in the right direction. I figured it out and felt that sharing was the best way to repay the developer community. Since, I am new to XAML it is a small victory in project battle that I am in. Hopefully, it will help other newbies like me. + +I will try to explain the best way that I can to show you how to manipulate the calendar any way that you need to. + +In my UserControl + +``` + + +``` + +Some of the parameters are overkill, the main point is the Dynamic Resource + +``` +CalendarItemStyle=""{DynamicResource calItemStyle}"" + +``` + +In my ResourceDictionary, I added the namespace + +``` +xmlns:primitives=""clr-namespace:System.Windows.Controls.Primitives;assembly=PresentationFramework"" + +``` + +You will also want to add the PresentationFramework reference to your project, if it is not already there. + +``` + + +``` + +I chose to hide the Previous and Next buttons, just in case removal caused a problem with any events but otherwise, it does what I want it to and I can add or take away features as needed. + +Hope this helps others.","Like Chris, I didn't want to mess with a ton a XAML. I also needed to hide/show dynamically. I imagine there is a way to do this with bindings in XAML as well, but I thought this was a pretty simple start. Just add a new class with this code, then use this derived control instead. + +Edit: I updated it to have a property you can set, HidePrevNextBtns. If checked/true, buttons will be hidden. This code does make a couple assumptions. One is that the template will also have prev/next buttons, and other is they will be visible by default. + +``` +class MyCalendar : Calendar +{ + public Button PrevBtn; + public Button NextBtn; + + protected bool _HidePrevNextBtns; + public bool HidePrevNextBtns + { + get + { + return (_HidePrevNextBtns); + } + set + { + _HidePrevNextBtns = value; + if (PrevBtn != null) + { + PrevBtn.Visibility = _HidePrevNextBtns ? Visibility.Hidden : Visibility.Visible; + NextBtn.Visibility = _HidePrevNextBtns ? Visibility.Hidden : Visibility.Visible; + } + } + } + + public override void OnApplyTemplate() + { + base.OnApplyTemplate(); + + var cal = this.Template.FindName(""PART_CalendarItem"", this) as CalendarItem; + + cal.Loaded += new RoutedEventHandler(cal_Loaded); + } + + void cal_Loaded(object sender, RoutedEventArgs e) + { + var cal = sender as CalendarItem; + PrevBtn = cal.Template.FindName(""PART_PreviousButton"", cal) as Button; + NextBtn = cal.Template.FindName(""PART_NextButton"", cal) as Button; + if (_HidePrevNextBtns) + { + PrevBtn.Visibility = Visibility.Hidden; + NextBtn.Visibility = Visibility.Hidden; + } + } +} + +```" +11287899,"Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. + +Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.",2012/07/02,"['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']","You can use clientX or pageX, see [here](http://www.sitepen.com/blog/2011/12/07/touching-and-gesturing-on-iphone-android-and-more/)","Was having similar issue on binding event-handler using jQuery's `.on` function on `canvas` element (Don't know the reason). + +I resolved it by binding event-handler using `addEventListener`. The `event` object in the handler has offsetX and offsetY defined with proper values. + +Hope it helps..." +11287899,"Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. + +Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.",2012/07/02,"['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']","You can use clientX or pageX, see [here](http://www.sitepen.com/blog/2011/12/07/touching-and-gesturing-on-iphone-android-and-more/)","The page - offset / client approach did not work for me. There was still an offset. I found this other solution that works perfectly: + +``` +let r = canvas.getBoundingClientRect(); + +let x = e.touches[0].pageX - r.left; +let y = e.touches[0].pageY - r.top; + +```" +11287899,"Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. + +Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.",2012/07/02,"['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']","You can use clientX or pageX, see [here](http://www.sitepen.com/blog/2011/12/07/touching-and-gesturing-on-iphone-android-and-more/)","Thanks, @Kontiki - this is the solution that finally fixed things for me: + +``` +if(""touchmove"" == e.type) +{ + + let r = canvas.getBoundingClientRect(); + currX = e.touches[0].clientX - r.left; + currY = e.touches[0].clientY - r.top; +} +else +{ + currX = e.offsetX; + currY = e.offsetY; +} + +```" +11287899,"Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. + +Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.",2012/07/02,"['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']","The correct answer based on the comments in the suggested answer: + +``` +e.offsetX = e.touches[0].pageX - e.touches[0].target.offsetLeft; +e.offsetY = e.touches[0].pageY - e.touches[0].target.offsetTop; + +``` + +This ignores any transformations such as rotations or scaling. Also be sure to check if there are any touches.","Was having similar issue on binding event-handler using jQuery's `.on` function on `canvas` element (Don't know the reason). + +I resolved it by binding event-handler using `addEventListener`. The `event` object in the handler has offsetX and offsetY defined with proper values. + +Hope it helps..." +11287899,"Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. + +Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.",2012/07/02,"['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']","The page - offset / client approach did not work for me. There was still an offset. I found this other solution that works perfectly: + +``` +let r = canvas.getBoundingClientRect(); + +let x = e.touches[0].pageX - r.left; +let y = e.touches[0].pageY - r.top; + +```","Was having similar issue on binding event-handler using jQuery's `.on` function on `canvas` element (Don't know the reason). + +I resolved it by binding event-handler using `addEventListener`. The `event` object in the handler has offsetX and offsetY defined with proper values. + +Hope it helps..." +11287899,"Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. + +Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.",2012/07/02,"['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']","Thanks, @Kontiki - this is the solution that finally fixed things for me: + +``` +if(""touchmove"" == e.type) +{ + + let r = canvas.getBoundingClientRect(); + currX = e.touches[0].clientX - r.left; + currY = e.touches[0].clientY - r.top; +} +else +{ + currX = e.offsetX; + currY = e.offsetY; +} + +```","Was having similar issue on binding event-handler using jQuery's `.on` function on `canvas` element (Don't know the reason). + +I resolved it by binding event-handler using `addEventListener`. The `event` object in the handler has offsetX and offsetY defined with proper values. + +Hope it helps..." +11287899,"Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. + +Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.",2012/07/02,"['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']","The correct answer based on the comments in the suggested answer: + +``` +e.offsetX = e.touches[0].pageX - e.touches[0].target.offsetLeft; +e.offsetY = e.touches[0].pageY - e.touches[0].target.offsetTop; + +``` + +This ignores any transformations such as rotations or scaling. Also be sure to check if there are any touches.","The page - offset / client approach did not work for me. There was still an offset. I found this other solution that works perfectly: + +``` +let r = canvas.getBoundingClientRect(); + +let x = e.touches[0].pageX - r.left; +let y = e.touches[0].pageY - r.top; + +```" +11287899,"Is this possible to generate a new Zabbix event from a Ruby script? I was suggested to use [zabbix\_sender](http://www.zabbix.com/documentation/1.8/manpages/zabbix_sender) script, but I couldn't find any example. + +Also, I couldn't find any API related to the [events](http://www.zabbix.com/documentation/1.8/api/event) creation.",2012/07/02,"['https://Stackoverflow.com/questions/11287899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398309/']","The correct answer based on the comments in the suggested answer: + +``` +e.offsetX = e.touches[0].pageX - e.touches[0].target.offsetLeft; +e.offsetY = e.touches[0].pageY - e.touches[0].target.offsetTop; + +``` + +This ignores any transformations such as rotations or scaling. Also be sure to check if there are any touches.","Thanks, @Kontiki - this is the solution that finally fixed things for me: + +``` +if(""touchmove"" == e.type) +{ + + let r = canvas.getBoundingClientRect(); + currX = e.touches[0].clientX - r.left; + currY = e.touches[0].clientY - r.top; +} +else +{ + currX = e.offsetX; + currY = e.offsetY; +} + +```" +232858,"Are all sentences below correct? + +* I parked in the parking lot. +* I parked on the parking lot. +* I parked at the parking lot. + +My understanding is that I can use ""to park in"" if the parking lot is indoors and ""to park at"" with any kind of parking lot, but I'm not sure if ""to park on"" is usual for both indoor and outdoor parking lots.",2019/12/18,"['https://ell.stackexchange.com/questions/232858', 'https://ell.stackexchange.com', 'https://ell.stackexchange.com/users/92124/']","When talking about a structure for holding cars, such as a lot, you park *in*. ""I parked in the lot."" ""I parked in the parking garage."" + +You can also talk about parking *on* a surface or *on* a street/road. ""I parked on the concrete"". ""I parked on 4th Avenue."" ""Parking on grass is not good for your car."" + +In this sense, saying you parked ""on the lot"" is also acceptable (but not as common) because the lot is a surface. You never park *on* a parking garage or other fixed structure that your goes goes inside of. + +You can also park *at* a location or destination. ""I parked at the store."" In this case, the store is your destination. This is a more colloquial way of saying ""I parked in the store's parking lot."" + +In the same sense, you could say you parked *at* a lot or a garage, since they are also locations. ""I parked at the lot on 5th Street."" sounds natural. The lot on 5th Street is a location that you parked at. + +This can get even more complicated: If you parked in a parking garage located on 6th Street, you could say ""I parked on 6th Street"" and then clarify with ""in the parking garage."" + +In some cases, all of these are interchangeable. If a friend asks, ""where did you park?"", you could say ""At the lot on 5th Ave"" OR ""On the lot on 5th Ave"" OR ""In the lot on 5th Ave"". Any of these works because in this situation, the lot could be considered either a location or a surface/structure for cars.","I think you use ""to park in"" both when it’s outdoors and indoors. + +I have never heard someone saying ""to park at"" or ""to park on""." +232858,"Are all sentences below correct? + +* I parked in the parking lot. +* I parked on the parking lot. +* I parked at the parking lot. + +My understanding is that I can use ""to park in"" if the parking lot is indoors and ""to park at"" with any kind of parking lot, but I'm not sure if ""to park on"" is usual for both indoor and outdoor parking lots.",2019/12/18,"['https://ell.stackexchange.com/questions/232858', 'https://ell.stackexchange.com', 'https://ell.stackexchange.com/users/92124/']","> +> I parked in the parking lot. +> +> +> + +This is correct whether the parking lot is enclosed in some way or not (it doesn't matter). The use of ""in"" here generally means ""within the borders of"". This is also the same sense you would use when saying ""I parked in a parking space"" as well. + +> +> I parked on the parking lot. +> +> +> + +This is not common usage for parking lots. It's grammatically correct, but the use of ""on"" emphasizes the idea of ""on top of"", and most parking lots don't actually have a ""top"" (they're open-air spaces with no roofs), so it seems a bit odd to say this. However, it is common to say something like ""I parked on the asphalt"" or ""I parked on the street"", because those are flat things you can put a car on top of. + +> +> I parked at the parking lot. +> +> +> + +This is also fine. This is using ""at"" in the sense of a location which you went to and then you parked there. + +In general: + +* ""in"" is the most common way to say this, and you can use it really any time you are inside of some area with well-defined boundaries (e.g. ""in the parking lot"", ""in the yard"", etc) +* ""at"" is also fine, and would not sound particularly strange in most situations. +* ""on"" would sound strange to most people.","I think you use ""to park in"" both when it’s outdoors and indoors. + +I have never heard someone saying ""to park at"" or ""to park on""." +232858,"Are all sentences below correct? + +* I parked in the parking lot. +* I parked on the parking lot. +* I parked at the parking lot. + +My understanding is that I can use ""to park in"" if the parking lot is indoors and ""to park at"" with any kind of parking lot, but I'm not sure if ""to park on"" is usual for both indoor and outdoor parking lots.",2019/12/18,"['https://ell.stackexchange.com/questions/232858', 'https://ell.stackexchange.com', 'https://ell.stackexchange.com/users/92124/']","When talking about a structure for holding cars, such as a lot, you park *in*. ""I parked in the lot."" ""I parked in the parking garage."" + +You can also talk about parking *on* a surface or *on* a street/road. ""I parked on the concrete"". ""I parked on 4th Avenue."" ""Parking on grass is not good for your car."" + +In this sense, saying you parked ""on the lot"" is also acceptable (but not as common) because the lot is a surface. You never park *on* a parking garage or other fixed structure that your goes goes inside of. + +You can also park *at* a location or destination. ""I parked at the store."" In this case, the store is your destination. This is a more colloquial way of saying ""I parked in the store's parking lot."" + +In the same sense, you could say you parked *at* a lot or a garage, since they are also locations. ""I parked at the lot on 5th Street."" sounds natural. The lot on 5th Street is a location that you parked at. + +This can get even more complicated: If you parked in a parking garage located on 6th Street, you could say ""I parked on 6th Street"" and then clarify with ""in the parking garage."" + +In some cases, all of these are interchangeable. If a friend asks, ""where did you park?"", you could say ""At the lot on 5th Ave"" OR ""On the lot on 5th Ave"" OR ""In the lot on 5th Ave"". Any of these works because in this situation, the lot could be considered either a location or a surface/structure for cars.","> +> I parked in the parking lot. +> +> +> + +This is correct whether the parking lot is enclosed in some way or not (it doesn't matter). The use of ""in"" here generally means ""within the borders of"". This is also the same sense you would use when saying ""I parked in a parking space"" as well. + +> +> I parked on the parking lot. +> +> +> + +This is not common usage for parking lots. It's grammatically correct, but the use of ""on"" emphasizes the idea of ""on top of"", and most parking lots don't actually have a ""top"" (they're open-air spaces with no roofs), so it seems a bit odd to say this. However, it is common to say something like ""I parked on the asphalt"" or ""I parked on the street"", because those are flat things you can put a car on top of. + +> +> I parked at the parking lot. +> +> +> + +This is also fine. This is using ""at"" in the sense of a location which you went to and then you parked there. + +In general: + +* ""in"" is the most common way to say this, and you can use it really any time you are inside of some area with well-defined boundaries (e.g. ""in the parking lot"", ""in the yard"", etc) +* ""at"" is also fine, and would not sound particularly strange in most situations. +* ""on"" would sound strange to most people." +64173564,"I'm trying to upgrade my Spring Boot 2.3.4 app to use Flyway 7.0.0 (the latest version). Previously it was using Flyway 6.5.6. The relevant entries in `build.gradle` are shown below. + +``` +buildscript { + ext { + flywayVersion = ""7.0.0"" // changed from 6.5.6 + } +} + +plugins { + id ""org.flywaydb.flyway"" version ""${flywayVersion}"" +} + +dependencies { + implementation ""org.flywaydb:flyway-core:${flywayVersion}"" +} + +flyway { + url = ""jdbc:postgresql://0.0.0.0:5432/postgres"" + user = ""postgres"" + password = ""secret"" +} + +``` + +The following error occurs when I start the app e.g. with `./gradlew bootRun` + +> +> +> +> --- +> +> +> APPLICATION FAILED TO START +> +> +> +> +> --- +> +> +> Description: +> +> +> An attempt was made to call a method that does not exist. The attempt +> was made from the following location: +> +> +> +> ``` +> org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:65) +> +> ``` +> +> The following method did not exist: +> +> +> +> ``` +> 'int org.flywaydb.core.Flyway.migrate()' +> +> ``` +> +> The method's class, org.flywaydb.core.Flyway, is available from the +> following locations: +> +> +> +> ``` +> jar:file:/Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar!/org/flywaydb/core/Flyway.class +> +> ``` +> +> The class hierarchy was loaded from the following locations: +> +> +> +> ``` +> org.flywaydb.core.Flyway: file:/Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar +> +> ``` +> +> Action: +> +> +> Correct the classpath of your application so that it contains a +> single, compatible version of org.flywaydb.core.Flyway +> +> +>",2020/10/02,"['https://Stackoverflow.com/questions/64173564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4786956/']","Basically, see Philip's comment on your question. + +Flyway 7.x.x is not currently compatible with Spring Boot 2.3.4 + +Temporary solution is to just downgrade to Flyway 6.5.7 (the last 6.x.x version) until Spring Boot 2.3.5 is released. + +Read more and follow the issue here: + +Support for Flyway's new configuration options: ",downgrade to Flyway 6.5.7 works. +64173564,"I'm trying to upgrade my Spring Boot 2.3.4 app to use Flyway 7.0.0 (the latest version). Previously it was using Flyway 6.5.6. The relevant entries in `build.gradle` are shown below. + +``` +buildscript { + ext { + flywayVersion = ""7.0.0"" // changed from 6.5.6 + } +} + +plugins { + id ""org.flywaydb.flyway"" version ""${flywayVersion}"" +} + +dependencies { + implementation ""org.flywaydb:flyway-core:${flywayVersion}"" +} + +flyway { + url = ""jdbc:postgresql://0.0.0.0:5432/postgres"" + user = ""postgres"" + password = ""secret"" +} + +``` + +The following error occurs when I start the app e.g. with `./gradlew bootRun` + +> +> +> +> --- +> +> +> APPLICATION FAILED TO START +> +> +> +> +> --- +> +> +> Description: +> +> +> An attempt was made to call a method that does not exist. The attempt +> was made from the following location: +> +> +> +> ``` +> org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:65) +> +> ``` +> +> The following method did not exist: +> +> +> +> ``` +> 'int org.flywaydb.core.Flyway.migrate()' +> +> ``` +> +> The method's class, org.flywaydb.core.Flyway, is available from the +> following locations: +> +> +> +> ``` +> jar:file:/Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar!/org/flywaydb/core/Flyway.class +> +> ``` +> +> The class hierarchy was loaded from the following locations: +> +> +> +> ``` +> org.flywaydb.core.Flyway: file:/Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar +> +> ``` +> +> Action: +> +> +> Correct the classpath of your application so that it contains a +> single, compatible version of org.flywaydb.core.Flyway +> +> +>",2020/10/02,"['https://Stackoverflow.com/questions/64173564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4786956/']","Basically, see Philip's comment on your question. + +Flyway 7.x.x is not currently compatible with Spring Boot 2.3.4 + +Temporary solution is to just downgrade to Flyway 6.5.7 (the last 6.x.x version) until Spring Boot 2.3.5 is released. + +Read more and follow the issue here: + +Support for Flyway's new configuration options: ","In Flyway 7 the signature of `migrate` changed. + +To get Flyway 7.x.x working with Spring Boot 2.3.x you can provide a custom FlywayMigrationStrategy implementation, which calls the the right `migrate` method. + +``` +import org.flywaydb.core.Flyway; +import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy; +import org.springframework.stereotype.Component; + +@Component +public class FlywayMigrationStrategyImpl implements FlywayMigrationStrategy { + @Override + public void migrate(Flyway flyway) { + flyway.migrate(); + } +} + +```" +64173564,"I'm trying to upgrade my Spring Boot 2.3.4 app to use Flyway 7.0.0 (the latest version). Previously it was using Flyway 6.5.6. The relevant entries in `build.gradle` are shown below. + +``` +buildscript { + ext { + flywayVersion = ""7.0.0"" // changed from 6.5.6 + } +} + +plugins { + id ""org.flywaydb.flyway"" version ""${flywayVersion}"" +} + +dependencies { + implementation ""org.flywaydb:flyway-core:${flywayVersion}"" +} + +flyway { + url = ""jdbc:postgresql://0.0.0.0:5432/postgres"" + user = ""postgres"" + password = ""secret"" +} + +``` + +The following error occurs when I start the app e.g. with `./gradlew bootRun` + +> +> +> +> --- +> +> +> APPLICATION FAILED TO START +> +> +> +> +> --- +> +> +> Description: +> +> +> An attempt was made to call a method that does not exist. The attempt +> was made from the following location: +> +> +> +> ``` +> org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:65) +> +> ``` +> +> The following method did not exist: +> +> +> +> ``` +> 'int org.flywaydb.core.Flyway.migrate()' +> +> ``` +> +> The method's class, org.flywaydb.core.Flyway, is available from the +> following locations: +> +> +> +> ``` +> jar:file:/Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar!/org/flywaydb/core/Flyway.class +> +> ``` +> +> The class hierarchy was loaded from the following locations: +> +> +> +> ``` +> org.flywaydb.core.Flyway: file:/Users/antonio/.gradle/caches/modules-2/files-2.1/org.flywaydb/flyway-core/7.0.0/623494c303c62080ca1bc5886098ee65d1a5528a/flyway-core-7.0.0.jar +> +> ``` +> +> Action: +> +> +> Correct the classpath of your application so that it contains a +> single, compatible version of org.flywaydb.core.Flyway +> +> +>",2020/10/02,"['https://Stackoverflow.com/questions/64173564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4786956/']","In Flyway 7 the signature of `migrate` changed. + +To get Flyway 7.x.x working with Spring Boot 2.3.x you can provide a custom FlywayMigrationStrategy implementation, which calls the the right `migrate` method. + +``` +import org.flywaydb.core.Flyway; +import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy; +import org.springframework.stereotype.Component; + +@Component +public class FlywayMigrationStrategyImpl implements FlywayMigrationStrategy { + @Override + public void migrate(Flyway flyway) { + flyway.migrate(); + } +} + +```",downgrade to Flyway 6.5.7 works. +502374,"I have this spec file that will install numerous rpm packages such as apache, mysql, etc. +I'm new to building rpms and I did looked at the Fedora documentation but I did not find the answer to my question. + +How do I add commands in my spec file so that if I do a: + +``` +rpm -e +yum erase + +``` + +it will stop services that wasn't stopped during yum erase/rpm-e? + +Thanks.",2013/04/24,"['https://serverfault.com/questions/502374', 'https://serverfault.com', 'https://serverfault.com/users/163460/']","It may not be relevant to this case, but remember that if you will upgrade your RPM, rpm will install the new version and then remove the old one, so after upgrade the services will be down. To be on the safe side, do: + +``` +%preun +if [[ $1 -eq 0 ]] +then + service https stop + # or what ever you want +fi + +```","There is a section in spec file preun which runs before package is uninstalled: + +``` +%preun +service https stop +# or what ever you want + +```" +14755569,"I have some floated divs where I can't use display: inline-block because some of those divs are jqxSwitchButtons and using that inline-block would mess everything around those buttons. + +[Here](http://jsfiddle.net/Luigino/Ps3zE/) is a JSFiddle example where I commented some lines that are jqxSwitchButtons and I'd like to center in the middle those divs. + +Code from JSFiddle: + +``` + + + + + + +
    +
    Member ID>
    First Name>
    "" + position + """" + log.Logs1.Team.TeamName + """" + log.Logs1.Played + """" + log.Logs1.Win + """" + log.Logs1.Draw + """" + log.Logs1.Lost + """" + log.Logs1.GoalsFor + """" + log.Logs1.GoalsAgainst + """" + log.Logs1.GoalDifference + """" + log.Logs1.Points + ""
    + + +
    +
    + +
    Element 1
    +
    + +
    Element 2
    +
    + +
    Element 3
    +
    + +
    |
    + +
    + +
    |
    + +
    Auto-compute
    +
    + +
    + +
    + +
    + + + + +``` + +Any suggestions?",2013/02/07,"['https://Stackoverflow.com/questions/14755569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1487979/']","You can use a meteorite package. + +accounts-anonymous + + + +So you use + +``` +Meteor.loginAnonymously(); + +``` + +if the user visits your page for the first time, and use .allow to check what you need","Use a session or localStorage key. When the visitor submits the form check if the key has been set, and if it has, reject the insert." +14755569,"I have some floated divs where I can't use display: inline-block because some of those divs are jqxSwitchButtons and using that inline-block would mess everything around those buttons. + +[Here](http://jsfiddle.net/Luigino/Ps3zE/) is a JSFiddle example where I commented some lines that are jqxSwitchButtons and I'd like to center in the middle those divs. + +Code from JSFiddle: + +``` + + + + + + +
    + + + +
    +
    + +
    Element 1
    +
    + +
    Element 2
    +
    + +
    Element 3
    +
    + +
    |
    + +
    + +
    |
    + +
    Auto-compute
    +
    + +
    + +
    + +
    +
    + + + +``` + +Any suggestions?",2013/02/07,"['https://Stackoverflow.com/questions/14755569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1487979/']","To get the ip address, the observatory () project uses this: + +in coffee: + +``` +Meteor.userIP = (uid)-> + ret = {} + if uid? + s = ss for k, ss of Meteor.default_server.sessions when ss.userId is uid + if s + ret.forwardedFor = s.socket?.headers?['x-forwarded-for'] + ret.remoteAddress = s.socket?.remoteAddress + ret + +``` + +Which returns an object like `{ forwardedFor: '192.168.5.4', remoteAddress: '192.168.5.4' }`","Use a session or localStorage key. When the visitor submits the form check if the key has been set, and if it has, reject the insert." +14755569,"I have some floated divs where I can't use display: inline-block because some of those divs are jqxSwitchButtons and using that inline-block would mess everything around those buttons. + +[Here](http://jsfiddle.net/Luigino/Ps3zE/) is a JSFiddle example where I commented some lines that are jqxSwitchButtons and I'd like to center in the middle those divs. + +Code from JSFiddle: + +``` + + + + + + +
    + + + +
    +
    + +
    Element 1
    +
    + +
    Element 2
    +
    + +
    Element 3
    +
    + +
    |
    + +
    + +
    |
    + +
    Auto-compute
    +
    + +
    + +
    + +
    +
    + + + +``` + +Any suggestions?",2013/02/07,"['https://Stackoverflow.com/questions/14755569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1487979/']","You can use a meteorite package. + +accounts-anonymous + + + +So you use + +``` +Meteor.loginAnonymously(); + +``` + +if the user visits your page for the first time, and use .allow to check what you need","You can do something like this: + +``` +if (Meteor.isClient) { + Meteor.startup(function () { + Session.set('currentuser', 'something randomly generated by another function'); + } +} + +``` + +and check if the 'currentuser' already has inserted in your database." +14755569,"I have some floated divs where I can't use display: inline-block because some of those divs are jqxSwitchButtons and using that inline-block would mess everything around those buttons. + +[Here](http://jsfiddle.net/Luigino/Ps3zE/) is a JSFiddle example where I commented some lines that are jqxSwitchButtons and I'd like to center in the middle those divs. + +Code from JSFiddle: + +``` + + + + + + +
    + + + +
    +
    + +
    Element 1
    +
    + +
    Element 2
    +
    + +
    Element 3
    +
    + +
    |
    + +
    + +
    |
    + +
    Auto-compute
    +
    + +
    + +
    + +
    +
    + + + +``` + +Any suggestions?",2013/02/07,"['https://Stackoverflow.com/questions/14755569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1487979/']","To get the ip address, the observatory () project uses this: + +in coffee: + +``` +Meteor.userIP = (uid)-> + ret = {} + if uid? + s = ss for k, ss of Meteor.default_server.sessions when ss.userId is uid + if s + ret.forwardedFor = s.socket?.headers?['x-forwarded-for'] + ret.remoteAddress = s.socket?.remoteAddress + ret + +``` + +Which returns an object like `{ forwardedFor: '192.168.5.4', remoteAddress: '192.168.5.4' }`","You can do something like this: + +``` +if (Meteor.isClient) { + Meteor.startup(function () { + Session.set('currentuser', 'something randomly generated by another function'); + } +} + +``` + +and check if the 'currentuser' already has inserted in your database." +14755569,"I have some floated divs where I can't use display: inline-block because some of those divs are jqxSwitchButtons and using that inline-block would mess everything around those buttons. + +[Here](http://jsfiddle.net/Luigino/Ps3zE/) is a JSFiddle example where I commented some lines that are jqxSwitchButtons and I'd like to center in the middle those divs. + +Code from JSFiddle: + +``` + + + + + + +
    + + + +
    +
    + +
    Element 1
    +
    + +
    Element 2
    +
    + +
    Element 3
    +
    + +
    |
    + +
    + +
    |
    + +
    Auto-compute
    +
    + +
    + +
    + +
    +
    + + + +``` + +Any suggestions?",2013/02/07,"['https://Stackoverflow.com/questions/14755569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1487979/']","You can use a meteorite package. + +accounts-anonymous + + + +So you use + +``` +Meteor.loginAnonymously(); + +``` + +if the user visits your page for the first time, and use .allow to check what you need","To get the ip address, the observatory () project uses this: + +in coffee: + +``` +Meteor.userIP = (uid)-> + ret = {} + if uid? + s = ss for k, ss of Meteor.default_server.sessions when ss.userId is uid + if s + ret.forwardedFor = s.socket?.headers?['x-forwarded-for'] + ret.remoteAddress = s.socket?.remoteAddress + ret + +``` + +Which returns an object like `{ forwardedFor: '192.168.5.4', remoteAddress: '192.168.5.4' }`" +76593,"in my header and other sections I would like to use + +``` + + +``` + +While maintaining the default theme folder structure in server as below + +``` +/wp-content/themes/theme-name/incs/js/script.js + +``` + +file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** + +``` +http://website.com/incs/js/script.js + +``` + +This is also applicable to images I may have under /incs/images/imagname.jpg + +I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. + +Is this possible? + +Thanks",2012/12/19,"['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']","The easiest way to move your theme folder is only via constant; include the wp-content folder. +You can set a constant for the plugin folder and wp-content folder. Then is your plugins and themes in separete url, also in the include in the source of the frontend. + +like this example for my dev installs: + +``` +define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' ); +define( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' ); +// Custom plugin directory +define( 'WP_PLUGIN_DIR', dirname( __FILE__ ) . '/wp-plugins' ); +define( 'WP_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-plugins' ); +// Custom mu plugin directory +define( 'WPMU_PLUGIN_DIR', dirname( __FILE__ ) . '/wpmu-plugins' ); +define( 'WPMU_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpmu-plugins' ); + +```","Why dont you use bloginfo(); default wordpress functions + +``` + + + + +``` + +more info " +76593,"in my header and other sections I would like to use + +``` + + +``` + +While maintaining the default theme folder structure in server as below + +``` +/wp-content/themes/theme-name/incs/js/script.js + +``` + +file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** + +``` +http://website.com/incs/js/script.js + +``` + +This is also applicable to images I may have under /incs/images/imagname.jpg + +I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. + +Is this possible? + +Thanks",2012/12/19,"['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']","The easiest way to move your theme folder is only via constant; include the wp-content folder. +You can set a constant for the plugin folder and wp-content folder. Then is your plugins and themes in separete url, also in the include in the source of the frontend. + +like this example for my dev installs: + +``` +define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' ); +define( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' ); +// Custom plugin directory +define( 'WP_PLUGIN_DIR', dirname( __FILE__ ) . '/wp-plugins' ); +define( 'WP_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-plugins' ); +// Custom mu plugin directory +define( 'WPMU_PLUGIN_DIR', dirname( __FILE__ ) . '/wpmu-plugins' ); +define( 'WPMU_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpmu-plugins' ); + +```","Nowadays I use the technique I describe in this Q: [Steps to Take to Hide the Fact a Site is Using WordPress?](https://wordpress.stackexchange.com/q/1507/12615). + +Before that, I used the [Roots Theme method](http://benword.com/how-to-hide-that-youre-using-wordpress/), which is what I think you are looking for: + +> +> This post contains information on how to clean up WordPress code output. The methods described below do not prevent actual fingerprinting and shouldn’t be looked at as any sort of security measure. +> +> +> + +Note that it doesn't work in Multisite or Child Themes. + +--- + +I'll reproduce here the documentation I did for using the Roots method: + +Modifying `.htaccess` Rewrite Rules +----------------------------------- + +Large chunk of code directly from the Roots theme: + + [PasteBin mirror](http://pastebin.com/8C2gAb6C). + +The array `$roots_new_non_wp_rules` has to be adapted accordingly. + +Refresh permalinks +------------------ + +Go to `/wp-admin/options-permalink.php` and click `Save Changes`. + +Load scripts from CDN and not from `/wp-includes/` +-------------------------------------------------- + +``` +add_action( 'wp_enqueue_scripts', 'wpse_76593_scripts_custom' ); + +function wpse_76593_scripts_custom() { + wp_deregister_script('jquery'); + wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', false, '1.7.1', true); + wp_enqueue_script( 'jquery' ); +} + +``` + +Search the theme for all style and script registers and enqueues. + +style.css +--------- + +1. create a new file inside the folder ""/css"" named ""style.css"" +2. open the theme's `style.css` +3. select all declarations bellow the [theme file header](http://codex.wordpress.org/File_Header#Theme_File_Header_Example) +4. cut and paste in the file `/css/style.css` +5. save both +in short: `/your-theme/styles.css` will contain only the header information, and `/your-theme/css/styles.css` will contain all the styles + + * change all occurrences of `url('fonts/` with `url('../fonts/` + * change all occurrences of `images/` with `../images/` + +header.php +---------- + +Change the stylesheet link from + +``` +"" /> + +``` + +to + +``` +/css/style.css"" /> + +``` + +All theme files +--------------- + +Search for: + +* `get_bloginfo('template_url')` +* `get_bloginfo('template_directory')` + +and replace with: + +* `get_template_directory_uri()` + +Testing +------- + +Not sure about other browsers, but [Safari Activity Window](https://www.google.com/search?q=safari%20activity%20window&hl=es&safe=off&tbo=d&source=lnms&tbm=isch) is perfect to check all loaded files and its URLs. + +Depending on the theme complexity, extra steps have to be taken." +76593,"in my header and other sections I would like to use + +``` + + +``` + +While maintaining the default theme folder structure in server as below + +``` +/wp-content/themes/theme-name/incs/js/script.js + +``` + +file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** + +``` +http://website.com/incs/js/script.js + +``` + +This is also applicable to images I may have under /incs/images/imagname.jpg + +I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. + +Is this possible? + +Thanks",2012/12/19,"['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']","The easiest way to move your theme folder is only via constant; include the wp-content folder. +You can set a constant for the plugin folder and wp-content folder. Then is your plugins and themes in separete url, also in the include in the source of the frontend. + +like this example for my dev installs: + +``` +define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' ); +define( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' ); +// Custom plugin directory +define( 'WP_PLUGIN_DIR', dirname( __FILE__ ) . '/wp-plugins' ); +define( 'WP_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-plugins' ); +// Custom mu plugin directory +define( 'WPMU_PLUGIN_DIR', dirname( __FILE__ ) . '/wpmu-plugins' ); +define( 'WPMU_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpmu-plugins' ); + +```",I created the [Roots Plug](http://wordpress.org/extend/plugins/roots-plug/) which has the same `.htaccess` rewrites as the Roots Theme. But completely agree with what @brasofolio [said](https://wordpress.stackexchange.com/a/76605/9605) +76593,"in my header and other sections I would like to use + +``` + + +``` + +While maintaining the default theme folder structure in server as below + +``` +/wp-content/themes/theme-name/incs/js/script.js + +``` + +file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** + +``` +http://website.com/incs/js/script.js + +``` + +This is also applicable to images I may have under /incs/images/imagname.jpg + +I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. + +Is this possible? + +Thanks",2012/12/19,"['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']","The easiest way to move your theme folder is only via constant; include the wp-content folder. +You can set a constant for the plugin folder and wp-content folder. Then is your plugins and themes in separete url, also in the include in the source of the frontend. + +like this example for my dev installs: + +``` +define( 'WP_CONTENT_DIR', dirname( __FILE__ ) . '/wp-content' ); +define( 'WP_CONTENT_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' ); +// Custom plugin directory +define( 'WP_PLUGIN_DIR', dirname( __FILE__ ) . '/wp-plugins' ); +define( 'WP_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wp-plugins' ); +// Custom mu plugin directory +define( 'WPMU_PLUGIN_DIR', dirname( __FILE__ ) . '/wpmu-plugins' ); +define( 'WPMU_PLUGIN_URL', 'http://' . $_SERVER['HTTP_HOST'] . '/wpmu-plugins' ); + +```","This can be easily achieved by using '[hide my wp](http://bit.ly/1cyQW91)' plugin. Please change it's permalinks and url settings as shown below: + +![Change theme path under Permalinks & urls to /incs](https://i.stack.imgur.com/tHGVs.jpg) +Change theme path under Permalinks & urls to `/incs`. + +Once you have changed these settings, you will notice, `bloginfo('template_url')` will render `http://website.com/incs/` and hence + +``` + http://website.com/incs/js/script.js + +``` + +Reference: " +76593,"in my header and other sections I would like to use + +``` + + +``` + +While maintaining the default theme folder structure in server as below + +``` +/wp-content/themes/theme-name/incs/js/script.js + +``` + +file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** + +``` +http://website.com/incs/js/script.js + +``` + +This is also applicable to images I may have under /incs/images/imagname.jpg + +I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. + +Is this possible? + +Thanks",2012/12/19,"['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']","Nowadays I use the technique I describe in this Q: [Steps to Take to Hide the Fact a Site is Using WordPress?](https://wordpress.stackexchange.com/q/1507/12615). + +Before that, I used the [Roots Theme method](http://benword.com/how-to-hide-that-youre-using-wordpress/), which is what I think you are looking for: + +> +> This post contains information on how to clean up WordPress code output. The methods described below do not prevent actual fingerprinting and shouldn’t be looked at as any sort of security measure. +> +> +> + +Note that it doesn't work in Multisite or Child Themes. + +--- + +I'll reproduce here the documentation I did for using the Roots method: + +Modifying `.htaccess` Rewrite Rules +----------------------------------- + +Large chunk of code directly from the Roots theme: + + [PasteBin mirror](http://pastebin.com/8C2gAb6C). + +The array `$roots_new_non_wp_rules` has to be adapted accordingly. + +Refresh permalinks +------------------ + +Go to `/wp-admin/options-permalink.php` and click `Save Changes`. + +Load scripts from CDN and not from `/wp-includes/` +-------------------------------------------------- + +``` +add_action( 'wp_enqueue_scripts', 'wpse_76593_scripts_custom' ); + +function wpse_76593_scripts_custom() { + wp_deregister_script('jquery'); + wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', false, '1.7.1', true); + wp_enqueue_script( 'jquery' ); +} + +``` + +Search the theme for all style and script registers and enqueues. + +style.css +--------- + +1. create a new file inside the folder ""/css"" named ""style.css"" +2. open the theme's `style.css` +3. select all declarations bellow the [theme file header](http://codex.wordpress.org/File_Header#Theme_File_Header_Example) +4. cut and paste in the file `/css/style.css` +5. save both +in short: `/your-theme/styles.css` will contain only the header information, and `/your-theme/css/styles.css` will contain all the styles + + * change all occurrences of `url('fonts/` with `url('../fonts/` + * change all occurrences of `images/` with `../images/` + +header.php +---------- + +Change the stylesheet link from + +``` +"" /> + +``` + +to + +``` +/css/style.css"" /> + +``` + +All theme files +--------------- + +Search for: + +* `get_bloginfo('template_url')` +* `get_bloginfo('template_directory')` + +and replace with: + +* `get_template_directory_uri()` + +Testing +------- + +Not sure about other browsers, but [Safari Activity Window](https://www.google.com/search?q=safari%20activity%20window&hl=es&safe=off&tbo=d&source=lnms&tbm=isch) is perfect to check all loaded files and its URLs. + +Depending on the theme complexity, extra steps have to be taken.","Why dont you use bloginfo(); default wordpress functions + +``` + + + + +``` + +more info " +76593,"in my header and other sections I would like to use + +``` + + +``` + +While maintaining the default theme folder structure in server as below + +``` +/wp-content/themes/theme-name/incs/js/script.js + +``` + +file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** + +``` +http://website.com/incs/js/script.js + +``` + +This is also applicable to images I may have under /incs/images/imagname.jpg + +I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. + +Is this possible? + +Thanks",2012/12/19,"['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']",I created the [Roots Plug](http://wordpress.org/extend/plugins/roots-plug/) which has the same `.htaccess` rewrites as the Roots Theme. But completely agree with what @brasofolio [said](https://wordpress.stackexchange.com/a/76605/9605),"Why dont you use bloginfo(); default wordpress functions + +``` + + + + +``` + +more info " +76593,"in my header and other sections I would like to use + +``` + + +``` + +While maintaining the default theme folder structure in server as below + +``` +/wp-content/themes/theme-name/incs/js/script.js + +``` + +file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** + +``` +http://website.com/incs/js/script.js + +``` + +This is also applicable to images I may have under /incs/images/imagname.jpg + +I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. + +Is this possible? + +Thanks",2012/12/19,"['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']","This can be easily achieved by using '[hide my wp](http://bit.ly/1cyQW91)' plugin. Please change it's permalinks and url settings as shown below: + +![Change theme path under Permalinks & urls to /incs](https://i.stack.imgur.com/tHGVs.jpg) +Change theme path under Permalinks & urls to `/incs`. + +Once you have changed these settings, you will notice, `bloginfo('template_url')` will render `http://website.com/incs/` and hence + +``` + http://website.com/incs/js/script.js + +``` + +Reference: ","Why dont you use bloginfo(); default wordpress functions + +``` + + + + +``` + +more info " +76593,"in my header and other sections I would like to use + +``` + + +``` + +While maintaining the default theme folder structure in server as below + +``` +/wp-content/themes/theme-name/incs/js/script.js + +``` + +file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** + +``` +http://website.com/incs/js/script.js + +``` + +This is also applicable to images I may have under /incs/images/imagname.jpg + +I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. + +Is this possible? + +Thanks",2012/12/19,"['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']","Nowadays I use the technique I describe in this Q: [Steps to Take to Hide the Fact a Site is Using WordPress?](https://wordpress.stackexchange.com/q/1507/12615). + +Before that, I used the [Roots Theme method](http://benword.com/how-to-hide-that-youre-using-wordpress/), which is what I think you are looking for: + +> +> This post contains information on how to clean up WordPress code output. The methods described below do not prevent actual fingerprinting and shouldn’t be looked at as any sort of security measure. +> +> +> + +Note that it doesn't work in Multisite or Child Themes. + +--- + +I'll reproduce here the documentation I did for using the Roots method: + +Modifying `.htaccess` Rewrite Rules +----------------------------------- + +Large chunk of code directly from the Roots theme: + + [PasteBin mirror](http://pastebin.com/8C2gAb6C). + +The array `$roots_new_non_wp_rules` has to be adapted accordingly. + +Refresh permalinks +------------------ + +Go to `/wp-admin/options-permalink.php` and click `Save Changes`. + +Load scripts from CDN and not from `/wp-includes/` +-------------------------------------------------- + +``` +add_action( 'wp_enqueue_scripts', 'wpse_76593_scripts_custom' ); + +function wpse_76593_scripts_custom() { + wp_deregister_script('jquery'); + wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', false, '1.7.1', true); + wp_enqueue_script( 'jquery' ); +} + +``` + +Search the theme for all style and script registers and enqueues. + +style.css +--------- + +1. create a new file inside the folder ""/css"" named ""style.css"" +2. open the theme's `style.css` +3. select all declarations bellow the [theme file header](http://codex.wordpress.org/File_Header#Theme_File_Header_Example) +4. cut and paste in the file `/css/style.css` +5. save both +in short: `/your-theme/styles.css` will contain only the header information, and `/your-theme/css/styles.css` will contain all the styles + + * change all occurrences of `url('fonts/` with `url('../fonts/` + * change all occurrences of `images/` with `../images/` + +header.php +---------- + +Change the stylesheet link from + +``` +"" /> + +``` + +to + +``` +/css/style.css"" /> + +``` + +All theme files +--------------- + +Search for: + +* `get_bloginfo('template_url')` +* `get_bloginfo('template_directory')` + +and replace with: + +* `get_template_directory_uri()` + +Testing +------- + +Not sure about other browsers, but [Safari Activity Window](https://www.google.com/search?q=safari%20activity%20window&hl=es&safe=off&tbo=d&source=lnms&tbm=isch) is perfect to check all loaded files and its URLs. + +Depending on the theme complexity, extra steps have to be taken.","This can be easily achieved by using '[hide my wp](http://bit.ly/1cyQW91)' plugin. Please change it's permalinks and url settings as shown below: + +![Change theme path under Permalinks & urls to /incs](https://i.stack.imgur.com/tHGVs.jpg) +Change theme path under Permalinks & urls to `/incs`. + +Once you have changed these settings, you will notice, `bloginfo('template_url')` will render `http://website.com/incs/` and hence + +``` + http://website.com/incs/js/script.js + +``` + +Reference: " +76593,"in my header and other sections I would like to use + +``` + + +``` + +While maintaining the default theme folder structure in server as below + +``` +/wp-content/themes/theme-name/incs/js/script.js + +``` + +file need to be accessed via browser/html source if need be so that it hides **/wp-content/themes/theme-name** + +``` +http://website.com/incs/js/script.js + +``` + +This is also applicable to images I may have under /incs/images/imagname.jpg + +I've seen solutions where defining the directory located outside of theme folder... but need a solution that does this within. + +Is this possible? + +Thanks",2012/12/19,"['https://wordpress.stackexchange.com/questions/76593', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/16419/']",I created the [Roots Plug](http://wordpress.org/extend/plugins/roots-plug/) which has the same `.htaccess` rewrites as the Roots Theme. But completely agree with what @brasofolio [said](https://wordpress.stackexchange.com/a/76605/9605),"This can be easily achieved by using '[hide my wp](http://bit.ly/1cyQW91)' plugin. Please change it's permalinks and url settings as shown below: + +![Change theme path under Permalinks & urls to /incs](https://i.stack.imgur.com/tHGVs.jpg) +Change theme path under Permalinks & urls to `/incs`. + +Once you have changed these settings, you will notice, `bloginfo('template_url')` will render `http://website.com/incs/` and hence + +``` + http://website.com/incs/js/script.js + +``` + +Reference: " +36248147,"I have a regexp: + +``` +import re + +regexp = re.compile(r'^(?P(?:[\w-]+/?)+)/$') + +``` + +It matches a string like `foo/bar/baz/` and put the `foo/bar/baz` in a group named `parts` (the `/?` combined with the `/$` support this). + +This works perfectly fine, **until you match a string that doesn't end in a slash**. Then, it gets slower at a seemingly-exponential rate with each new char you add to the string you're matching. + +### Example + +``` +# This is instant (trailing slash) +regexp.match('this-will-take-no-time-at-all/') + +# This is slow +regexp.match('this-takes-about-5-seconds') + +# This will not finish +regexp.match('this-probably-will-not-finish-until-the-day-star-turns-black') + +``` + +I'm trying to understand why this specific recursion issue only happens when the `/$` (trailing slash) isn't in the string (i.e., a non-match). Could you help me understand the control flow of the underlying algorithm in both the trailing slash and the non trailing slash cases? + +### Note + +I'm not looking for a solution for my desired pattern. I'm trying to understand the specific regexp.",2016/03/27,"['https://Stackoverflow.com/questions/36248147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128463/']","It is getting slow due to [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html) in your regex: + +You can fix catastrophic backtracking by using this regex: + +``` +^(?P(?:[\w-]+/)*[\w-]+)/$ + +``` + +As per the link above: + +> +> The **solution to avoid *catastrophic backtracking*** is simple. When nesting repetition operators, make absolutely sure that there is only one way to match the same match. +> +> +>","Wiktor Stribizew is correct. The issue is the question mark after the slash inside the repeating pattern. So, the pattern you gave: + +``` +'^(?P(?:[\w-]+/?)+)/$' + +``` + +Says, look for one or more groups of one or more word characters or dashes possibly followed by a slash, then there should be a slash at the very end. + +So, for a string like `arm/`, the inner grouping could be any of: + +``` +(arm)/ +(ar)(m)/ +(a)(rm)/ +(a)(r)(m)/ + +``` + +As the string gets longer, if the regex fails to match on its first try, it will check more and more combinations to try to match. To avoid this the same match could be achieved with: + +``` +'^(?P(?:[\w-]+/)*[\w-]+)/$' + +``` + +because this version can only match your target strings one way." +25530172,"1) Here's my schema: + +``` +{ + ""_id"" : ObjectId(""53f4db1d968166157c2d57ce""), + ""init"" : ""SJ"", + ""name"" : ""Steve Jobs"", + ""companies"" : [ + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57cf""), + ""ticker"" : ""AAPL"", + ""compname"" : ""Apple"" + }, + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57d0""), + ""ticker"" : ""MSFT"", + ""compname"" : ""Microsoft"" + }, + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57d1""), + ""ticker"" : ""ABC"", + ""compname"" : ""iTunes"" + }, + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57d2""), + ""ticker"" : ""DEF"", + ""compname"" : ""iPad Mini"" + } + ] +} + +``` + +I'm trying to get a list of compnames, using Powershell & MongoDB. Here's what I have so far: + +``` +$databaseName = ""CompanyInfo"" +$collectionName = ""comps"" +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://localhost:27017"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query['init'] = ""SJ"" +$results = $collection.FindOne($query) +foreach ($result in $results) { + write-host $result[""companies.ticker""] /// Doesn't show me any records +} + +``` + +This doesn't show me any records. How can I display companies.ticker info where init = ""SJ""? + +2) Btw, I get the following error after + +``` +$query['init'] = ""SJ"" + +``` + +error + +``` +Cannot index into a null array. +At line:9 char:1 ++ $query['init'] = ""SJ"" ++ ~~~~~~~~~~~~~~~~~~~~~~ + + CategoryInfo : InvalidOperation: (:) [], RuntimeException + + FullyQualifiedErrorId : NullArray + +``` + +Any ideas as to why? I only have the MongoDB's standard index, which is on ""\_id"", nothing else. My powershell script still works but I'm curious as to why I get that error. + +**[UPDATE Part 2]** Thanks to @arco444, I no longer get error in part 2. Here's my revised code: + +``` +$query = @{'init' = ""SJ""} +$collection.FindOne([MongoDB.Driver.QueryDocument]$query) + +``` + +But I actually need help with part 1 - which is to display only the company tickers for a particular init. Any ideas on that one? + +**[ANSWER Part 1]** Thanks again to @arco444 for directing me to the right path. After some tinkering around, I figured out what I missed. Here's my updated code: + +``` +$databaseName = ""CompanyInfo"" +$collectionName = ""comps"" +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://localhost:27017"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query = new-object MongoDB.Driver.QueryDocument(""init"",""SJ"") /// Updated +$results = $collection.FindOne($query) +foreach ($result in $results[""companies""]) { /// Updated + write-host $result[""ticker""] /// Updated +} + +```",2014/08/27,"['https://Stackoverflow.com/questions/25530172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979127/']","From reading the MongoDB [documentation](http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/#findone-and-findoneas-methods), it looks like you need to initialise the query object properly first. Try this: + +``` +$query = new-object MongoDB.Driver.QueryDocument(""init"",""SJ"") +$results = $collection.FindOne($query) + +```","So when I use your query procedure with + +``` +$mongoDbDriverPath = 'D:\mongo\driver\' +$mongoServer = 'myserver:27000' + +Add-Type -Path ""$($mongoDbDriverPath)MongoDB.Bson.dll"" +Add-Type -Path ""$($mongoDbDriverPath)MongoDB.Driver.dll"" + +$databaseName = 'Tickets' +$collectionName = 'MongoUserTicket' + +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://$mongoServer"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query = new-object Mongodb.driver.querydocument('Id','5') +$query2 = New-object Mongodb.driver.querydocument('Type','User') +$results = @() +foreach($item in $collection.Find($query)) +{ + $results += $item +} + +``` + +I get unexpected results for the query: +When piping to Get member for results I get this: + +``` + TypeName: MongoDB.Bson.BsonElement + +Name MemberType Definition +---- ---------- ---------- +Clone Method MongoDB.Bson.BsonElement Clone() +CompareTo Method int CompareTo(MongoDB.Bson.BsonElement other), int IComparable[BsonElement].CompareTo(MongoDB.Bson.BsonElement other) +DeepClone Method MongoDB.Bson.BsonElement DeepClone() +Equals Method bool Equals(MongoDB.Bson.BsonElement rhs), bool Equals(System.Object obj), bool IEquatable[BsonElement].Equals(MongoDB.Bson.BsonElement other) +GetHashCode Method int GetHashCode() +GetType Method type GetType() +ToString Method string ToString() +Name Property string Name {get;} +Value Property MongoDB.Bson.BsonValue Value {get;set;} + +``` + +When entering $results on the shell prompt I get the data I expect: + +``` +$results + +Name Value +---- ----- +Id 5 +AccessToken +CreatedOn 2013-09-27T22:05:52.246Z +TokenExpiration 2013-09-27T22:20:52.246Z +RefreshTokenExpiration 2013-09-28T22:05:52.246Z +ProfileToken BsonNull +Type User +Id 5 +AccessToken +CreatedOn 2013-09-27T23:42:28.492Z +TokenExpiration 2013-09-27T23:57:28.492Z +RefreshTokenExpiration 2013-09-28T22:06:04.071Z +ProfileToken BsonNull +Type User + +```" +25530172,"1) Here's my schema: + +``` +{ + ""_id"" : ObjectId(""53f4db1d968166157c2d57ce""), + ""init"" : ""SJ"", + ""name"" : ""Steve Jobs"", + ""companies"" : [ + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57cf""), + ""ticker"" : ""AAPL"", + ""compname"" : ""Apple"" + }, + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57d0""), + ""ticker"" : ""MSFT"", + ""compname"" : ""Microsoft"" + }, + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57d1""), + ""ticker"" : ""ABC"", + ""compname"" : ""iTunes"" + }, + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57d2""), + ""ticker"" : ""DEF"", + ""compname"" : ""iPad Mini"" + } + ] +} + +``` + +I'm trying to get a list of compnames, using Powershell & MongoDB. Here's what I have so far: + +``` +$databaseName = ""CompanyInfo"" +$collectionName = ""comps"" +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://localhost:27017"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query['init'] = ""SJ"" +$results = $collection.FindOne($query) +foreach ($result in $results) { + write-host $result[""companies.ticker""] /// Doesn't show me any records +} + +``` + +This doesn't show me any records. How can I display companies.ticker info where init = ""SJ""? + +2) Btw, I get the following error after + +``` +$query['init'] = ""SJ"" + +``` + +error + +``` +Cannot index into a null array. +At line:9 char:1 ++ $query['init'] = ""SJ"" ++ ~~~~~~~~~~~~~~~~~~~~~~ + + CategoryInfo : InvalidOperation: (:) [], RuntimeException + + FullyQualifiedErrorId : NullArray + +``` + +Any ideas as to why? I only have the MongoDB's standard index, which is on ""\_id"", nothing else. My powershell script still works but I'm curious as to why I get that error. + +**[UPDATE Part 2]** Thanks to @arco444, I no longer get error in part 2. Here's my revised code: + +``` +$query = @{'init' = ""SJ""} +$collection.FindOne([MongoDB.Driver.QueryDocument]$query) + +``` + +But I actually need help with part 1 - which is to display only the company tickers for a particular init. Any ideas on that one? + +**[ANSWER Part 1]** Thanks again to @arco444 for directing me to the right path. After some tinkering around, I figured out what I missed. Here's my updated code: + +``` +$databaseName = ""CompanyInfo"" +$collectionName = ""comps"" +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://localhost:27017"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query = new-object MongoDB.Driver.QueryDocument(""init"",""SJ"") /// Updated +$results = $collection.FindOne($query) +foreach ($result in $results[""companies""]) { /// Updated + write-host $result[""ticker""] /// Updated +} + +```",2014/08/27,"['https://Stackoverflow.com/questions/25530172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979127/']","From reading the MongoDB [documentation](http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/#findone-and-findoneas-methods), it looks like you need to initialise the query object properly first. Try this: + +``` +$query = new-object MongoDB.Driver.QueryDocument(""init"",""SJ"") +$results = $collection.FindOne($query) + +```","here is what allowed me to get an object that i could operate on: + +``` + $results = @() +foreach($item in $collection.Find($query)) +{ + $props = @{} + $item | foreach { $props[ $_.name ] = $_.value } + $pso = [pscustomobject]$props + $results += $pso +} + +``` + +full code: + +``` + $mongoDbDriverPath = 'D:\mongo\driver\' +$mongoServer = 'myserver:27000' + +Add-Type -Path ""$($mongoDbDriverPath)MongoDB.Bson.dll"" +Add-Type -Path ""$($mongoDbDriverPath)MongoDB.Driver.dll"" + +$databaseName = 'Tickets' +$collectionName = 'MongoUserTicket' + +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://$mongoServer"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query = new-object Mongodb.driver.querydocument('Id','5') +$query2 = New-object Mongodb.driver.querydocument('Type','User') +$results = @() +foreach($item in $collection.Find($query)) +{ + $props = @{} + $item | foreach { $props[ $_.name ] = $_.value } + $pso = [pscustomobject]$props + $results += $pso +} +$results + +```" +25530172,"1) Here's my schema: + +``` +{ + ""_id"" : ObjectId(""53f4db1d968166157c2d57ce""), + ""init"" : ""SJ"", + ""name"" : ""Steve Jobs"", + ""companies"" : [ + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57cf""), + ""ticker"" : ""AAPL"", + ""compname"" : ""Apple"" + }, + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57d0""), + ""ticker"" : ""MSFT"", + ""compname"" : ""Microsoft"" + }, + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57d1""), + ""ticker"" : ""ABC"", + ""compname"" : ""iTunes"" + }, + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57d2""), + ""ticker"" : ""DEF"", + ""compname"" : ""iPad Mini"" + } + ] +} + +``` + +I'm trying to get a list of compnames, using Powershell & MongoDB. Here's what I have so far: + +``` +$databaseName = ""CompanyInfo"" +$collectionName = ""comps"" +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://localhost:27017"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query['init'] = ""SJ"" +$results = $collection.FindOne($query) +foreach ($result in $results) { + write-host $result[""companies.ticker""] /// Doesn't show me any records +} + +``` + +This doesn't show me any records. How can I display companies.ticker info where init = ""SJ""? + +2) Btw, I get the following error after + +``` +$query['init'] = ""SJ"" + +``` + +error + +``` +Cannot index into a null array. +At line:9 char:1 ++ $query['init'] = ""SJ"" ++ ~~~~~~~~~~~~~~~~~~~~~~ + + CategoryInfo : InvalidOperation: (:) [], RuntimeException + + FullyQualifiedErrorId : NullArray + +``` + +Any ideas as to why? I only have the MongoDB's standard index, which is on ""\_id"", nothing else. My powershell script still works but I'm curious as to why I get that error. + +**[UPDATE Part 2]** Thanks to @arco444, I no longer get error in part 2. Here's my revised code: + +``` +$query = @{'init' = ""SJ""} +$collection.FindOne([MongoDB.Driver.QueryDocument]$query) + +``` + +But I actually need help with part 1 - which is to display only the company tickers for a particular init. Any ideas on that one? + +**[ANSWER Part 1]** Thanks again to @arco444 for directing me to the right path. After some tinkering around, I figured out what I missed. Here's my updated code: + +``` +$databaseName = ""CompanyInfo"" +$collectionName = ""comps"" +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://localhost:27017"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query = new-object MongoDB.Driver.QueryDocument(""init"",""SJ"") /// Updated +$results = $collection.FindOne($query) +foreach ($result in $results[""companies""]) { /// Updated + write-host $result[""ticker""] /// Updated +} + +```",2014/08/27,"['https://Stackoverflow.com/questions/25530172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979127/']","Here's my updated code: + +``` +$databaseName = ""CompanyInfo"" +$collectionName = ""comps"" +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://localhost:27017"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query = new-object MongoDB.Driver.QueryDocument(""init"",""SJ"") /// Updated +$results = $collection.FindOne($query) +foreach ($result in $results[""companies""]) { /// Updated + write-host $result[""ticker""] /// Updated +} + +```","So when I use your query procedure with + +``` +$mongoDbDriverPath = 'D:\mongo\driver\' +$mongoServer = 'myserver:27000' + +Add-Type -Path ""$($mongoDbDriverPath)MongoDB.Bson.dll"" +Add-Type -Path ""$($mongoDbDriverPath)MongoDB.Driver.dll"" + +$databaseName = 'Tickets' +$collectionName = 'MongoUserTicket' + +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://$mongoServer"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query = new-object Mongodb.driver.querydocument('Id','5') +$query2 = New-object Mongodb.driver.querydocument('Type','User') +$results = @() +foreach($item in $collection.Find($query)) +{ + $results += $item +} + +``` + +I get unexpected results for the query: +When piping to Get member for results I get this: + +``` + TypeName: MongoDB.Bson.BsonElement + +Name MemberType Definition +---- ---------- ---------- +Clone Method MongoDB.Bson.BsonElement Clone() +CompareTo Method int CompareTo(MongoDB.Bson.BsonElement other), int IComparable[BsonElement].CompareTo(MongoDB.Bson.BsonElement other) +DeepClone Method MongoDB.Bson.BsonElement DeepClone() +Equals Method bool Equals(MongoDB.Bson.BsonElement rhs), bool Equals(System.Object obj), bool IEquatable[BsonElement].Equals(MongoDB.Bson.BsonElement other) +GetHashCode Method int GetHashCode() +GetType Method type GetType() +ToString Method string ToString() +Name Property string Name {get;} +Value Property MongoDB.Bson.BsonValue Value {get;set;} + +``` + +When entering $results on the shell prompt I get the data I expect: + +``` +$results + +Name Value +---- ----- +Id 5 +AccessToken +CreatedOn 2013-09-27T22:05:52.246Z +TokenExpiration 2013-09-27T22:20:52.246Z +RefreshTokenExpiration 2013-09-28T22:05:52.246Z +ProfileToken BsonNull +Type User +Id 5 +AccessToken +CreatedOn 2013-09-27T23:42:28.492Z +TokenExpiration 2013-09-27T23:57:28.492Z +RefreshTokenExpiration 2013-09-28T22:06:04.071Z +ProfileToken BsonNull +Type User + +```" +25530172,"1) Here's my schema: + +``` +{ + ""_id"" : ObjectId(""53f4db1d968166157c2d57ce""), + ""init"" : ""SJ"", + ""name"" : ""Steve Jobs"", + ""companies"" : [ + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57cf""), + ""ticker"" : ""AAPL"", + ""compname"" : ""Apple"" + }, + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57d0""), + ""ticker"" : ""MSFT"", + ""compname"" : ""Microsoft"" + }, + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57d1""), + ""ticker"" : ""ABC"", + ""compname"" : ""iTunes"" + }, + { + ""_id"" : ObjectId(""53f4db1d968166157c2d57d2""), + ""ticker"" : ""DEF"", + ""compname"" : ""iPad Mini"" + } + ] +} + +``` + +I'm trying to get a list of compnames, using Powershell & MongoDB. Here's what I have so far: + +``` +$databaseName = ""CompanyInfo"" +$collectionName = ""comps"" +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://localhost:27017"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query['init'] = ""SJ"" +$results = $collection.FindOne($query) +foreach ($result in $results) { + write-host $result[""companies.ticker""] /// Doesn't show me any records +} + +``` + +This doesn't show me any records. How can I display companies.ticker info where init = ""SJ""? + +2) Btw, I get the following error after + +``` +$query['init'] = ""SJ"" + +``` + +error + +``` +Cannot index into a null array. +At line:9 char:1 ++ $query['init'] = ""SJ"" ++ ~~~~~~~~~~~~~~~~~~~~~~ + + CategoryInfo : InvalidOperation: (:) [], RuntimeException + + FullyQualifiedErrorId : NullArray + +``` + +Any ideas as to why? I only have the MongoDB's standard index, which is on ""\_id"", nothing else. My powershell script still works but I'm curious as to why I get that error. + +**[UPDATE Part 2]** Thanks to @arco444, I no longer get error in part 2. Here's my revised code: + +``` +$query = @{'init' = ""SJ""} +$collection.FindOne([MongoDB.Driver.QueryDocument]$query) + +``` + +But I actually need help with part 1 - which is to display only the company tickers for a particular init. Any ideas on that one? + +**[ANSWER Part 1]** Thanks again to @arco444 for directing me to the right path. After some tinkering around, I figured out what I missed. Here's my updated code: + +``` +$databaseName = ""CompanyInfo"" +$collectionName = ""comps"" +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://localhost:27017"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query = new-object MongoDB.Driver.QueryDocument(""init"",""SJ"") /// Updated +$results = $collection.FindOne($query) +foreach ($result in $results[""companies""]) { /// Updated + write-host $result[""ticker""] /// Updated +} + +```",2014/08/27,"['https://Stackoverflow.com/questions/25530172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979127/']","Here's my updated code: + +``` +$databaseName = ""CompanyInfo"" +$collectionName = ""comps"" +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://localhost:27017"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query = new-object MongoDB.Driver.QueryDocument(""init"",""SJ"") /// Updated +$results = $collection.FindOne($query) +foreach ($result in $results[""companies""]) { /// Updated + write-host $result[""ticker""] /// Updated +} + +```","here is what allowed me to get an object that i could operate on: + +``` + $results = @() +foreach($item in $collection.Find($query)) +{ + $props = @{} + $item | foreach { $props[ $_.name ] = $_.value } + $pso = [pscustomobject]$props + $results += $pso +} + +``` + +full code: + +``` + $mongoDbDriverPath = 'D:\mongo\driver\' +$mongoServer = 'myserver:27000' + +Add-Type -Path ""$($mongoDbDriverPath)MongoDB.Bson.dll"" +Add-Type -Path ""$($mongoDbDriverPath)MongoDB.Driver.dll"" + +$databaseName = 'Tickets' +$collectionName = 'MongoUserTicket' + +$client = New-Object -TypeName MongoDB.Driver.MongoClient -ArgumentList ""mongodb://$mongoServer"" +$server = $client.GetServer() +$database = $server.GetDatabase($databaseName) +$collection = $database.GetCollection($collectionName) + +$query = new-object Mongodb.driver.querydocument('Id','5') +$query2 = New-object Mongodb.driver.querydocument('Type','User') +$results = @() +foreach($item in $collection.Find($query)) +{ + $props = @{} + $item | foreach { $props[ $_.name ] = $_.value } + $pso = [pscustomobject]$props + $results += $pso +} +$results + +```" +1748356,"I have some application, which has ability to update itself. Its downloads the jar file from the net, and then tries to replace used jar to run this application by downloaded one. +But I cannot to do that, because the file is locked by windows, because application is still running. + +Does anybody know some workaround of that?",2009/11/17,"['https://Stackoverflow.com/questions/1748356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212822/']","One of the popular solutions for this is to run your updater as a separate program. Have you ever noticed that Firefox has to restart when it is updated? Well that is because a separate process (updater.exe) is updating the files, then starting Firefox again. + +You can try this approach. The only obstacle I see in the way is trying to automate the MAIN program to close itself. The only portable way to do this (in my head) is for the main application to wait for a kill signal via a local socket, and the updater can send the command through local networking. One more thing you have to consider is that the updater has to run in a separate java process. If your main program just creates a new Updater object, the Updater will co-exist with the main program's JVM, which brings you back to square one.","I think the correct thing to do here is to **restart** the application. Event if you could update the jar at *runtime*, all sort of errors might occur after because of class versions, different classes, different implementations, etc." +1748356,"I have some application, which has ability to update itself. Its downloads the jar file from the net, and then tries to replace used jar to run this application by downloaded one. +But I cannot to do that, because the file is locked by windows, because application is still running. + +Does anybody know some workaround of that?",2009/11/17,"['https://Stackoverflow.com/questions/1748356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212822/']","I think the correct thing to do here is to **restart** the application. Event if you could update the jar at *runtime*, all sort of errors might occur after because of class versions, different classes, different implementations, etc.","Typical way to do this is to write a separate updater which will be invoked by your main program when it sees an update. At this time your main program can start the updater in a new process and exit. You updater can wait for main program to exit, download and copy the updated files and restart your main program" +1748356,"I have some application, which has ability to update itself. Its downloads the jar file from the net, and then tries to replace used jar to run this application by downloaded one. +But I cannot to do that, because the file is locked by windows, because application is still running. + +Does anybody know some workaround of that?",2009/11/17,"['https://Stackoverflow.com/questions/1748356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212822/']","One of the popular solutions for this is to run your updater as a separate program. Have you ever noticed that Firefox has to restart when it is updated? Well that is because a separate process (updater.exe) is updating the files, then starting Firefox again. + +You can try this approach. The only obstacle I see in the way is trying to automate the MAIN program to close itself. The only portable way to do this (in my head) is for the main application to wait for a kill signal via a local socket, and the updater can send the command through local networking. One more thing you have to consider is that the updater has to run in a separate java process. If your main program just creates a new Updater object, the Updater will co-exist with the main program's JVM, which brings you back to square one.","Typical way to do this is to write a separate updater which will be invoked by your main program when it sees an update. At this time your main program can start the updater in a new process and exit. You updater can wait for main program to exit, download and copy the updated files and restart your main program" +1748356,"I have some application, which has ability to update itself. Its downloads the jar file from the net, and then tries to replace used jar to run this application by downloaded one. +But I cannot to do that, because the file is locked by windows, because application is still running. + +Does anybody know some workaround of that?",2009/11/17,"['https://Stackoverflow.com/questions/1748356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212822/']","One of the popular solutions for this is to run your updater as a separate program. Have you ever noticed that Firefox has to restart when it is updated? Well that is because a separate process (updater.exe) is updating the files, then starting Firefox again. + +You can try this approach. The only obstacle I see in the way is trying to automate the MAIN program to close itself. The only portable way to do this (in my head) is for the main application to wait for a kill signal via a local socket, and the updater can send the command through local networking. One more thing you have to consider is that the updater has to run in a separate java process. If your main program just creates a new Updater object, the Updater will co-exist with the main program's JVM, which brings you back to square one.","That's a problem **already solved** by OSGi. + +The real problem is not to load a new jar version. This could be done with your own classloader that releases the file lock. The real problem is how to [handle instances of different versions of the same class](http://en.wikipedia.org/wiki/Classloader#JAR_hell). + +Restart does omit these problem. If you really need different jar versions in one application use OSGi." +1748356,"I have some application, which has ability to update itself. Its downloads the jar file from the net, and then tries to replace used jar to run this application by downloaded one. +But I cannot to do that, because the file is locked by windows, because application is still running. + +Does anybody know some workaround of that?",2009/11/17,"['https://Stackoverflow.com/questions/1748356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212822/']","That's a problem **already solved** by OSGi. + +The real problem is not to load a new jar version. This could be done with your own classloader that releases the file lock. The real problem is how to [handle instances of different versions of the same class](http://en.wikipedia.org/wiki/Classloader#JAR_hell). + +Restart does omit these problem. If you really need different jar versions in one application use OSGi.","Typical way to do this is to write a separate updater which will be invoked by your main program when it sees an update. At this time your main program can start the updater in a new process and exit. You updater can wait for main program to exit, download and copy the updated files and restart your main program" +12302290,"I have a log file on server called `writelog` which is about `2GB`. + +I want to delete first `100,000` lines from the file. I could open the file and delete those lines but because of the file size it takes me forever to download it. + +So, is it possible to do this from Linux terminal? If yes how?",2012/09/06,"['https://Stackoverflow.com/questions/12302290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1143828/']","If you want to clear out the *whole file* a quick way is + +`cat /dev/null > writelog` + +See also [this thread on unix.com](http://www.unix.com/unix-dummies-questions-answers/150082-create-empty-file-overwrite-file-differences-between-cat-echo-etc.html).","If you are running a Linux server, you can use `ssh`: + +``` +ssh username@mydomain.com sed -i '1,100000d' /path/to/logfile + +```" +12302290,"I have a log file on server called `writelog` which is about `2GB`. + +I want to delete first `100,000` lines from the file. I could open the file and delete those lines but because of the file size it takes me forever to download it. + +So, is it possible to do this from Linux terminal? If yes how?",2012/09/06,"['https://Stackoverflow.com/questions/12302290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1143828/']","If you want to clear out the *whole file* a quick way is + +`cat /dev/null > writelog` + +See also [this thread on unix.com](http://www.unix.com/unix-dummies-questions-answers/150082-create-empty-file-overwrite-file-differences-between-cat-echo-etc.html).","It might be better to keep the last 1000 lines: + +``` +mv writelog writelog.bak +tail -1000 writelog.bak > writelog + +``` + +And you should enable `logrotate` ([manual](http://linux.die.net/man/8/logrotate)) for the file. The system will then make sure the file doesn't grow out of proportions." +9293124,"``` + Qt :: WindowFlags flags = 0; + + // Makes the Pomodoro stay on the top of all windows. + flags |= Qt :: WindowStaysOnTopHint; + + // Removes minimize, maximize, and close buttons. + flags |= Qt :: WindowTitleHint | Qt :: CustomizeWindowHint; + + window->setWindowFlags (flags); + window->setWindowTitle (""Failing to plan is planning to fail""); + +``` + +This removes minimize, maximize, and close buttons. The default menu on the left is still there. How to get rid of that? + +I want the title bar to be there, but just want the menu to be removed. + +Default menu contains: Minimize, Maximize, Move etc options. + +EDIT 1: +------- + +timer.cpp + +``` +#include +#include +#include ""timer.h"" + +#include +#include +#include +#include +int main(int argc, char *argv[]) +{ + QApplication app (argc, argv); + + // The window on which we will place the timer. + QMainWindow *window = new QMainWindow(); + QWidget *centralWidget = new QWidget (window); + + /* Button widget */ + // Displays a button on the main window. + QPushButton *startButton = new QPushButton(""Start"", window); + // Setting the size of the button widget. + startButton->setFixedSize (245, 25); + + /* Text box */ + // Displays a time interval list on the main window. + QListWidget *timeIntervalList = new QListWidget (window); + timeIntervalList->setFixedSize (30, 145); + + QStringList timeIntervals; + timeIntervals << ""1"" << ""20"" << ""30"" << ""40""; + timeIntervalList->addItems (timeIntervals); + + /* LCD widget */ + // Start Counting down from 25 minutes + lcdDisplay *objLcdDisplay = new lcdDisplay (centralWidget); + // Setting the size of the LCD widget. + objLcdDisplay->setFixedSize (245, 140); + + // The clicked time interval should be returned from the list to the timer. + QObject :: connect (timeIntervalList, SIGNAL (itemClicked (QListWidgetItem *)), objLcdDisplay, SLOT (receiveTimeInterval (QListWidgetItem *))); + + // The timer should start and emit signals when the start button is clicked. + QObject :: connect (startButton, SIGNAL (clicked ()), objLcdDisplay, SLOT (setTimerConnect ())); + + ************************************************************************* + Qt :: WindowFlags flags = 0; + // Makes the Pomodoro stay on the top of all windows. + flags |= Qt :: Window | Qt :: WindowStaysOnTopHint; + // Removes minimize, maximize, and close buttons. + flags |= Qt :: WindowTitleHint | Qt :: CustomizeWindowHint; + window->setWindowFlags (flags); + ************************************************************************* + window->setWindowTitle (""Failing to plan is planning to fail""); + + QGridLayout *layout = new QGridLayout(); + centralWidget->setLayout(layout); + + //Add Items to QGridLayout Here + //Row and Column counts are set Automatically + layout->addWidget (objLcdDisplay, 0, 1); + layout->addWidget (startButton, 1, 1); + layout->addWidget (timeIntervalList, 0, 0); + + window->setCentralWidget (centralWidget); + window->show(); + + return app.exec(); +} + +``` + +Timer.h + +``` +#ifndef LCDNUMBER_H +#define LCDNUMBER_H + +#include +#include +#include +#include +#include +#include + +class lcdDisplay : public QLCDNumber +{ + Q_OBJECT + + public: + // The QTimer class provides repetitive and single-shot timers. + QTimer* objTimer; + // The QTime class provides clock time functions. + QTime* objTime; + + public: + lcdDisplay (QWidget *parentWidget) + { + objTimer = new QTimer (); + // Setting our own time with the specified hours, minutes, and seconds. + objTime = new QTime (0, 0, 0); + + setParent (parentWidget); + }; + + ~ lcdDisplay () {}; + + public slots: + // This slot is called after the timer timeouts (1 second). + void setDisplay () + { + // TODO + objTime->setHMS (0, objTime->addSecs (-1).minute (), objTime->addSecs (-1).second ()); + display (objTime->toString ()); + + if ((objTime->minute () == 0) && (objTime->second () == 0)) + { + objTimer->stop (); + QMessageBox msgBox; + msgBox.setWindowTitle (""Pomodoro""); + msgBox.setText (""Time's up.""); + msgBox.setWindowModality(Qt::ApplicationModal); + msgBox.exec(); + } + }; + + void receiveTimeInterval (QListWidgetItem *item) + { + QString h = item->text(); + objTime->setHMS (0, h.toUInt(), 0); + } + + void setTimerConnect () + { + // connect (objectA, signalAFromObjectA, objectB, slotAFromObjectB) + // timeout (): This signal is emitted when the timer times out. The time out period can be specified with `start (int milliseconds)` function. + QObject :: connect (objTimer, SIGNAL (timeout ()), this, SLOT (setDisplay ())); + + // 1 second has 1000 milliseconds. + // start (int milliseconds): Starts the timer with a timeout interval of specified milliseconds. this means that after 1 second the timer will emit a signal. TODO placement + objTimer->start (1000); + } +}; +#endif + +```",2012/02/15,"['https://Stackoverflow.com/questions/9293124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/462608/']","This is working for me: + +``` +Qt::Window | Qt::WindowTitleHint | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint + +``` + +![Screen shot](https://i.stack.imgur.com/zCRxF.png) + +Sometimes you have to specify these in the constructor of the window for them to take effect. If you assign them later (`setWindowFlags`), some of the settings may not apply.","I'm currently at work without an Qt environment, so I could not test it. Would you please try this? + +``` +Qt::WindowFlags flags = 0; + +// Makes the Pomodoro stay on the top of all windows. +flags |= Qt :: WindowStaysOnTopHint; + +// Removes minimize, maximize, and close buttons. +flags |= Qt :: WindowTitleHint | Qt :: CustomizeWindowHint; + +window->setWindowFlags (flags & ~Qt::WindowSystemMenuHint); +window->setWindowTitle (""Failing to plan is planning to fail""); + +```" +9293124,"``` + Qt :: WindowFlags flags = 0; + + // Makes the Pomodoro stay on the top of all windows. + flags |= Qt :: WindowStaysOnTopHint; + + // Removes minimize, maximize, and close buttons. + flags |= Qt :: WindowTitleHint | Qt :: CustomizeWindowHint; + + window->setWindowFlags (flags); + window->setWindowTitle (""Failing to plan is planning to fail""); + +``` + +This removes minimize, maximize, and close buttons. The default menu on the left is still there. How to get rid of that? + +I want the title bar to be there, but just want the menu to be removed. + +Default menu contains: Minimize, Maximize, Move etc options. + +EDIT 1: +------- + +timer.cpp + +``` +#include +#include +#include ""timer.h"" + +#include +#include +#include +#include +int main(int argc, char *argv[]) +{ + QApplication app (argc, argv); + + // The window on which we will place the timer. + QMainWindow *window = new QMainWindow(); + QWidget *centralWidget = new QWidget (window); + + /* Button widget */ + // Displays a button on the main window. + QPushButton *startButton = new QPushButton(""Start"", window); + // Setting the size of the button widget. + startButton->setFixedSize (245, 25); + + /* Text box */ + // Displays a time interval list on the main window. + QListWidget *timeIntervalList = new QListWidget (window); + timeIntervalList->setFixedSize (30, 145); + + QStringList timeIntervals; + timeIntervals << ""1"" << ""20"" << ""30"" << ""40""; + timeIntervalList->addItems (timeIntervals); + + /* LCD widget */ + // Start Counting down from 25 minutes + lcdDisplay *objLcdDisplay = new lcdDisplay (centralWidget); + // Setting the size of the LCD widget. + objLcdDisplay->setFixedSize (245, 140); + + // The clicked time interval should be returned from the list to the timer. + QObject :: connect (timeIntervalList, SIGNAL (itemClicked (QListWidgetItem *)), objLcdDisplay, SLOT (receiveTimeInterval (QListWidgetItem *))); + + // The timer should start and emit signals when the start button is clicked. + QObject :: connect (startButton, SIGNAL (clicked ()), objLcdDisplay, SLOT (setTimerConnect ())); + + ************************************************************************* + Qt :: WindowFlags flags = 0; + // Makes the Pomodoro stay on the top of all windows. + flags |= Qt :: Window | Qt :: WindowStaysOnTopHint; + // Removes minimize, maximize, and close buttons. + flags |= Qt :: WindowTitleHint | Qt :: CustomizeWindowHint; + window->setWindowFlags (flags); + ************************************************************************* + window->setWindowTitle (""Failing to plan is planning to fail""); + + QGridLayout *layout = new QGridLayout(); + centralWidget->setLayout(layout); + + //Add Items to QGridLayout Here + //Row and Column counts are set Automatically + layout->addWidget (objLcdDisplay, 0, 1); + layout->addWidget (startButton, 1, 1); + layout->addWidget (timeIntervalList, 0, 0); + + window->setCentralWidget (centralWidget); + window->show(); + + return app.exec(); +} + +``` + +Timer.h + +``` +#ifndef LCDNUMBER_H +#define LCDNUMBER_H + +#include +#include +#include +#include +#include +#include + +class lcdDisplay : public QLCDNumber +{ + Q_OBJECT + + public: + // The QTimer class provides repetitive and single-shot timers. + QTimer* objTimer; + // The QTime class provides clock time functions. + QTime* objTime; + + public: + lcdDisplay (QWidget *parentWidget) + { + objTimer = new QTimer (); + // Setting our own time with the specified hours, minutes, and seconds. + objTime = new QTime (0, 0, 0); + + setParent (parentWidget); + }; + + ~ lcdDisplay () {}; + + public slots: + // This slot is called after the timer timeouts (1 second). + void setDisplay () + { + // TODO + objTime->setHMS (0, objTime->addSecs (-1).minute (), objTime->addSecs (-1).second ()); + display (objTime->toString ()); + + if ((objTime->minute () == 0) && (objTime->second () == 0)) + { + objTimer->stop (); + QMessageBox msgBox; + msgBox.setWindowTitle (""Pomodoro""); + msgBox.setText (""Time's up.""); + msgBox.setWindowModality(Qt::ApplicationModal); + msgBox.exec(); + } + }; + + void receiveTimeInterval (QListWidgetItem *item) + { + QString h = item->text(); + objTime->setHMS (0, h.toUInt(), 0); + } + + void setTimerConnect () + { + // connect (objectA, signalAFromObjectA, objectB, slotAFromObjectB) + // timeout (): This signal is emitted when the timer times out. The time out period can be specified with `start (int milliseconds)` function. + QObject :: connect (objTimer, SIGNAL (timeout ()), this, SLOT (setDisplay ())); + + // 1 second has 1000 milliseconds. + // start (int milliseconds): Starts the timer with a timeout interval of specified milliseconds. this means that after 1 second the timer will emit a signal. TODO placement + objTimer->start (1000); + } +}; +#endif + +```",2012/02/15,"['https://Stackoverflow.com/questions/9293124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/462608/']","This is working for me: + +``` +Qt::Window | Qt::WindowTitleHint | Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint + +``` + +![Screen shot](https://i.stack.imgur.com/zCRxF.png) + +Sometimes you have to specify these in the constructor of the window for them to take effect. If you assign them later (`setWindowFlags`), some of the settings may not apply.","Try to start by setting Qt::Dialog + +``` +setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowStaysOnTopHint); + +```" +10581112,"What would be the best way to create a C# Web Application that allows the user to browse for an image and then display it? +An equivalent of Picturebox in windows applications, sort of + +Ideally the user should be able to click on Browse, choose the picture and see it in the browser itself + +Thanks",2012/05/14,"['https://Stackoverflow.com/questions/10581112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1211929/']","There are all ready some image-browser for asp.net including source code. + +Some of them + + + +","For this, the user needs to choose an image which will be uploaded to the server, and then rendered in the HTML or recovered using AJAX. The problem is that you can't get rid of the send/receive, and it can get slow. + +You can use a `FileUpload` or any other component that allows to upload files directly or via AJAX (look at [AjaxFileUpload](http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AjaxFileUpload/AjaxFileUpload.aspx) AjaxControlToolkit for this). + +Then you need to add an `` to your page, through a full postback or using any other means (like jQuery.Ajax)." +30796314,"Am new to Angularjs, any one can help me about this +infact my array is like this + +``` +array = [{""loc_name"":""pronto network office"",""address"":""3rd floor, kalyani motors"",""ap"":[]}], + +``` + +but when i use at dynamically its converted like this + +``` +["" {\""loc_name\"":\""pronto="""" network="""" office\"",\""address\"":\""3rd="""" floor,="""" kalyani="""" motors\"",\""ap\"":[]}""] + +``` + +finally i want like this + +``` +
      +
    • +
      + +
      +
      +

      {{ loc.loc_name }}

      +

      {{ loc.address }}

      +
      +
    • +
    • +
        +
      • +
        + +
        +
        +

        {{ ap.mac_id }}

        +

        +
        +
      • +
      +
    • +
    + +```",2015/06/12,"['https://Stackoverflow.com/questions/30796314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/748447/']","Your response should not contain `""` at starting of object inside array right after `[` and just before `]` need to remove `""` like it should be like `[{\""loc_name\"":\""pronto="""" network="""" office\"",\""address\"":\""3rd="""" floor,="""" kalyani="""" motors\"",\""ap\"":[]}]` + +Then place it in your scope variable `$scope.locations = [{\""loc_name\"":\""pronto="""" network="""" office\"",\""address\"":\""3rd="""" floor,="""" kalyani="""" motors\"",\""ap\"":[]}]` & refer that scope variable on html then you need to worry about to convert it to double quote`""` to '`' single quote. + +``` +
      + ... +
        + +```","You can just use single quotes instead of `""`: + +``` +
          + +
        + +``` + +You can also omit quotes around keys: string inside `ngRepeat` doesn't have to comply string JSON notation with quoted keys. Of course you can still use `'` for keys as well." +30796314,"Am new to Angularjs, any one can help me about this +infact my array is like this + +``` +array = [{""loc_name"":""pronto network office"",""address"":""3rd floor, kalyani motors"",""ap"":[]}], + +``` + +but when i use at dynamically its converted like this + +``` +["" {\""loc_name\"":\""pronto="""" network="""" office\"",\""address\"":\""3rd="""" floor,="""" kalyani="""" motors\"",\""ap\"":[]}""] + +``` + +finally i want like this + +``` +
          +
        • +
          + +
          +
          +

          {{ loc.loc_name }}

          +

          {{ loc.address }}

          +
          +
        • +
        • +
            +
          • +
            + +
            +
            +

            {{ ap.mac_id }}

            +

            +
            +
          • +
          +
        • +
        + +```",2015/06/12,"['https://Stackoverflow.com/questions/30796314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/748447/']","Your response should not contain `""` at starting of object inside array right after `[` and just before `]` need to remove `""` like it should be like `[{\""loc_name\"":\""pronto="""" network="""" office\"",\""address\"":\""3rd="""" floor,="""" kalyani="""" motors\"",\""ap\"":[]}]` + +Then place it in your scope variable `$scope.locations = [{\""loc_name\"":\""pronto="""" network="""" office\"",\""address\"":\""3rd="""" floor,="""" kalyani="""" motors\"",\""ap\"":[]}]` & refer that scope variable on html then you need to worry about to convert it to double quote`""` to '`' single quote. + +``` +
          + ... +
            + +```","Do you really want your array inside your html? Otherwise to make it simple and recommended way of doing is to move it to your controller in the JS. I have created a sample in for you" +55740242,Are there any compiler independent flags that can be set? I'd like to be able to set single variable to e.g. `OPTIMIZE_MOST` and get `-O3` on gcc and `/O2` in MS C++ compiler. Is there something I can use or should flags be set for each compiler separately?,2019/04/18,"['https://Stackoverflow.com/questions/55740242', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3826362/']","Simply spoken: No, there is no flag to directly set the optimization level independently for every compiler. + +However, CMake provides so called [build types](https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html). Those are independent of the compiler in use and each comes with a predefined selection of flags, one of which is the optimization flag. + +Available build types are + +* `Debug` +* `Release` +* `RelWithDebInfo` +* `MinSizeRel` + +For a comprehensive explanation, I refer to [this answer](https://stackoverflow.com/a/24767451/579698). It also provides some code that helps to identify the flags in question when included into the `CMakeLists.txt` file: + +``` +message(""CMAKE_C_FLAGS_DEBUG is ${CMAKE_C_FLAGS_DEBUG}"") +message(""CMAKE_C_FLAGS_RELEASE is ${CMAKE_C_FLAGS_RELEASE}"") +message(""CMAKE_C_FLAGS_RELWITHDEBINFO is ${CMAKE_C_FLAGS_RELWITHDEBINFO}"") +message(""CMAKE_C_FLAGS_MINSIZEREL is ${CMAKE_C_FLAGS_MINSIZEREL}"") + +message(""CMAKE_CXX_FLAGS_DEBUG is ${CMAKE_CXX_FLAGS_DEBUG}"") +message(""CMAKE_CXX_FLAGS_RELEASE is ${CMAKE_CXX_FLAGS_RELEASE}"") +message(""CMAKE_CXX_FLAGS_RELWITHDEBINFO is ${CMAKE_CXX_FLAGS_RELWITHDEBINFO}"") +message(""CMAKE_CXX_FLAGS_MINSIZEREL is ${CMAKE_CXX_FLAGS_MINSIZEREL}"") + +```","To a degree. For some concepts, CMake has support for specifying them in a compiler-agnostic manner, usually by setting properties on the target in question. Unfortunately, there is no one location where all such possibilities would be listed. I went through the current [list of target properties](https://cmake.org/cmake/help/latest/manual/cmake-properties.7.html#properties-on-targets) and identified the following properties as ""absrtacting away build-tool option syntax"": + +* `COMPILE_PDB_NAME` +* `INCLUDE_DIRECTORIES` +* `INSTALL_RPATH` +* `INTERPROCEDURAL_OPTIMIZATION` +* `LINK_DIRECTORIES` +* `LINK_LIBRARIES` +* `PDB_NAME` +* `PDB_OUTPUT_DIRECTORY` +* (plus the properties for setting output name, path, etc.) + +There is apparently nothing for handling optimisation flags other than IPO. + +To the best of my knowledge, there is also no generic process for adding these — they are added to CMake as someone finds the need for them (and the time to implement them)." +20693377,"I have a sortable list of items (each with a draggable handle) and I'm trying to align some elements within each item: a title, link, and some descriptive text. The items are adjacent to a left-floated div (the ""handle"" you see on the left). Unfortunately, there is a large gap between the title and the link: + +![There's a gap between the title and the link](https://i.stack.imgur.com/IzgND.png) + +() + +Here's a mock-up I made in an image editing program that illustrates what I'm trying to achieve (no large gap between the title and the link): + +![Here's the ideal layout--without the gap](https://i.stack.imgur.com/gmmKJ.png) + +I know it has something to do with the `.handle` div which is floated left and has a specified width and height, but I can't quite figure it out. When I remove the `.handle`, everything lines up fine without the awkward gap. I'm sure it's a simple fix, but I'm struggling to find an answer. Any suggestions would be helpful. Thanks!",2013/12/19,"['https://Stackoverflow.com/questions/20693377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/557928/']","Try adding these properties to your existing classes: + +``` +.itemSubContainer { + overflow:hidden; +} +.handle { + margin-right:10px; +} + +``` + +To help clear your floated elemets, because your itemSubContainer class doesn't know about the containing elements because they are floated and taken out of the flow.","Try the [`Media Object`](http://getbootstrap.com/components/#media) implementation given in Bootstrap. It includes a left-floated element with multiple text elements on its right. + +``` +
            + + + +
            +

            Media heading

            + ... +
            +
            + +```" +20693377,"I have a sortable list of items (each with a draggable handle) and I'm trying to align some elements within each item: a title, link, and some descriptive text. The items are adjacent to a left-floated div (the ""handle"" you see on the left). Unfortunately, there is a large gap between the title and the link: + +![There's a gap between the title and the link](https://i.stack.imgur.com/IzgND.png) + +() + +Here's a mock-up I made in an image editing program that illustrates what I'm trying to achieve (no large gap between the title and the link): + +![Here's the ideal layout--without the gap](https://i.stack.imgur.com/gmmKJ.png) + +I know it has something to do with the `.handle` div which is floated left and has a specified width and height, but I can't quite figure it out. When I remove the `.handle`, everything lines up fine without the awkward gap. I'm sure it's a simple fix, but I'm struggling to find an answer. Any suggestions would be helpful. Thanks!",2013/12/19,"['https://Stackoverflow.com/questions/20693377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/557928/']","Try adding these properties to your existing classes: + +``` +.itemSubContainer { + overflow:hidden; +} +.handle { + margin-right:10px; +} + +``` + +To help clear your floated elemets, because your itemSubContainer class doesn't know about the containing elements because they are floated and taken out of the flow.","The problem is that `.row` itself is also floating left and each `.row` clears the float. Instead of floating `.handle`, use `position: absolute` so the handle doesn't interfere with the rest of the content. + +Note that there's also a 10px margin on `h4` that you may wish to adjust. + +![enter image description here](https://i.stack.imgur.com/e3FKw.png)" +60996959,"I have this command : + +``` +$ anbox session-manager --single-window --window-size=400,650 + +``` + +and i need to run it **frequently**, is there any way to avoid **rewriting** it every time I need it ?",2020/04/02,"['https://Stackoverflow.com/questions/60996959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10863605/']","You can set an alias like this, + +``` +alias sessmgr = ""anbox session-manager --single-window --window-size=400,650"" + +``` + +Later, you can directly use `sessmgr`.","There are several ways you can do this, the most common is probably [using an alias](https://www.tecmint.com/create-alias-in-linux/) + +A common alias is using 'll' for 'ls -al', one way you could do that is with the following command: + +`alias ll='ls-al'`" +60996959,"I have this command : + +``` +$ anbox session-manager --single-window --window-size=400,650 + +``` + +and i need to run it **frequently**, is there any way to avoid **rewriting** it every time I need it ?",2020/04/02,"['https://Stackoverflow.com/questions/60996959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10863605/']","For permanently use + +1. run this + +``` +echo 'alias customcommand=""anbox session-manager --single-window --window-size=400,650""' >> /home/$(USER)/.bashrc + +``` +2. open new terminal +3. now you can run `customcommand` and get that response","There are several ways you can do this, the most common is probably [using an alias](https://www.tecmint.com/create-alias-in-linux/) + +A common alias is using 'll' for 'ls -al', one way you could do that is with the following command: + +`alias ll='ls-al'`" +60996959,"I have this command : + +``` +$ anbox session-manager --single-window --window-size=400,650 + +``` + +and i need to run it **frequently**, is there any way to avoid **rewriting** it every time I need it ?",2020/04/02,"['https://Stackoverflow.com/questions/60996959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10863605/']","You can use the alias command, and if you want to make the change permanent you can append the alias command in your .bashrc file, so every time you launch a terminal you will have by default the defined alias that you set before in your .bashrc file. +e.g. +`alias ="""".` + +You can find more info regarding alias [here](https://en.wikipedia.org/wiki/Alias_(command))","There are several ways you can do this, the most common is probably [using an alias](https://www.tecmint.com/create-alias-in-linux/) + +A common alias is using 'll' for 'ls -al', one way you could do that is with the following command: + +`alias ll='ls-al'`" +60996959,"I have this command : + +``` +$ anbox session-manager --single-window --window-size=400,650 + +``` + +and i need to run it **frequently**, is there any way to avoid **rewriting** it every time I need it ?",2020/04/02,"['https://Stackoverflow.com/questions/60996959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10863605/']","For permanently use + +1. run this + +``` +echo 'alias customcommand=""anbox session-manager --single-window --window-size=400,650""' >> /home/$(USER)/.bashrc + +``` +2. open new terminal +3. now you can run `customcommand` and get that response","You can set an alias like this, + +``` +alias sessmgr = ""anbox session-manager --single-window --window-size=400,650"" + +``` + +Later, you can directly use `sessmgr`." +60996959,"I have this command : + +``` +$ anbox session-manager --single-window --window-size=400,650 + +``` + +and i need to run it **frequently**, is there any way to avoid **rewriting** it every time I need it ?",2020/04/02,"['https://Stackoverflow.com/questions/60996959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10863605/']","For permanently use + +1. run this + +``` +echo 'alias customcommand=""anbox session-manager --single-window --window-size=400,650""' >> /home/$(USER)/.bashrc + +``` +2. open new terminal +3. now you can run `customcommand` and get that response","You can use the alias command, and if you want to make the change permanent you can append the alias command in your .bashrc file, so every time you launch a terminal you will have by default the defined alias that you set before in your .bashrc file. +e.g. +`alias ="""".` + +You can find more info regarding alias [here](https://en.wikipedia.org/wiki/Alias_(command))" +58505500,"My code looks like this: + +``` +cIndex = (int)rand.Next(App.viewablePhrases.Count); +phrase = App.viewablePhrases[cIndex]; + +``` + +Infrequently it's giving me an error: + +``` +Application Specific Information: +*** Terminating app due to uncaught exception 'SIGABRT', reason: 'Index was out of range. Must be non-negative and less than the size of the collection. +Parameter name: index' + +Xamarin Exception Stack: +System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. +Parameter name: index + at System.Collections.Generic.List`1[T].get_Item (System.Int32 ) <0x10047bfc0 + 0x0007b> in <939d99b14d934342858948926287beba#d346c1f46aec0f7ce096300b9d7adc79>:0 + at CardsTabViewModel.Random () <0x10138a5d0 + 0x0013b> in <1a94c4e2e6ff49bab0334b2d6333fc29#d346c1f46aec0f7ce096300b9d7adc79>:0 + +``` + +Is there a way I could catch this exception to show more details?",2019/10/22,"['https://Stackoverflow.com/questions/58505500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1422604/']","> +> Is there a way I could catch this exception to show more details? +> +> +> + +Just put your code in try / catch block like this: + +``` +try +{ + cIndex = (int)rand.Next(App.viewablePhrases.Count); + phrase = App.viewablePhrases[cIndex]; +} +catch(System.ArgumentOutOfRangeException e) +{ + Console.WriteLine(""Exception information: {0}"", e); +} +catch(Exception e) +{ + Console.WriteLine(""Exception information: {0}"", e); +} + +``` + +Set a break point in catch block to see more information.",Index can be from 0 to Count-1. +38710913,"I'm learning Angular on Plural Sight and the first lesson gives an example of how to use the ng-app directive. + +Here's a link to the Plunker editor + + +``` + + + + + + + + + + +

            Hello Plunker!

            + {{ 843 /42 }} + + + +``` + +The example that was given uses the expression {{ 843 / 42 }} to demonstrate how angular would render the quotient on a webpage. + +I've copied the lesson script several times over and can't figure out what I'm doing wrong and why its rendering as text. + +This is my first post on stackoverflow, and I'm happy to join the community! + +Thanks Again. +Shamus",2016/08/02,"['https://Stackoverflow.com/questions/38710913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6665622/']","The method you are looking for is this + +**[`org.bouncycastle.util.encoders.Base64.encode(byte[] data)`](https://people.eecs.berkeley.edu/~jonah/bc/org/bouncycastle/util/encoders/Base64.html#encode(byte[]))** + +I'm not sure where you got the reference to `Base64.toBase64String`, but a quick search shows that is very close to a similar C# method.","I guess you will have to use the methoad as below and check if it compiles + +``` +Base64.getEncoder().encodeToString(cipher.doFinal(initiatorpassword.getBytes())) + +```" +19447314,"There in C# available any methods like serialize and unserialize in php? + +I need it for best way to transfer an array through network.",2013/10/18,"['https://Stackoverflow.com/questions/19447314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146533/']","``` +var countries = [""FR"", ""IT"", ""DE"", ""AU"", ""RU""]; + +$('div').hide(); + +$('select').change(function () { + if ($.inArray(this.value, countries) >= 0) { + $('div').show(); + } else { + $('div').hide(); + } +}); + +``` + +[**FIDDLE**](http://jsfiddle.net/qYnKK/1/)","Try this, + +``` +var countries = [""FR"", ""IT"", ""DE"", ""AU"", ""RU""]; +$('#myitems').hide(); +$('#country').on('change', function () { + if ($.inArray($(this).val(), countries)!=-1) { + $('#myitems').show(); + } else { + $('#myitems').hide(); + } +}); + +``` + +[Demo](http://jsfiddle.net/rohankumar1524/sVXJF/)" +19447314,"There in C# available any methods like serialize and unserialize in php? + +I need it for best way to transfer an array through network.",2013/10/18,"['https://Stackoverflow.com/questions/19447314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146533/']","``` +var countries = [""FR"", ""IT"", ""DE"", ""AU"", ""RU""]; + +$('div').hide(); + +$('select').change(function () { + if ($.inArray(this.value, countries) >= 0) { + $('div').show(); + } else { + $('div').hide(); + } +}); + +``` + +[**FIDDLE**](http://jsfiddle.net/qYnKK/1/)","[JSFIDDLE](http://jsfiddle.net/zDuq5/) + +``` +var countries=[""FR"",""IT"",""DE"", ""AU"", ""RU""]; +$(""#country"").change(function(){ + var selectedVal = $(this).val(); + if(countries.indexOf(selectedVal) != -1){ + + $(""#divToShow"").show(); + } + else { + $(""#divToShow"").hide(); + } +}); + +```" +19447314,"There in C# available any methods like serialize and unserialize in php? + +I need it for best way to transfer an array through network.",2013/10/18,"['https://Stackoverflow.com/questions/19447314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146533/']","``` +var countries = [""FR"", ""IT"", ""DE"", ""AU"", ""RU""]; + +$('div').hide(); + +$('select').change(function () { + if ($.inArray(this.value, countries) >= 0) { + $('div').show(); + } else { + $('div').hide(); + } +}); + +``` + +[**FIDDLE**](http://jsfiddle.net/qYnKK/1/)","**[Live Demo](http://jsfiddle.net/FfzgR/1/)** + +you can use `$.inArray(""Your data"", array)` using `Jquery` function + +for ex: + **HTML:** + +``` + + +``` + +**JQuery:** + +``` +$(function() { + $('select').on('change', function() { +var countries=[""FR"",""IT"",""DE"", ""AU"", ""RU""]; + var data1 = $(this).val();http://jsfiddle.net/FfzgR/#update +if ($.inArray(data1, countries) !== -1) +{ + alert('yes'); +} + else{ + alert('no'); + } + }); +}); + +```" +54126434,"Right now I'm calling an external bash script via open, because said script might run for seconds or it might run for minutes. The only things that are certain are: + +1. It will output text which has to be displayed to the user. Not after the script is done, but while it is still running. +2. It will set a return code with different meanings + +Reading and using the text outputted by the shell script does work. But I don't have a clue on how to read the return code. + +The (simplified) TCL script looks like this: + +``` +#!/usr/bin/tclsh + +proc run_script {} { + set script ""./testing.sh"" + + set process [open ""|${script}"" ""r""] + chan configure $process -blocking 0 -translation {""lf"" ""lf""} -encoding ""iso8859-1"" + + while {[eof $process] == 0} { + if {[gets $process zeile] != -1} { + puts $zeile + } + + update + } + close $process + + return ""???"" +} + +set rc [run_script] +puts ""RC = ${rc}"" + +``` + +The (simplified) shell script does look like this: + +``` +#!/bin/bash + +echo Here +sleep 1 +echo be +sleep 2 +echo dragons +sleep 4 +echo .... +sleep 8 + +exit 20 + +``` + +So how do I read the return code of the shell script via tcl?",2019/01/10,"['https://Stackoverflow.com/questions/54126434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6009051/']","You need to switch the file descriptor back to blocking before you close it to get the exit code. For example: + +You can use `try ... trap`, which was implemented with tcl 8.6: + +``` +chan configure $process -blocking 1 +try { + close $process + # No error + return 0 +} trap CHILDSTATUS {result options} { + return [lindex [dict get $options -errorcode] 2] +} + +``` + +An other option would be to use `catch`: + +``` +chan configure $process -blocking 1 +if {[catch {close $process} result options]} { + if {[lindex [dict get $options -errorcode] 0] eq ""CHILDSTATUS""} { + return [lindex [dict get $options -errorcode] 2] + } else { + # Rethrow other errors + return -options [dict incr options -level] $result + } +} +return 0 + +```","To get the status in 8.5, use this: + +``` +fconfigure $process -blocking 1 +if {[catch {close $process} result options] == 1} { + set code [dict get $options -errorcode] + if {[lindex $code 0] eq ""CHILDSTATUS""} { + return [lindex $code 2] + } + # handle other types of failure here... +} + +``` + +To get the status in 8.4, use this: + +``` +fconfigure $process -blocking 1 +if {[catch {close $process}] == 1} { + set code $::errorCode + if {[lindex $code 0] eq ""CHILDSTATUS""} { + return [lindex $code 2] + } + # handle other types of failure here... +} + +```" +34811616,"As a complete beginner to VBA Excel, I would like to be able to do the following: + +I want to find the first value larger than 0 in a row, and then sum over the following 4 cells in the same row. So + +``` +Animal1 0 0 1 2 3 0 1 +Animal2 3 3 0 1 4 2 0 +Animal3 0 0 0 0 0 1 0 + +``` + +Results in + +``` +Animal1 7 +Animal2 11 +Animal3 1 + +``` + +Is this possible?",2016/01/15,"['https://Stackoverflow.com/questions/34811616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4729787/']","(Your problem description didn't match your examples. I interpreted the problem as one of summing the 4 elements in a row which begin with the first number which is greater than 0. If my interpretation is wrong -- the following code would need to be tweaked.) + +You could do it with a user-defined function (i.e. a UDF -- a VBA function designed to be used as a spreadsheet function): + +``` +Function SumAfter(R As Range, n As Long) As Variant + 'Sums the (at most) n elements beginning with the first occurence of + 'a strictly positive number in the range R, + 'which is assumed to be 1-dimensional. + 'If all numbers are zero or negative -- returns a #VALUE! error + + Dim i As Long, j As Long, m As Long + Dim total As Variant + + m = R.Cells.Count + For i = 1 To m + If R.Cells(i).Value > 0 Then + For j = i To Application.Min(m, i + n - 1) + total = total + R.Cells(j) + Next j + SumAfter = total + Exit Function + End If + Next i + 'error condition if you reach here + SumAfter = CVErr(xlErrValue) +End Function + +``` + +If your sample data is in `A1:H3` then putting the formula `=SumAfter(B1:H1,4)` in `I1` and copying down will work as intended. Note that the code is slightly more general than your problem description. If you are going to use VBA, you might as well make your subs/functions as flexible as possible. Also note that if you are writing a UDF, it is a good idea to think of what type of error you want to return if the input violates expectations. See [this](http://www.cpearson.com/Excel/ReturningErrors.aspx) for an excellent discussion (from Chip Pearson's site - which is an excellent resource for Excel VBA programmers). + +ON EDIT: If you want the first cell greater than 0 added to the next 4 (for a total of 5 cells in the sum) then the function I gave works as is, but using `=SumAfter(B1:H1,5)` instead of `=SumAfter(B1:H1,4)`.","Here is what I would use, I dont know any of the cell placement you have used so you will need to change that yourself. + +Future reference this isnt a code writing site for you, if you are new to VBA i suggest doing simple stuff first, make a message box appear, use code to move to different cells, try a few if statments and/or loops. When your comftable with that start using varibles(Booleans, string , intergers and such) and you will see how far you can go. As i like to say , ""if you can do it in excel, code can do it better"" + +If the code doesnt work or doesnt suit your needs then change it so it does, it worked for me when i used it but im not you nor do i have your spread sheet + +paste it into your vba and use F8 to go through it step by step see how it works and if you want to use it. + +``` +Sub test() + +[A1].Select ' assuming it starts in column A1 + +'loops till it reachs the end of the cells or till it hits a blank cell +Do Until ActiveCell.Value = """" + +ActiveCell.Offset(0, 1).Select + +'adds up the value of the cells going right and removes the previous cell to clean up +Do Until ActiveCell.Value = """" +x = x + ActiveCell.Value +ActiveCell.Offset(0, 1).Select +ActiveCell.Offset(0, -1).ClearContents +Loop + +'goes back to the begining and ends tallyed up value +Selection.End(xlToLeft).Select +ActiveCell.Offset(0, 1).Value = x + +'moves down one to next row +ActiveCell.Offset(1, 0).Select + +Loop + +End Sub + +```" +34811616,"As a complete beginner to VBA Excel, I would like to be able to do the following: + +I want to find the first value larger than 0 in a row, and then sum over the following 4 cells in the same row. So + +``` +Animal1 0 0 1 2 3 0 1 +Animal2 3 3 0 1 4 2 0 +Animal3 0 0 0 0 0 1 0 + +``` + +Results in + +``` +Animal1 7 +Animal2 11 +Animal3 1 + +``` + +Is this possible?",2016/01/15,"['https://Stackoverflow.com/questions/34811616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4729787/']","This is the one of the variants of how you can achieve required result: + +``` + Sub test() + Dim cl As Range, cl2 As Range, k, Dic As Object, i%: i = 1 + Set Dic = CreateObject(""Scripting.Dictionary"") + For Each cl In ActiveSheet.UsedRange.Columns(1).Cells + For Each cl2 In Range(Cells(cl.Row, 2), Cells(cl.Row, 8)) + If cl2.Value2 > 0 Then + Dic.Add i, cl.Value2 & ""|"" & Application.Sum(Range(cl2, cl2.Offset(, 4))) + i = i + 1 + Exit For + End If + Next cl2, cl + Workbooks.Add: i = 1 + For Each k In Dic + Cells(i, ""A"").Value2 = Split(Dic(k), ""|"")(0) + Cells(i, ""b"").Value2 = CDec(Split(Dic(k), ""|"")(1)) + i = i + 1 + Next k + End Sub + +``` + +[![enter image description here](https://i.stack.imgur.com/rviN2.png)](https://i.stack.imgur.com/rviN2.png)","Here is what I would use, I dont know any of the cell placement you have used so you will need to change that yourself. + +Future reference this isnt a code writing site for you, if you are new to VBA i suggest doing simple stuff first, make a message box appear, use code to move to different cells, try a few if statments and/or loops. When your comftable with that start using varibles(Booleans, string , intergers and such) and you will see how far you can go. As i like to say , ""if you can do it in excel, code can do it better"" + +If the code doesnt work or doesnt suit your needs then change it so it does, it worked for me when i used it but im not you nor do i have your spread sheet + +paste it into your vba and use F8 to go through it step by step see how it works and if you want to use it. + +``` +Sub test() + +[A1].Select ' assuming it starts in column A1 + +'loops till it reachs the end of the cells or till it hits a blank cell +Do Until ActiveCell.Value = """" + +ActiveCell.Offset(0, 1).Select + +'adds up the value of the cells going right and removes the previous cell to clean up +Do Until ActiveCell.Value = """" +x = x + ActiveCell.Value +ActiveCell.Offset(0, 1).Select +ActiveCell.Offset(0, -1).ClearContents +Loop + +'goes back to the begining and ends tallyed up value +Selection.End(xlToLeft).Select +ActiveCell.Offset(0, 1).Value = x + +'moves down one to next row +ActiveCell.Offset(1, 0).Select + +Loop + +End Sub + +```" +34811616,"As a complete beginner to VBA Excel, I would like to be able to do the following: + +I want to find the first value larger than 0 in a row, and then sum over the following 4 cells in the same row. So + +``` +Animal1 0 0 1 2 3 0 1 +Animal2 3 3 0 1 4 2 0 +Animal3 0 0 0 0 0 1 0 + +``` + +Results in + +``` +Animal1 7 +Animal2 11 +Animal3 1 + +``` + +Is this possible?",2016/01/15,"['https://Stackoverflow.com/questions/34811616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4729787/']","(Your problem description didn't match your examples. I interpreted the problem as one of summing the 4 elements in a row which begin with the first number which is greater than 0. If my interpretation is wrong -- the following code would need to be tweaked.) + +You could do it with a user-defined function (i.e. a UDF -- a VBA function designed to be used as a spreadsheet function): + +``` +Function SumAfter(R As Range, n As Long) As Variant + 'Sums the (at most) n elements beginning with the first occurence of + 'a strictly positive number in the range R, + 'which is assumed to be 1-dimensional. + 'If all numbers are zero or negative -- returns a #VALUE! error + + Dim i As Long, j As Long, m As Long + Dim total As Variant + + m = R.Cells.Count + For i = 1 To m + If R.Cells(i).Value > 0 Then + For j = i To Application.Min(m, i + n - 1) + total = total + R.Cells(j) + Next j + SumAfter = total + Exit Function + End If + Next i + 'error condition if you reach here + SumAfter = CVErr(xlErrValue) +End Function + +``` + +If your sample data is in `A1:H3` then putting the formula `=SumAfter(B1:H1,4)` in `I1` and copying down will work as intended. Note that the code is slightly more general than your problem description. If you are going to use VBA, you might as well make your subs/functions as flexible as possible. Also note that if you are writing a UDF, it is a good idea to think of what type of error you want to return if the input violates expectations. See [this](http://www.cpearson.com/Excel/ReturningErrors.aspx) for an excellent discussion (from Chip Pearson's site - which is an excellent resource for Excel VBA programmers). + +ON EDIT: If you want the first cell greater than 0 added to the next 4 (for a total of 5 cells in the sum) then the function I gave works as is, but using `=SumAfter(B1:H1,5)` instead of `=SumAfter(B1:H1,4)`.","This is the one of the variants of how you can achieve required result: + +``` + Sub test() + Dim cl As Range, cl2 As Range, k, Dic As Object, i%: i = 1 + Set Dic = CreateObject(""Scripting.Dictionary"") + For Each cl In ActiveSheet.UsedRange.Columns(1).Cells + For Each cl2 In Range(Cells(cl.Row, 2), Cells(cl.Row, 8)) + If cl2.Value2 > 0 Then + Dic.Add i, cl.Value2 & ""|"" & Application.Sum(Range(cl2, cl2.Offset(, 4))) + i = i + 1 + Exit For + End If + Next cl2, cl + Workbooks.Add: i = 1 + For Each k In Dic + Cells(i, ""A"").Value2 = Split(Dic(k), ""|"")(0) + Cells(i, ""b"").Value2 = CDec(Split(Dic(k), ""|"")(1)) + i = i + 1 + Next k + End Sub + +``` + +[![enter image description here](https://i.stack.imgur.com/rviN2.png)](https://i.stack.imgur.com/rviN2.png)" +230343,"I asked a question here [how can i see if my data are coming from two different population?](https://stats.stackexchange.com/questions/230255/how-can-i-see-if-my-data-are-coming-from-two-different-population) and seems like I cannot correctly communicate and the person who is writing to me is making me confused. + +So I try to explain what I want , if you know any method, please just tell me the method, I will try to do it myself. + +I have two groups +**Group A** with **n** number of **samples** +**Group B** with **m** number of **samples** + +The measurements have replicate + +I want to see if the Group A is different from Group B. +for example by the mean, or whatever else which makes statistically different or not different. + +Is there someone who can really guide me what to do? +Many thanks +Nik",2016/08/17,"['https://stats.stackexchange.com/questions/230343', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/127951/']","From reading your previous post, I see that you have two groups with 15 subjects, each with multiple observations (3 each). Each subject appears in each group, except subject 15 who has 0 observation in group 1. + +So, basically, you have a paired design. A way to test whether Group 1 and Group 2 are different is by using a paired wilcoxon signed rank sum test. In R, this can be done using the following code: + +``` +df<- structure(list(Group = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, + 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, + 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, + 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, + 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, + 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), Subject = c(1L, + 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L, 6L, 6L, + 6L, 7L, 7L, 7L, 8L, 8L, 8L, 9L, 9L, 9L, 10L, 10L, 10L, 11L, 11L, + 11L, 12L, 12L, 12L, 13L, 13L, 13L, 14L, 14L, 14L, 1L, 1L, 1L, + 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L, 6L, 6L, 6L, 7L, + 7L, 7L, 8L, 8L, 8L, 9L, 9L, 9L, 10L, 10L, 10L, 11L, 11L, 11L, + 12L, 12L, 12L, 13L, 13L, 13L, 14L, 14L, 14L, 15L, 15L, 15L), + Value = c(29.89577946, 29.51885854, 29.77429604, 33.20695108, + 32.09027292, 31.90909894, 30.88358173, 30.67547731, 30.82494595, + 31.70128247, 31.57217504, 31.61359752, 30.51371055, 30.42241945, + 30.44913954, 26.90850496, 0, 0, 0, 0, 0, 28.94047335, 29.27188604, + 29.78511206, 28.18475423, 27.54266717, 26.99873401, 29.26941344, + 28.50457189, 28.78050443, 31.39038527, 31.19237052, 30.74053275, + 28.68618888, 28.42109545, 28.58222544, 28.99337177, 29.31797, + 28.4541501, 28.18475423, 27.54266717, 26.99873401, 28.07576794, + 28.96344894, 28.48358437, 27.02527663, 27.1308483, 26.96091103, + 27.04019758, 27.51900858, 28.14559621, 26.83569136, 26.90724462, + 26.82675, 0, 0, 0, 27.62449786, 26.82335228, 26.66925534, + 0, 25.81254792, 26.61666776, 26.12545858, 0, 0, 0, 0, 0, + 28.84580419, 29.11003424, 29.24723895, 28.72919768, 29.70673437, + 29.31274377, 30.73133587, 30.44805655, 30.61561583, 27.06896964, + 27.04249553, 27.15990629, 31.54738209, 31.51643714, 31.8055509, + 31.291867, 31.89146186, 31.65812735)), .Names = c(""Group"", + ""Subject"", ""Value""), class = ""data.frame"", row.names = c(NA, + -87L)) + +df$Value[df$Value == 0] <- NA + +df[is.na(df$Value),] ## missing data + +table(df$Group, df$Subject) ## check to see if all groups have equal obs + +## perform wilcoxon signed rank sum test +wilcox.test(formula = Value ~ Group, data = df[!df$Subject == 15,]) ## omit the 15th patient + +Wilcoxon rank sum test with continuity correction + +data: Value by Group +W = 900, p-value = 0.0006732 +alternative hypothesis: true location shift is not equal to 0 + +Warning message: +In wilcox.test.default(x = c(29.89577946, 29.51885854, 29.77429604, : + cannot compute exact p-value with ties + +## we can reject the null hypothesis that both groups are equal + +``` + +From the R documentation, + +> +> If exact p-values are available, an exact confidence interval is obtained by the algorithm described in Bauer (1972), and the Hodges-Lehmann estimator is employed. Otherwise, the returned confidence interval and point estimate are based on normal approximations. These are continuity-corrected for the interval but not the estimate (as the correction depends on the alternative). +> +> +>","For comparing means of populations with different samples, the standard practice is applying a two-sample location test. Depending on the size of your data, you could implement either a t-test or a z-test (t-test is recommended for smaller sample sizes). + +In any case, since you want to find out if the groups are *different*, a two-sided test would be ideal for the purpose. Since the data has different sizes, it is generally accepted that a Welch's test is the best way of performing such comparison. The Welch's test assumes unequal variances, an assumption you could test yourself. In case you have reasons to believe that the variances are equal instead, it is recommended that you use a *paired* t-test. + +In R, assuming your data is stored un vectors `x` and `y` + +``` +#Welch's t-test +t.test(x,y) + +#paired sample test +t.test(x,y, paired = TRUE) + +#test for equality of variances +var.test(x,y) + +```" +230343,"I asked a question here [how can i see if my data are coming from two different population?](https://stats.stackexchange.com/questions/230255/how-can-i-see-if-my-data-are-coming-from-two-different-population) and seems like I cannot correctly communicate and the person who is writing to me is making me confused. + +So I try to explain what I want , if you know any method, please just tell me the method, I will try to do it myself. + +I have two groups +**Group A** with **n** number of **samples** +**Group B** with **m** number of **samples** + +The measurements have replicate + +I want to see if the Group A is different from Group B. +for example by the mean, or whatever else which makes statistically different or not different. + +Is there someone who can really guide me what to do? +Many thanks +Nik",2016/08/17,"['https://stats.stackexchange.com/questions/230343', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/127951/']","When thinking about a statistical problem, you should ask yourself what experiment you have. + +You have two groups, with different sample size. You can calculate arithmetic mean over all your replicates. You will be able to use the means for comparison. + +1:) Check if you can assume normality. Because your data is simple, you can just do a simple QQ plot or histogram. + +2:) If you can assume normality, you should use paired t-test. + +3:) If you can't assume normality, you should Wilcox signed-rank test","For comparing means of populations with different samples, the standard practice is applying a two-sample location test. Depending on the size of your data, you could implement either a t-test or a z-test (t-test is recommended for smaller sample sizes). + +In any case, since you want to find out if the groups are *different*, a two-sided test would be ideal for the purpose. Since the data has different sizes, it is generally accepted that a Welch's test is the best way of performing such comparison. The Welch's test assumes unequal variances, an assumption you could test yourself. In case you have reasons to believe that the variances are equal instead, it is recommended that you use a *paired* t-test. + +In R, assuming your data is stored un vectors `x` and `y` + +``` +#Welch's t-test +t.test(x,y) + +#paired sample test +t.test(x,y, paired = TRUE) + +#test for equality of variances +var.test(x,y) + +```" +4490227,Does anyone know how to build automatic tagging (blog post/document) algorithm? Any example will be appreciated.,2010/12/20,"['https://Stackoverflow.com/questions/4490227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548690/']","Heroku creates a database for each application deployed to it (no need to run `heroku rake db:create`. Here are the commands you should be using to deploy a Rails application to Heroku: + +``` +git init +git add . +git commit -m ""initial import"" +heroku create +git push heroku master +heroku rake db:migrate +heroku open + +```",I believe Heroku creates a new database.yml for you on deploy if you have no production according to the [Docs](http://groups.google.com/group/heroku/browse_thread/thread/cfa3ad5263a9e967?pli=1). +4490227,Does anyone know how to build automatic tagging (blog post/document) algorithm? Any example will be appreciated.,2010/12/20,"['https://Stackoverflow.com/questions/4490227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548690/']","It's not telling you that you have no Database. + +It's telling you that it can't find a specific record + +``` +(Couldn't find Drummer with ID=1): + +``` + +It's likely that you have code that's doing `Drummer.find(1)` and that doesn't exist on your production environment. + +Recommend you either: + +* create a seeds file (heroku rake db:seed) [rails cast](http://railscasts.com/episodes/179-seed-data) +* push your entire database to heroku (heroku db:push) [make sure you understand this will wipe out your production database]","Heroku creates a database for each application deployed to it (no need to run `heroku rake db:create`. Here are the commands you should be using to deploy a Rails application to Heroku: + +``` +git init +git add . +git commit -m ""initial import"" +heroku create +git push heroku master +heroku rake db:migrate +heroku open + +```" +4490227,Does anyone know how to build automatic tagging (blog post/document) algorithm? Any example will be appreciated.,2010/12/20,"['https://Stackoverflow.com/questions/4490227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548690/']","It's not telling you that you have no Database. + +It's telling you that it can't find a specific record + +``` +(Couldn't find Drummer with ID=1): + +``` + +It's likely that you have code that's doing `Drummer.find(1)` and that doesn't exist on your production environment. + +Recommend you either: + +* create a seeds file (heroku rake db:seed) [rails cast](http://railscasts.com/episodes/179-seed-data) +* push your entire database to heroku (heroku db:push) [make sure you understand this will wipe out your production database]",I believe Heroku creates a new database.yml for you on deploy if you have no production according to the [Docs](http://groups.google.com/group/heroku/browse_thread/thread/cfa3ad5263a9e967?pli=1). +36534043,"Given day in week (let's say Monday), I need to find closest date (in future) to given date (for example 9-4-2016) which is this day in week (for these examples, it should be 11-4-2016).",2016/04/10,"['https://Stackoverflow.com/questions/36534043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1767332/']","This is a pure Ruby solution. + +``` +require 'date' + +d = Date.strptime('9-4-2016', '%d-%m-%Y') + #=> # +d + (1 - d.wday) % 7 + #=> # + +``` + +`1` is Monday's offset. `d.wday #=> 6`. + +I have assumed that if the date falls on a Monday, the ""closest"" Monday is the same day. If it is to be the following Monday, use: + +``` +d + (d.wday == 1) ? 7 : (1 - d.wday) % 7 + +```","You can find this date in the nearest week of your `date`: + +``` +date = Date.parse('9-4-2016') +(date..date + 6).find {|d| d.strftime(""%A"") == ""Monday""} +#=> Mon, 11 Apr 2016 + +```" +4030546,"I'm developing a football manager website, but I can't figure out how to use properly the background-thread plugin and Quartz plugin (there is no much docs). +My problem is.. +I have a Controller of a Match class, with a function that I need to start at some time. +With quartz I have tried to create a job but then I cannot call directly the function (and how many job should I create if I have more match to start?) or I don't know how to do it, and with background-thread I create the service class but then I have no idea how to implement it. +Someone Can help me with this? +Thanks + +**EDIT:** + +**Solution in this post:** + +[grails thread -> hibernateException: No Hibernate session bound to thread](https://stackoverflow.com/questions/4088259/grails-thread-hibernateexception-no-hibernate-session-bound-to-thread)",2010/10/27,"['https://Stackoverflow.com/questions/4030546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/488413/']","(March 2012) It looks like this is finally going to be possible soon -- git 1.7.10 is going to support this syntax in `.gitconfig`: + +``` +[include] + path = /path/to/file + +``` + +See [here](https://github.com/gitster/git/commit/9b25a0b52e09400719366f0a33d0d0da98bbf7b0) for a detailed description of the git change and its edge cases. + +By the way, a couple of subtleties worth pointing out: + +1. Path expansion, e.g. `~` or `$HOME`, does not appear to be supported. +2. If a relative path is specified, then it is relative to the .gitconfig file that has the `[include]` statement. This works correctly even across chained includes -- e.g. `~/.gitconfig` can have: + +``` +[include] + path = subdir/gitconfig + +``` + +and `subdir/gitconfig` can have: + +``` +[include] + path = nested_subdir/gitconfig + +``` + +... which will cause `subdir/nested_subdir/gitconfig` to be loaded. +3. If git can't find the target file, it silently ignores the error. This appears to be by design.","(March 2012): As mentioned in [Mike Morearty](https://stackoverflow.com/users/179675/mike-morearty)'s [answer](https://stackoverflow.com/a/9733336/6309) (which I upvoted), git 1.7.10+ will support this feature. + +--- + +Original answer (October 2010): + +Currently, no. + +As I mentioned in [Is it possible to include a file in your `.gitconfig`](https://stackoverflow.com/questions/1557183/is-it-possible-to-include-a-file-in-your-gitconfig), you already have 3 separate gitconfig for you to get your settings organized: + +``` +$GIT_DIR/config + +``` + +> +> Repository specific configuration file. (The filename is of course relative to the repository root, not the working directory.) +> +> +> + +``` +~/.gitconfig + +``` + +> +> User-specific configuration file. Also called ""global"" configuration file. +> +> +> + +``` +$(prefix)/etc/gitconfig + +``` + +> +> System-wide configuration file +> +> +> + +Config File inclusion was discussed in May 2010, and a [first patch was written](http://kerneltrap.org/mailarchive/git/2010/5/6/29891) by Ævar Arnfjörð Bjarmason, but I don't see this patch in one of the latest ""[what's cooking in Git](http://permalink.gmane.org/gmane.comp.version-control.git/159023)""." +71266586,"I try to see when I click navbar then I want to see the topic, but it is showing the topic under navbar. I try to give margin, but it doesn't work. Is someone help me with how can I solve this problem. + +[Web site showing like that](https://i.stack.imgur.com/g4vki.png) + +[But I want to see like that](https://i.stack.imgur.com/WcN46.png) + +``` +there is code: https://codepen.io/rero34/pen/mdqGyVo + +```",2022/02/25,"['https://Stackoverflow.com/questions/71266586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14349341/']","Here is a generator which meets your requirements: + +``` +def dict_generator(dictionary, previous=None): + previous = previous[:] if previous else [] + if isinstance(dictionary, dict): + for key, value in dictionary.items(): + if isinstance(value, dict): + for d in dict_generator(value, previous + [key]): + yield d + elif isinstance(value, list) or isinstance(value, tuple): + for k,v in enumerate(value): + for d in dict_generator(v, previous + [key] + [[k]]): + yield d + else: + yield previous + [key, value] + else: + yield previous + [dictionary] + +mydict ={'foo': {'foo1': [1,2,3], 'foo2': 1}} +print(list(dict_generator(mydict))) + +``` + +Will produce output like this: + +``` +[['foo', 'foo1', [0], 1], ['foo', 'foo1', [1], 2], ['foo', 'foo1', [2], 3], ['foo', 'foo2', 1]] + +```","Preparation: +------------ + +[`jsonpath-ng`](https://github.com/h2non/jsonpath-ng) can parse even such a nested json object very easily. It can be installed by the following command: + +```sh +pip install --upgrade jsonpath-ng + +``` + +Code: +----- + +```py +import jsonpath_ng as jp + +# Create the sample json +data = {""Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder"":{ ""CoopRoomDifficultySetups"": [ { ""RoomDifficulties"": [ { ""Id"" : 510, ""IsEnabled"" : 1, ""AvailableRegions"" : [ ], ""Weight"" : 1, ""MinLevel"" : 60, ""MaxLevel"" : 69, ""MinFriendsLevel"" : 50, ""MaxFriendsLevel"" : 99, ""MinPunishLevel"" : 0, ""MaxPunishLevel"" : 0, ""MinHardCP"" : ""0"", ""MinCP"" : ""0"", ""MaxCP"" : ""0"", ""MaxHardCP"" : ""0"", ""LowPowerBonus"" : 0.5, ""LowPowerCp"" : ""0"", ""LowPowerLevel"" : 90, ""Maps"" : [ { ""MapId"" : 4, ""NpcPreset"" : ""NPCPresetMap5Coop3"", ""TypesLimit"" : 1000, ""TierSpawnProbabilities"" : [ { ""Tier"" : 0, ""SpawnProbability"" : 0.6 }, { ""Tier"" : 1, ""SpawnProbability"" : 0.75 }, { ""Tier"" : 2, ""SpawnProbability"" : 0.52 }, { ""Tier"" : 3, ""SpawnProbability"" : 0.6 } ], ""ChampionProbabilityTier2"" : 0.1, ""ChampionProbabilityTier3"" : 0.08, ""PlayersWhenMaxProbabilityTier2"" : 3, ""PlayersWhenMaxProbabilityTier3"" : 6, ""NpcLevelMultiplier"" : 1.15, ""MapWeight"" : 1, ""PointsNpcMultiplier"" : 0.85, ""XpNpcMultiplier"" : 0.85, ""ScoreNpcMultiplier"" : 0.85, ""NpcMinLevel"" : 63, ""NpcMaxLevel"" : 77 } ], ""TimeOfDayMode_Parsable"" : 0 }]},[{""foo"":""foo""}]]}} + +# Define a dictionary +d = {} + +# Define an expression to parse the json object +expr = jp.parse('$..*') +for m in expr.find(data): + + # Show a json path + print(str(m.full_path)) + + # Update the dictionary + d[str(m.full_path)] = m.value + +# Show an example value in the dictionary +key = 'Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].NpcMaxLevel' +print(d[key]) + +``` + +Output: +------- + +``` +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Id +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].IsEnabled +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].AvailableRegions +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Weight +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].MinLevel +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].MaxLevel +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].MinFriendsLevel +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].MaxFriendsLevel +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].MinPunishLevel +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].MaxPunishLevel +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].MinHardCP +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].MinCP +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].MaxCP +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].MaxHardCP +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].LowPowerBonus +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].LowPowerCp +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].LowPowerLevel +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].TimeOfDayMode_Parsable +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].MapId +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].NpcPreset +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].TypesLimit +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].TierSpawnProbabilities +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].ChampionProbabilityTier2 +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].ChampionProbabilityTier3 +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].PlayersWhenMaxProbabilityTier2 +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].PlayersWhenMaxProbabilityTier3 +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].NpcLevelMultiplier +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].MapWeight +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].PointsNpcMultiplier +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].XpNpcMultiplier +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].ScoreNpcMultiplier +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].NpcMinLevel +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].NpcMaxLevel +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].TierSpawnProbabilities.[0].Tier +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].TierSpawnProbabilities.[0].SpawnProbability +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].TierSpawnProbabilities.[1].Tier +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].TierSpawnProbabilities.[1].SpawnProbability +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].TierSpawnProbabilities.[2].Tier +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].TierSpawnProbabilities.[2].SpawnProbability +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].TierSpawnProbabilities.[3].Tier +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[0].RoomDifficulties.[0].Maps.[0].TierSpawnProbabilities.[3].SpawnProbability +Assets/CustomGameData/Resources/Configs/RoomDifficulty/RoomDifficultySetupHolder.CoopRoomDifficultySetups.[1].[0].foo + +``` + +and + +``` +77 + +```" +71266586,"I try to see when I click navbar then I want to see the topic, but it is showing the topic under navbar. I try to give margin, but it doesn't work. Is someone help me with how can I solve this problem. + +[Web site showing like that](https://i.stack.imgur.com/g4vki.png) + +[But I want to see like that](https://i.stack.imgur.com/WcN46.png) + +``` +there is code: https://codepen.io/rero34/pen/mdqGyVo + +```",2022/02/25,"['https://Stackoverflow.com/questions/71266586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14349341/']","Here is a generator which meets your requirements: + +``` +def dict_generator(dictionary, previous=None): + previous = previous[:] if previous else [] + if isinstance(dictionary, dict): + for key, value in dictionary.items(): + if isinstance(value, dict): + for d in dict_generator(value, previous + [key]): + yield d + elif isinstance(value, list) or isinstance(value, tuple): + for k,v in enumerate(value): + for d in dict_generator(v, previous + [key] + [[k]]): + yield d + else: + yield previous + [key, value] + else: + yield previous + [dictionary] + +mydict ={'foo': {'foo1': [1,2,3], 'foo2': 1}} +print(list(dict_generator(mydict))) + +``` + +Will produce output like this: + +``` +[['foo', 'foo1', [0], 1], ['foo', 'foo1', [1], 2], ['foo', 'foo1', [2], 3], ['foo', 'foo2', 1]] + +```","What almost helped me completely is that piece of code + + +``` +def dict_generator(indict, pre=None): +pre = pre[:] if pre else [] +if isinstance(indict, dict): + for key, value in indict.items(): + if isinstance(value, dict): + for d in dict_generator(value, pre + [key]): + yield d + elif isinstance(value, list) or isinstance(value, tuple): + for k,v in enumerate(value): + for d in dict_generator(v, pre + [key] + [k]): + yield d + else: + yield pre + [key, value] +else: + yield indict + +``` + +However still there is one exception when it doesn't work as I wish for example when this structure is given + +``` +{ +""foo"":{ + ""foo1"": [1,2,3], + ""foo2"": 1 +} + +``` + +} +the output of `dict_generator` will be + +``` +[1, 2, 3, ['foo', 'foo2', 1]] + +``` + +so it doesn't give me a path to the key that has a list as an value since my desired output should look that way: + +``` +[['foo', 'foo1', [0], 1], ['foo', 'foo2', [1], 2], ['foo', 'foo2, [2], 3], ['foo', 'foo2', 1]]] + +```" +38659730,"We have an extremely large nvarchar(max) field that contains html. Within this html is an img tag. + +Example: + +``` + input[j + 1]) + swap(input, j, j + 1); + +``` + +Second example: + +``` +for (int i = 1; i < input.Length-1; i++) + for (int j = 0; j < input.Length - 1; j++) + if (input[j] > input[j + 1]) + swap(input, j, j + 1); + +``` + +[**Wikipedia Example**](http://en.wikipedia.org/wiki/Bubble_sort) +----------------------------------------------------------------- + +For input: 5 1 4 2 8 + +First example: 6 comparisons + +Second example: 12 comparisons + +> +> **First Pass:** +> +> +> ( **5 1** 4 2 8 ) --> ( **1 5** 4 2 8 ), Swap since 5 > 1 +> +> +> ( 1 **5 4** 2 8 ) --> ( 1 **4 5** 2 8 ), Swap since 5 > 4 +> +> +> ( 1 4 **5 2** 8 ) --> ( 1 4 **2 5** 8 ), Swap since 5 > 2 +> +> +> ( 1 4 2 **5 8** ) --> ( 1 4 2 **5 8** ) +> +> +> **Second Pass:** +> +> +> ( **1 4** 2 5 8 ) --> ( **1 4** 2 5 8 ) +> +> +> ( 1 **4 2** 5 8 ) --> ( 1 **2 4** 5 8 ), Swap since 4 > 2 **<-- Example 1 stop here** +> +> +> ( 1 2 **4 5** 8 ) --> ( 1 2 **4 5** 8 ) +> +> +> ( 1 2 4 **5 8** ) --> ( 1 2 4 **5 8** ) +> +> +> **Third Pass** +> +> +> ( **1 2** 4 5 8 ) --> ( **1 2** 4 5 8 ) +> +> +> ( 1 **2 4** 5 8 ) --> ( 1 **2 4** 5 8 ) +> +> +> ( 1 2 **4 5** 8 ) --> ( 1 2 **4 5** 8 ) +> +> +> ( 1 2 4 **5 8** ) --> ( 1 2 4 **5 8** ) **<-- Example 2 stop here** +> +> +> + +Edit: when I say which one is right I mean which one is the original bubble sort",2012/11/29,"['https://Stackoverflow.com/questions/13630967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1424127/']","First algorithm is incorrect. +It will fail if last element in the array is not the greatest. + +Specifically, iteration on 'j': + +``` +for (int j = 0; j < input.Length - 1 - i; j++) + +``` + +seems to skip last element. +If your input is {0, 2, 2, 1} +Then your input.Length = 4 + +for loop above will have condition j < 4 - 1 - i, where i = 1 so j < 4 - 1 - 1, so j < 2 +so last j used will be j = 1, last comparison will be input[1] > input[2] -> input[3] is never compared. + +you can fix it by changing for loop to j <= input.Length - 1 - i","*I found two bubble algorithms but I not sure which one is right..* + +I'm sure they're both right. The only difference is your second code has to loop through the sorted array one last time." +13630967,"I found two bubble algorithms but I not sure which one is right... + +First example: + +``` +for (int i = 1; i < input.Length-1; i++) + for (int j = 0; j < input.Length - 1 - i; j++) + if (input[j] > input[j + 1]) + swap(input, j, j + 1); + +``` + +Second example: + +``` +for (int i = 1; i < input.Length-1; i++) + for (int j = 0; j < input.Length - 1; j++) + if (input[j] > input[j + 1]) + swap(input, j, j + 1); + +``` + +[**Wikipedia Example**](http://en.wikipedia.org/wiki/Bubble_sort) +----------------------------------------------------------------- + +For input: 5 1 4 2 8 + +First example: 6 comparisons + +Second example: 12 comparisons + +> +> **First Pass:** +> +> +> ( **5 1** 4 2 8 ) --> ( **1 5** 4 2 8 ), Swap since 5 > 1 +> +> +> ( 1 **5 4** 2 8 ) --> ( 1 **4 5** 2 8 ), Swap since 5 > 4 +> +> +> ( 1 4 **5 2** 8 ) --> ( 1 4 **2 5** 8 ), Swap since 5 > 2 +> +> +> ( 1 4 2 **5 8** ) --> ( 1 4 2 **5 8** ) +> +> +> **Second Pass:** +> +> +> ( **1 4** 2 5 8 ) --> ( **1 4** 2 5 8 ) +> +> +> ( 1 **4 2** 5 8 ) --> ( 1 **2 4** 5 8 ), Swap since 4 > 2 **<-- Example 1 stop here** +> +> +> ( 1 2 **4 5** 8 ) --> ( 1 2 **4 5** 8 ) +> +> +> ( 1 2 4 **5 8** ) --> ( 1 2 4 **5 8** ) +> +> +> **Third Pass** +> +> +> ( **1 2** 4 5 8 ) --> ( **1 2** 4 5 8 ) +> +> +> ( 1 **2 4** 5 8 ) --> ( 1 **2 4** 5 8 ) +> +> +> ( 1 2 **4 5** 8 ) --> ( 1 2 **4 5** 8 ) +> +> +> ( 1 2 4 **5 8** ) --> ( 1 2 4 **5 8** ) **<-- Example 2 stop here** +> +> +> + +Edit: when I say which one is right I mean which one is the original bubble sort",2012/11/29,"['https://Stackoverflow.com/questions/13630967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1424127/']","First algorithm is incorrect. +It will fail if last element in the array is not the greatest. + +Specifically, iteration on 'j': + +``` +for (int j = 0; j < input.Length - 1 - i; j++) + +``` + +seems to skip last element. +If your input is {0, 2, 2, 1} +Then your input.Length = 4 + +for loop above will have condition j < 4 - 1 - i, where i = 1 so j < 4 - 1 - 1, so j < 2 +so last j used will be j = 1, last comparison will be input[1] > input[2] -> input[3] is never compared. + +you can fix it by changing for loop to j <= input.Length - 1 - i","Both are right. + +First one is comparatively more efficient." +13630967,"I found two bubble algorithms but I not sure which one is right... + +First example: + +``` +for (int i = 1; i < input.Length-1; i++) + for (int j = 0; j < input.Length - 1 - i; j++) + if (input[j] > input[j + 1]) + swap(input, j, j + 1); + +``` + +Second example: + +``` +for (int i = 1; i < input.Length-1; i++) + for (int j = 0; j < input.Length - 1; j++) + if (input[j] > input[j + 1]) + swap(input, j, j + 1); + +``` + +[**Wikipedia Example**](http://en.wikipedia.org/wiki/Bubble_sort) +----------------------------------------------------------------- + +For input: 5 1 4 2 8 + +First example: 6 comparisons + +Second example: 12 comparisons + +> +> **First Pass:** +> +> +> ( **5 1** 4 2 8 ) --> ( **1 5** 4 2 8 ), Swap since 5 > 1 +> +> +> ( 1 **5 4** 2 8 ) --> ( 1 **4 5** 2 8 ), Swap since 5 > 4 +> +> +> ( 1 4 **5 2** 8 ) --> ( 1 4 **2 5** 8 ), Swap since 5 > 2 +> +> +> ( 1 4 2 **5 8** ) --> ( 1 4 2 **5 8** ) +> +> +> **Second Pass:** +> +> +> ( **1 4** 2 5 8 ) --> ( **1 4** 2 5 8 ) +> +> +> ( 1 **4 2** 5 8 ) --> ( 1 **2 4** 5 8 ), Swap since 4 > 2 **<-- Example 1 stop here** +> +> +> ( 1 2 **4 5** 8 ) --> ( 1 2 **4 5** 8 ) +> +> +> ( 1 2 4 **5 8** ) --> ( 1 2 4 **5 8** ) +> +> +> **Third Pass** +> +> +> ( **1 2** 4 5 8 ) --> ( **1 2** 4 5 8 ) +> +> +> ( 1 **2 4** 5 8 ) --> ( 1 **2 4** 5 8 ) +> +> +> ( 1 2 **4 5** 8 ) --> ( 1 2 **4 5** 8 ) +> +> +> ( 1 2 4 **5 8** ) --> ( 1 2 4 **5 8** ) **<-- Example 2 stop here** +> +> +> + +Edit: when I say which one is right I mean which one is the original bubble sort",2012/11/29,"['https://Stackoverflow.com/questions/13630967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1424127/']","First algorithm is incorrect. +It will fail if last element in the array is not the greatest. + +Specifically, iteration on 'j': + +``` +for (int j = 0; j < input.Length - 1 - i; j++) + +``` + +seems to skip last element. +If your input is {0, 2, 2, 1} +Then your input.Length = 4 + +for loop above will have condition j < 4 - 1 - i, where i = 1 so j < 4 - 1 - 1, so j < 2 +so last j used will be j = 1, last comparison will be input[1] > input[2] -> input[3] is never compared. + +you can fix it by changing for loop to j <= input.Length - 1 - i","without doing too much thinking, It looks like they're both correct, but the first one seems to do less redundant operations, and therefore takes less time to execute + +The first seems to depend on the fact that your last i blocks are correct, therefore it doesn't even bother with them." +13630967,"I found two bubble algorithms but I not sure which one is right... + +First example: + +``` +for (int i = 1; i < input.Length-1; i++) + for (int j = 0; j < input.Length - 1 - i; j++) + if (input[j] > input[j + 1]) + swap(input, j, j + 1); + +``` + +Second example: + +``` +for (int i = 1; i < input.Length-1; i++) + for (int j = 0; j < input.Length - 1; j++) + if (input[j] > input[j + 1]) + swap(input, j, j + 1); + +``` + +[**Wikipedia Example**](http://en.wikipedia.org/wiki/Bubble_sort) +----------------------------------------------------------------- + +For input: 5 1 4 2 8 + +First example: 6 comparisons + +Second example: 12 comparisons + +> +> **First Pass:** +> +> +> ( **5 1** 4 2 8 ) --> ( **1 5** 4 2 8 ), Swap since 5 > 1 +> +> +> ( 1 **5 4** 2 8 ) --> ( 1 **4 5** 2 8 ), Swap since 5 > 4 +> +> +> ( 1 4 **5 2** 8 ) --> ( 1 4 **2 5** 8 ), Swap since 5 > 2 +> +> +> ( 1 4 2 **5 8** ) --> ( 1 4 2 **5 8** ) +> +> +> **Second Pass:** +> +> +> ( **1 4** 2 5 8 ) --> ( **1 4** 2 5 8 ) +> +> +> ( 1 **4 2** 5 8 ) --> ( 1 **2 4** 5 8 ), Swap since 4 > 2 **<-- Example 1 stop here** +> +> +> ( 1 2 **4 5** 8 ) --> ( 1 2 **4 5** 8 ) +> +> +> ( 1 2 4 **5 8** ) --> ( 1 2 4 **5 8** ) +> +> +> **Third Pass** +> +> +> ( **1 2** 4 5 8 ) --> ( **1 2** 4 5 8 ) +> +> +> ( 1 **2 4** 5 8 ) --> ( 1 **2 4** 5 8 ) +> +> +> ( 1 2 **4 5** 8 ) --> ( 1 2 **4 5** 8 ) +> +> +> ( 1 2 4 **5 8** ) --> ( 1 2 4 **5 8** ) **<-- Example 2 stop here** +> +> +> + +Edit: when I say which one is right I mean which one is the original bubble sort",2012/11/29,"['https://Stackoverflow.com/questions/13630967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1424127/']","First algorithm is incorrect. +It will fail if last element in the array is not the greatest. + +Specifically, iteration on 'j': + +``` +for (int j = 0; j < input.Length - 1 - i; j++) + +``` + +seems to skip last element. +If your input is {0, 2, 2, 1} +Then your input.Length = 4 + +for loop above will have condition j < 4 - 1 - i, where i = 1 so j < 4 - 1 - 1, so j < 2 +so last j used will be j = 1, last comparison will be input[1] > input[2] -> input[3] is never compared. + +you can fix it by changing for loop to j <= input.Length - 1 - i","In a bubble sort, after the first pass, you are guaranteed that the largest value will occupy the last position in the array. This is because by definition, the bubble sort swaps the highest value toward the end of the array. + +This means that on the second pass, you do not need to compare the last value again, because it is guaranteed to be larger or equal to the element in the next lower index. Likewise, after pass 2, the top two elements will be the highest values and sorted relative to one another. + +By extension, after `i` passes, the `i` top elements will be in their correct positions. + +The first example takes this into account, by subtracting `i` from the maximum `j` iterator value. The second example unnecessarily compares the upper elements in subsequent passes. It doesn't hurt, but it is redundant, i.e. not *optimized*. It is still a bubble sort, because it is swapping adjacent values, moving the higher valued element toward the end of the array. + +Does that make sense?" +13630967,"I found two bubble algorithms but I not sure which one is right... + +First example: + +``` +for (int i = 1; i < input.Length-1; i++) + for (int j = 0; j < input.Length - 1 - i; j++) + if (input[j] > input[j + 1]) + swap(input, j, j + 1); + +``` + +Second example: + +``` +for (int i = 1; i < input.Length-1; i++) + for (int j = 0; j < input.Length - 1; j++) + if (input[j] > input[j + 1]) + swap(input, j, j + 1); + +``` + +[**Wikipedia Example**](http://en.wikipedia.org/wiki/Bubble_sort) +----------------------------------------------------------------- + +For input: 5 1 4 2 8 + +First example: 6 comparisons + +Second example: 12 comparisons + +> +> **First Pass:** +> +> +> ( **5 1** 4 2 8 ) --> ( **1 5** 4 2 8 ), Swap since 5 > 1 +> +> +> ( 1 **5 4** 2 8 ) --> ( 1 **4 5** 2 8 ), Swap since 5 > 4 +> +> +> ( 1 4 **5 2** 8 ) --> ( 1 4 **2 5** 8 ), Swap since 5 > 2 +> +> +> ( 1 4 2 **5 8** ) --> ( 1 4 2 **5 8** ) +> +> +> **Second Pass:** +> +> +> ( **1 4** 2 5 8 ) --> ( **1 4** 2 5 8 ) +> +> +> ( 1 **4 2** 5 8 ) --> ( 1 **2 4** 5 8 ), Swap since 4 > 2 **<-- Example 1 stop here** +> +> +> ( 1 2 **4 5** 8 ) --> ( 1 2 **4 5** 8 ) +> +> +> ( 1 2 4 **5 8** ) --> ( 1 2 4 **5 8** ) +> +> +> **Third Pass** +> +> +> ( **1 2** 4 5 8 ) --> ( **1 2** 4 5 8 ) +> +> +> ( 1 **2 4** 5 8 ) --> ( 1 **2 4** 5 8 ) +> +> +> ( 1 2 **4 5** 8 ) --> ( 1 2 **4 5** 8 ) +> +> +> ( 1 2 4 **5 8** ) --> ( 1 2 4 **5 8** ) **<-- Example 2 stop here** +> +> +> + +Edit: when I say which one is right I mean which one is the original bubble sort",2012/11/29,"['https://Stackoverflow.com/questions/13630967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1424127/']","First algorithm is incorrect. +It will fail if last element in the array is not the greatest. + +Specifically, iteration on 'j': + +``` +for (int j = 0; j < input.Length - 1 - i; j++) + +``` + +seems to skip last element. +If your input is {0, 2, 2, 1} +Then your input.Length = 4 + +for loop above will have condition j < 4 - 1 - i, where i = 1 so j < 4 - 1 - 1, so j < 2 +so last j used will be j = 1, last comparison will be input[1] > input[2] -> input[3] is never compared. + +you can fix it by changing for loop to j <= input.Length - 1 - i","The first one is what's called optimized bubble sort + + + +the second one is the ""classic"" bubble sort." +171510,"I have developed an app that will live at `xyzdomain.com/app` on our dedicated hosting setup. My client wants the app to be accessible at `clientdomain.com/app`. What options exist for transparently proxying or redirecting requests for `clientdomain.com/app/whatever` to `xyzdomain.com/app/whatever` such that the original URL is preserved for SEO purposes? In other words, the client doesn't want `xyzdomain.com/app/whatever` appearing on Google, but would rather it show up as `clientdomain.com/app/whatever`. + +An ordinary frame page at the client domain is not acceptable here, as links within the frame pages would still reference `xyzdomain.com`. + +Edit: It sounds like I want a reverse proxy setup, but is it common or even reasonable to setup a reverse proxy that forwards requests to another server not on the same network as the proxy server? Wouldn't that cause twice the latency and double the bandwidth usage? + +Edit: Guys, I'm aware of the benefits of using a subdomain. That isn't possible here because the client only wants www.clientdomain.com to show up in search results. So yeah, no subdomain recommendations - it's not an option.",2010/08/17,"['https://serverfault.com/questions/171510', 'https://serverfault.com', 'https://serverfault.com/users/11577/']","I only see two ways of doing this. One is to use a reverse proxy setup like you say... However, according to your description I would advise against it. + +The other solution is to have a server on your client reply to every request with with a HTTP 302 for the corresponding URL on the other side but again I would advise against this setup too because it would require 2 GETs for each page request and would also change the URL visible to the end user (on the address bar). + +How does your client feel about a subdomain like `app.clientdomain.com` instead of `clientdomain.com/app`? + +My recommendation is that you try to reason with your client about using a subdomain. + +Hope this helps.","You will need a virtual server for clientdomain.com on the dedicated hosting setup. Then the issue becomed transperently proxying the request from clientdomain.com to the dedicated server (by IP address). + +If clientdomain.com is not dedicated to the application, using a subdomain would be simpler. This also would need a host (virtual or otherwise) on the dedicated hosting setup." +171510,"I have developed an app that will live at `xyzdomain.com/app` on our dedicated hosting setup. My client wants the app to be accessible at `clientdomain.com/app`. What options exist for transparently proxying or redirecting requests for `clientdomain.com/app/whatever` to `xyzdomain.com/app/whatever` such that the original URL is preserved for SEO purposes? In other words, the client doesn't want `xyzdomain.com/app/whatever` appearing on Google, but would rather it show up as `clientdomain.com/app/whatever`. + +An ordinary frame page at the client domain is not acceptable here, as links within the frame pages would still reference `xyzdomain.com`. + +Edit: It sounds like I want a reverse proxy setup, but is it common or even reasonable to setup a reverse proxy that forwards requests to another server not on the same network as the proxy server? Wouldn't that cause twice the latency and double the bandwidth usage? + +Edit: Guys, I'm aware of the benefits of using a subdomain. That isn't possible here because the client only wants www.clientdomain.com to show up in search results. So yeah, no subdomain recommendations - it's not an option.",2010/08/17,"['https://serverfault.com/questions/171510', 'https://serverfault.com', 'https://serverfault.com/users/11577/']","I only see two ways of doing this. One is to use a reverse proxy setup like you say... However, according to your description I would advise against it. + +The other solution is to have a server on your client reply to every request with with a HTTP 302 for the corresponding URL on the other side but again I would advise against this setup too because it would require 2 GETs for each page request and would also change the URL visible to the end user (on the address bar). + +How does your client feel about a subdomain like `app.clientdomain.com` instead of `clientdomain.com/app`? + +My recommendation is that you try to reason with your client about using a subdomain. + +Hope this helps.","The easiest solution is to define an domain alias within the webserver. This is much the same method that www.blah.com is the same site as blah.com. + +This can be configured in most major web servers (e.g. IIS and Apache). + +If you specify your web server technology, I might be able to supply some instructions ;)" +206311,"I am trying to do an export of approx 30,000 attachments in our Salesforce Org, + +Would anyone have been through a similar exercise and can advise best practice or the best way / tool to do this? + +Kind Regards + +matt",2018/01/30,"['https://salesforce.stackexchange.com/questions/206311', 'https://salesforce.stackexchange.com', 'https://salesforce.stackexchange.com/users/34616/']","The first thing I would try is the (relatively) new [SFDX](https://developer.salesforce.com/tools/sfdxcli) tooling. See the SFDX documentation [Example: Export and Import Data Between Orgs](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_test_data_example.htm). + +The export would follow this pattern (example from the above link): + +``` +sfdx force:data:tree:export --query \ + ""SELECT Id, Name, Title__c, Phone__c, Mobile_Phone__c, \ + Email__c, Picture__c, \ + (SELECT Name, Address__c, City__c, State__c, Zip__c, \ + Price__c, Title__c, Beds__c, Baths__c, Picture__c, \ + Thumbnail__c, Description__c \ + FROM Properties__r) \ + FROM Broker__c"" \ + --prefix export-demo --outputdir sfdx-out --plan + +``` + +but with the SOQL querying the `Attachment` object. + +(Not sure about governor limits: may be necessary to use many requests with a `where` clause to break the data up into groups.)","If you don’t want to perform a manual entry and save time, check out Data2CRM - an automated migration tool that can transfer your attachments." +59944235,"In my react component I have added video tag like: + +``` + + +``` + +And I have added play button like: + +``` + + +``` + +This code is working for single video when using `ref` + +But i have multiple video in one page so + +How to use multiple ref in loop?",2020/01/28,"['https://Stackoverflow.com/questions/59944235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4316024/']","The file is serializable in theory (base64 for example) but it would probably make using the devtools harder or cause other unexpected side effects with that much data. + +I agree that it's valid to not store the actual file content in action payloads. + +You could save a hash of the file (or simply the name and a timestamp) and use this as a key to access the file in another type of storage if it becomes necessary to have the content. This would make time travel work again, but only if the actions are replayed in the same environment where the file content can be accessed.","I faced the same issue. +This is how had configured my store. + +``` +export default configureStore({ + reducer: { + vehicles: vehicleReducer, + }, + middleware: [...getDefaultMiddleware(), apiMiddleware], +}); + +``` + +Once I got rid of `getDefaultMiddleware`, the error was gone for me." +59944235,"In my react component I have added video tag like: + +``` + + +``` + +And I have added play button like: + +``` + + +``` + +This code is working for single video when using `ref` + +But i have multiple video in one page so + +How to use multiple ref in loop?",2020/01/28,"['https://Stackoverflow.com/questions/59944235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4316024/']","The file is serializable in theory (base64 for example) but it would probably make using the devtools harder or cause other unexpected side effects with that much data. + +I agree that it's valid to not store the actual file content in action payloads. + +You could save a hash of the file (or simply the name and a timestamp) and use this as a key to access the file in another type of storage if it becomes necessary to have the content. This would make time travel work again, but only if the actions are replayed in the same environment where the file content can be accessed.","```js +export default configureStore({ + reducer: { + \\Put your reducers here + }, + middleware:getDefaultMiddleware({ + \\this way you don't remove the middlewares + serializableCheck:false, + }), +}); + +```" +59944235,"In my react component I have added video tag like: + +``` + + +``` + +And I have added play button like: + +``` + + +``` + +This code is working for single video when using `ref` + +But i have multiple video in one page so + +How to use multiple ref in loop?",2020/01/28,"['https://Stackoverflow.com/questions/59944235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4316024/']","```js +export default configureStore({ + reducer: { + \\Put your reducers here + }, + middleware:getDefaultMiddleware({ + \\this way you don't remove the middlewares + serializableCheck:false, + }), +}); + +```","I faced the same issue. +This is how had configured my store. + +``` +export default configureStore({ + reducer: { + vehicles: vehicleReducer, + }, + middleware: [...getDefaultMiddleware(), apiMiddleware], +}); + +``` + +Once I got rid of `getDefaultMiddleware`, the error was gone for me." +18834713,"I need to allow certain users limited access to the lab server. The server is RHEL 5.6. However, I don't want to give them the root access. Basically, we have configured a LDAP server where all the users have centralized NFS and LDAP login from any of the client machines in the network. So, the LDAP users home area is located in /home/users in the server. I need to give access to only this folder to a certain user. + +If I edit the visudo file and add the following line in the RHEL server, will I be able to accomplish what am looking for? + +``` +user1, %operator ALL= /home/users + +```",2013/09/16,"['https://Stackoverflow.com/questions/18834713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1742825/']","When you are authenicating users with ldap and nfs mounted share, as such users of ldap or without ldap would be restricted to work in their home directory only. + +Thanks & Regards, + +Alok Thaker","Basically, as you giving all users access as users not as root hence all users will not have root access either using local authentication or remote authentication. I hope the users don't know your root password. :) + +SUDO is used only when you want to give some users privilege to run the command as root like a normal user will not be able to do the command ""service network restart"" but if you allow the user have sudo privileges, he will be able to do it." +452083,"I have just installed the latest Ubuntu 14.04 and I would like to install KDE along side my Gnome/Unity that I have now. How can I do this? + +Thanks!",2014/04/21,"['https://askubuntu.com/questions/452083', 'https://askubuntu.com', 'https://askubuntu.com/users/2975/']","You can install kde 4.12 easily on ubuntu 14.04 , open terminal : + +``` +sudo apt-get update +sudo apt-get install kubuntu-desktop + +``` + +Enjoy using **KDE**","Good answers here, but when installing you'll be asked a question in a terminal about choosing between lightdm and kdm. Either works well and lightdm should be selected by default, just press [ENTER}. + +Reboot/logout, and when you go to login again, you'll see a ""gear"" icon next to your password window. Click it and select KDE, now enter your password. + +This option will be remembered until you decide to change." +40447377,"I have a problem sorting a table. + +My table HTML is this: + +``` + + + + + + + + + +
            31
            24
            + +``` + +And I want it to look like this: + +``` + + + + + + + + + +
            12
            34
            + +``` + +Here is my current sorting code: + +```js +var rows = $('tr'); + +rows.eq(0).find('td').sort(function(a, b) { + return $.text([a]) > $.text([b]) ? 1 : -1; +}).each(function(newIndex) { + var originalIndex = $(this).index(); + rows.each(function() { +var td = $(this).find('td'); +if (originalIndex !== newIndex) + td.eq(originalIndex).insertAfter(td.eq(newIndex)); +}); + }); +``` + +```html + + + + + + + + + + +
            31
            24
            +``` + +The code only sorts by separate rows. I can't use any plugins and I need to do this with jquery or javascript. Can anyone suggestion how to make it work?",2016/11/06,"['https://Stackoverflow.com/questions/40447377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7121533/']","It's simple. + +1. Store all the numbers from `td` in an array. +2. Sort the array. +3. Modify the `td`s according to array. + +Here's how you'd do it in JS: + +``` +var tds= [].slice.call(document.getElementsByTagName(""td"")); //Find and store in array +var tdsa=tds.map(function (a) {return Number(a.innerHTML);}); //Take the innerHTMLs +tdsa.sort(); //Sort it +tds.forEach(function(a,i) {a.innerHTML=tdsa[i]}); //Modify 's innerHTML + +```","Try this - method: + +* get the items of the table into an array +* sort the array +* rebuild the rows + +```js +var columnCount = 2; +var items = []; +$('td').each(function (idx, obj) { + items.push(obj.innerHTML); +}); +items.sort(); +$('table tr').remove(); + +for(var i=0; i'; + }; + row += ''; + $('table').append(row); +}; +``` + +```html + + + + + + + + + + +
            31
            24
            +```" +34575731,"I am unable to disable/remove some extensions in Visual Studio 2015, including extensions like the ""Multilingual App Toolkit"" and ""MySQL for Visual Studio"" that I have installed myself. In several cases, both the `Disable` and `Uninstall` buttons are grayed out in the Extensions and Updates manager. + +[![Visual Studio Extensions - showing greyed out disable and uninstall options](https://i.stack.imgur.com/S3e35.png)](https://i.stack.imgur.com/S3e35.png) + +I've tried starting VS as administrator, and also launching VS in safe mode (using `devenv.exe /safemode`). + +Why is it not possible to disable some extensions, and what is the correct way to safely disable them?",2016/01/03,"['https://Stackoverflow.com/questions/34575731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1624894/']",You can manage extensions from Visual Studio only if they use standard .vsix installer. If they use other installer like .msi you typically use Control Panel - Programs and Features to uninstall them.,"Windows *Control Panel -> Programs and Features* can uninstall most of those addons. + +For anything else, there is an awesome simple utility: [Total-Uninstaller](https://github.com/tsasioglu/Total-Uninstaller). It can uninstall virtually anything, including hidden stuff. + +Warning: uninstalling too much can make Visual Studio crashing / unusable and can even damage Windows installation. Make sure to back up important info before proceeding." +18861370,"Need to remove everything between .jpg and > on all instances like these below: + +* .jpg|500|756|20121231-just-some-image-3.jpg)%> +* .jpg|500|729|)%> +* .jpg|500|700|)%> +* .jpg|500|756|test-43243.jpg)%> + +So everything becomes .jpg> + +Any suggestions using preg\_replace?",2013/09/17,"['https://Stackoverflow.com/questions/18861370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1550196/']","``` +preg_replace('/\.jpg[^>]+>/', '.jpg>', $your_string); + +```","``` +$str = '.jpg|500|756|20121231-just-some-image-3.jpg)%>'; +preg_replace('/[^\.jpg][^>]+/', '', $str); + +```" +149106,"Is anyone familiar with this error? It is causing TinyMCE to break in my Wordpress theme. + +In console it gives me these two errors both seem to originate from wp-admin/post-new.php + +> +> Uncaught ReferenceError:switchEditors is not defined +> +> +> Uncaught TypeError: undefined is not a function /wp-admin/load-scripts.php?c=0&load%5B%5D=hoverIntent,…editor,quickt&load%5B%5D=ags,wplink,wp-fullscreen,media-upload&ver=3.9.1:2 +> +> +> + +![enter image description here](https://i.stack.imgur.com/p3rLM.png) + +Both the Visual and Smart tabs break, becoming unclickable, and the TinyMCE toolbar disappears.",2014/06/10,"['https://wordpress.stackexchange.com/questions/149106', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/45362/']","it might me entirely different solution that i am providing but it solved the problem for me. + +I followed these steps: + +1. Open the user that is getting error. (Wordpress admin menu > users > your profile) +2. Changed the setting of ""Disable the visual editor when writing"" and saved the settings +3. Again disabled this feature and saved the settings +4. Boom. my editor is back. + +Maybe it could solve someone else problem. + +Regards, + +Rao","You are most probably having a conflict with some plugin or the theme (bad javascript usually). If you got some kind of an adblocker, this might be another reason too, so you'd better check them all and see if it is a browser-sensitive problem." +149106,"Is anyone familiar with this error? It is causing TinyMCE to break in my Wordpress theme. + +In console it gives me these two errors both seem to originate from wp-admin/post-new.php + +> +> Uncaught ReferenceError:switchEditors is not defined +> +> +> Uncaught TypeError: undefined is not a function /wp-admin/load-scripts.php?c=0&load%5B%5D=hoverIntent,…editor,quickt&load%5B%5D=ags,wplink,wp-fullscreen,media-upload&ver=3.9.1:2 +> +> +> + +![enter image description here](https://i.stack.imgur.com/p3rLM.png) + +Both the Visual and Smart tabs break, becoming unclickable, and the TinyMCE toolbar disappears.",2014/06/10,"['https://wordpress.stackexchange.com/questions/149106', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/45362/']","it might me entirely different solution that i am providing but it solved the problem for me. + +I followed these steps: + +1. Open the user that is getting error. (Wordpress admin menu > users > your profile) +2. Changed the setting of ""Disable the visual editor when writing"" and saved the settings +3. Again disabled this feature and saved the settings +4. Boom. my editor is back. + +Maybe it could solve someone else problem. + +Regards, + +Rao","You can disable concatenation by defining `CONCATENATE_SCRIPTS` constant to false. In `wp-config.php` would be fitting: + +``` +define('CONCATENATE_SCRIPTS', false); + +``` + +W3TC shouldn't affect anything on admin side." +149106,"Is anyone familiar with this error? It is causing TinyMCE to break in my Wordpress theme. + +In console it gives me these two errors both seem to originate from wp-admin/post-new.php + +> +> Uncaught ReferenceError:switchEditors is not defined +> +> +> Uncaught TypeError: undefined is not a function /wp-admin/load-scripts.php?c=0&load%5B%5D=hoverIntent,…editor,quickt&load%5B%5D=ags,wplink,wp-fullscreen,media-upload&ver=3.9.1:2 +> +> +> + +![enter image description here](https://i.stack.imgur.com/p3rLM.png) + +Both the Visual and Smart tabs break, becoming unclickable, and the TinyMCE toolbar disappears.",2014/06/10,"['https://wordpress.stackexchange.com/questions/149106', 'https://wordpress.stackexchange.com', 'https://wordpress.stackexchange.com/users/45362/']","it might me entirely different solution that i am providing but it solved the problem for me. + +I followed these steps: + +1. Open the user that is getting error. (Wordpress admin menu > users > your profile) +2. Changed the setting of ""Disable the visual editor when writing"" and saved the settings +3. Again disabled this feature and saved the settings +4. Boom. my editor is back. + +Maybe it could solve someone else problem. + +Regards, + +Rao","This fixed my issue - I added this line to the bottom of wp-config.php and BOOM! + +define('CONCATENATE\_SCRIPTS', false);" +70809910,"I have a function that is intended to rotate polygons by 5 degrees left or right and return their new points. This function is as follows, along with the function `player_center` that it requires. + +``` + +# finds center of player shape +# finds slope and midpoint of each vertice-midpoint line on the longer sides, +# then the intercept of them all +def player_center(player): + left_mid = line_midpoint(player[0], player[1]) + right_mid = line_midpoint(player[0], player[2]) + + left_mid_slope = line_slope(left_mid, player[2]) + right_mid_slope = line_slope(right_mid, player[1]) + + left_mid_line = find_equation(player[2], left_mid_slope, True) + right_mid_line = find_equation(player[1], right_mid_slope, True) + + standard_left_mid_line = slope_intercept_to_standard(left_mid_line[0], left_mid_line[1], left_mid_line[2]) + standard_right_mid_line = slope_intercept_to_standard(right_mid_line[0], right_mid_line[1], right_mid_line[2]) + + lines = sym.Matrix([standard_left_mid_line, standard_right_mid_line]) + + return (float(lines.rref()[0].row(0).col(2)[0]), float(lines.rref()[0].row(1).col(2)[0])) + +# rotates the player using SOHCAHTOA +# divides x coordinate by radius to find angle, then adds or subtracts increment of 5 to it depending on direction +# calculates the position of point at incremented angle, then appends to new set of points +# finally, new set is returned + +# direction; 1 is left, 0 is right +def rotate_player(player, direction): + increment = math.pi/36 # radian equivalent of 5 degrees + full_circle = 2 * math.pi # radian equivalent of 360 degrees + + center = player_center(player) + + new_player = [] + + for point in player: + radius = line_distance(point, center) + point_sin = (center[1] - point[1])/radius + while (point_sin > 1): + point_sin -= 1 + point_angle = math.asin(point_sin) + + if (direction == 1): + if ((point_angle+increment) > math.pi * 2): + new_angle = (point_angle+increment) - math.pi * 2 + else: + new_angle = point_angle + increment + else: + if ((point_angle-increment) < 0): + new_angle = 2 * math.pi + (point_angle-increment) + else: + new_angle = point_angle-increment + print(""The angle was {}"".format(math.degrees(point_angle))) + print(""The angle is now {}"".format(math.degrees(new_angle))) # print lines are for debug purposes + new_point = ((radius * math.cos(new_angle)) + center[0], -(radius * math.sin(new_angle)) + center[1]) + new_player.append(new_point) + + print(new_player) + return new_player + +``` + +The geometric functions that it relies on are all defined in this file here: + +``` +import math +import sympy as sym + +# shape is in form of list of tuples e.g [(1,1), (2,1), (1,0), (2,0)] +# angle is in degrees +# def rotate_shape(shape, angle): + +def line_distance(first_point, second_point): + return math.sqrt( (second_point[0] - first_point[0]) ** 2 + (second_point[1] - first_point[1]) ** 2) + +# undefined is represented by None in this program +def line_slope(first_point, second_point): + if (second_point[0] - first_point[0] == 0): + return None + elif (second_point[1] - first_point[1] == 0): + return 0 + else: + return (second_point[1] - first_point[1])/(second_point[0] - first_point[0]) + +def line_midpoint(first_point, second_point): + return ( (first_point[0] + second_point[0])/2, (first_point[1] + second_point[1])/2 ) + +def find_equation(coord_pair, slope, array_form): + # Array form useful for conversion into standard form + if (array_form == True): + if (slope == 0): + intercept = coord_pair[1] + return [0, 1, intercept] + elif (slope == None): + intercept = coord_pair[0] + return [1, 0, intercept] + else: + intercept = coord_pair[1] - (coord_pair[0] * slope) + return [slope, 1, intercept] + else: + + if (slope == 0): + intercept = coord_pair[1] + print(""y = {0}"".format(intercept)) + return + elif (slope == None): + intercept = coord_pair[0] + print(""x = {0}"".format(intercept)) + return + else: + intercept = coord_pair[1] - (coord_pair[0] * slope) + + if (intercept >= 0): + print(""y = {0}x + {1}"".format(slope, intercept)) + return + else: + print(""y = {0}x - {1}"".format(slope, intercept)) + +def find_perpendicular(slope): + if (slope == 0): + return None + elif (slope == None): + return 0 + else: + return -(1/slope) + +def find_perp_bisector(first_point, second_point): + # This function finds the perpendicular bisector between two points, using funcs made previously + midpoint = line_midpoint(first_point, second_point) + slope = line_slope(first_point, second_point) + return find_equation(midpoint, -(1/slope)) + +def find_perp_equation(x, y, m, array_form): + # returns the perpendicular equation of a given line + if (array_form == True): + return [find_perpendicular(x), y, m] + + else: + if (m >= 0): + print(""{0}y = {1}x + {2}"".format(y, find_perpendicular(x), m)) + else: + print(""{0}y = {1}x - {2}"".format(y, find_perpendicular(x), m)) + +def find_hyp(a, b): + return math.sqrt((a**2) + (b**2)) + +def find_tri_area(a, b, c): + # finds area of triangle using Heron's formula + semi = (a+b+c)/2 + return math.sqrt(semi * (semi - a) * (semi - b) * (semi - c) ) + +def r_tri_check(a, b, c): + if (a**2) + (b**2) != (c**2): + print(""This thing fake, bro."") + +def find_point_section(first_point, second_point, ratio): + # I coded this half a year ago and can't remember what for, but kept it here anyway. + # separtions aren't necessary, but good for code readability + first_numerator = (ratio[0] * second_point[0]) + (ratio[1] * first_point[0]) + second_numerator = (ratio[0] * second_point[1]) + (ratio[1] * first_point[1]) + return ( first_numerator/(ratio[0]+ratio[1]), second_numerator/(ratio[0] + ratio[1])) + +def slope_intercept_to_standard(x, y, b): + # x and y are the coeffients of the said variables, for example 5y = 3x + 8 would be inputted as (3, 5, 8) + if (x == 0): + return [0, 1, b] + elif (y == 0): + return [x, 0, b] + else: + return [x, -y, -b] + +``` + +It mathematically seems sound, but when I try to apply it, all hell breaks loose. +For example when trying to apply it with the set `polygon_points` equal to `[(400, 300), (385, 340), (415, 340)]`, All hell breaks loose. + +An example of the output among repeated calls to the function upon `polygon_points`(outputs manually spaced for clarity): + +``` +The angle was 90.0 +The angle is now 95.0 +The angle was -41.633539336570394 + +The angle is now -36.633539336570394 +The angle was -41.63353933657017 +The angle is now -36.63353933657017 + +The angle was 64.4439547804165 +The angle is now 69.4439547804165 +The angle was -64.44395478041695 + +The angle is now -59.44395478041695 +The angle was -64.44395478041623 +The angle is now -59.44395478041624 + +The angle was 80.94458887142648 +The angle is now 85.94458887142648 +The angle was -80.9445888714264 + +The angle is now -75.9445888714264 +The angle was -80.94458887142665 +The angle is now -75.94458887142665 + +``` + +Can anyone explain this?",2022/01/22,"['https://Stackoverflow.com/questions/70809910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17769030/']","Too much irrelevant code, a lot of magic like this `while (point_sin > 1): point_sin -= 1` - so hard to reproduce. + +To rotate point around some center, you need just this (where `cos(fi), sin(fi)` are precalculated value in your case): + +``` +new_x = center_x + (old_x - center_x) * cos(fi) - (old_y - center_y) * sin(fi) +new_y = center_y + (old_x - center_x) * sin(fi) + (old_y - center_y) * cos(fi) + +```","This is a built-in capability of RegularPolygon in SymPy: + +``` +>>> from sympy import RegularPolygon, rad +>>> p = RegularPolygon((0,0), 1, 5) +>>> p.vertices[0] +Point2D(1, 0) +>>> p.rotate(rad(30)) # or rad(-30) +>>> p.vertices[0] +Point2D(sqrt(3)/2, 1/2) + +```" +23576155,"I’m trying to learn a few things about scripting and Linux systems, so I started learning `bash` scripting. + +For an exercise, I’m trying to program a script that would install all programs that user chooses. + +I worked out a skeleton of installation part, but I’m stuck at determining users answer. + +Here is my code: + +``` +#!/bin/bash + +declare -a instal_list=(""Gimp"" ""VLC"" ""Gedit"") + +for ((i=0; i<3; i++)) +do + +echo ""Do you want to install ${instal_list[i]} ?"" +echo +read answer_${instal_list[i]} + +if [[ $answer_${instal_list[i]} == ""yes"" ]] || [[ $answer_${instal_list[i]} == ""Yes"" ]] || [[ $answer_${instal_list[i]} == ""YES"" ]]; +then + + instal+="" ${install_list[i]}"" + +fi + +done + +``` + +My problem is in my `if` statement. Inside of it, I’m trying to evaluate if users answer is yes. Problem is in `answer_${instal_list[i]}` variable. + +I don't know how to explain what I mean, so I will try to explain it on example. + +Example : + +* We run the script, and the script asks us if we want install Gimp. +* We say yes, and the script stores that answer in variable ""answer\_${instal\_list[1]}"" (""answer\_Gimp""). +* My problem is when I try to call back that variable (""answer\_Gimp""). += To call it I use ""$answer\_${instal\_list[1]}"" line, but the shell doesn’t recognize that command as answer\_Gimp. + +So how can I call back variable `answer_${instal_list[1]}` so that shell would recognize it as ""answer\_Gimp""?",2014/05/10,"['https://Stackoverflow.com/questions/23576155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3622290/']","``` +thing=""Gimp"" +answer_Gimp=""Yes"" + +variableName=""answer_$thing"" +echo ""The value of $variableName is ${!variableName}"" + +```","If you have bash version 4, you can use an associative array: + +``` +declare -a instal_list=(""Gimp"" ""VLC"" ""Gedit"") +declare -a to_install +declare -A answers + +for prog in ""${instal_list[@]}""; do + read -p ""Do you want to install $prog? [y/n] "" answer[""$prog""] + if [[ ""${answer[""$prog""],,}"" == y* ]]; then + to_install+=( ""$prog"" ) + fi +done + +echo you want to install: +printf "" %s\n"" ""${to_install[@]}"" + +``` + +Looking at that, I don't see why you need to keep the answers in an array. But if you do, that's how you'd do it." +32806744,"First, It is not just duplicate. None of answers from following questions are working for me. + + + + + +I've just updated all my packages using Nuget Package Manager and I started receiving this error. + +**Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)** + +My Package Config has: + +``` + + +``` + +Web.config includes this piece of code: + +``` + + + + + +``` + +Properties from Reference for `Newtonsoft.Json` + +[![enter image description here](https://i.stack.imgur.com/K5OMM.png)](https://i.stack.imgur.com/K5OMM.png) + +According to the answers from the similar questions, I have tried followings: + +* Reinstalling package using `Update-Package –reinstall Newtonsoft.Json` +* Removing `dependentAssembly` config from `Web.config` for `Newtonsoft.Json` +* Changing `newVersion` to `6.0.0.0` and `7.0.0.0` in `dependentAssembly`. Doing so gave birth to new error. +* Also tried `Get-Project -All | Add-BindingRedirect`. It changes `newVersion` for `Newtonsoft.Json` to `4.5.0.0`. But issue remains unresolved. + +Please help me fixing this.",2015/09/27,"['https://Stackoverflow.com/questions/32806744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306394/']","I know this is old, but I just ran into the same problem. My issue was that multiple projects in the solution used Newtonsoft.Json, but some were at different versions. I updated all of them to the most recent (9.0.1 as I type) and the problem went away. + +Anyway... if anyone is still dealing with this, make sure to update the package in EVERY project in the solution. + +HTH","run this command in the package manager console: + +``` +PM> Install-Package Newtonsoft.Json -Version 6.0.1 + +```" +32806744,"First, It is not just duplicate. None of answers from following questions are working for me. + + + + + +I've just updated all my packages using Nuget Package Manager and I started receiving this error. + +**Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)** + +My Package Config has: + +``` + + +``` + +Web.config includes this piece of code: + +``` + + + + + +``` + +Properties from Reference for `Newtonsoft.Json` + +[![enter image description here](https://i.stack.imgur.com/K5OMM.png)](https://i.stack.imgur.com/K5OMM.png) + +According to the answers from the similar questions, I have tried followings: + +* Reinstalling package using `Update-Package –reinstall Newtonsoft.Json` +* Removing `dependentAssembly` config from `Web.config` for `Newtonsoft.Json` +* Changing `newVersion` to `6.0.0.0` and `7.0.0.0` in `dependentAssembly`. Doing so gave birth to new error. +* Also tried `Get-Project -All | Add-BindingRedirect`. It changes `newVersion` for `Newtonsoft.Json` to `4.5.0.0`. But issue remains unresolved. + +Please help me fixing this.",2015/09/27,"['https://Stackoverflow.com/questions/32806744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306394/']","After trying much of the above (and some other posts), I uninstalled with the package manager all of the following from the project affected: + +``` +Microsoft.AspNet.WebApi +Microsoft.AspNet.Client +Microsoft.AspNet.Core +Microsoft.AspNet.WebHost +Newtonsoft.Json + +``` + +Then reinstalled Microsoft.AspNet.WebApi, which auto installed .Client, .Core, .WebHost, .Json.","check the 'Newtonsoft.Json' version in the project references. Add that version in the Web config. It will work. +For Example: +your Webconfig look like this: + +``` + + + + + +``` + +If your version in References is '9.0.0.0' +change to this: + +``` + + + + + +```" +32806744,"First, It is not just duplicate. None of answers from following questions are working for me. + + + + + +I've just updated all my packages using Nuget Package Manager and I started receiving this error. + +**Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)** + +My Package Config has: + +``` + + +``` + +Web.config includes this piece of code: + +``` + + + + + +``` + +Properties from Reference for `Newtonsoft.Json` + +[![enter image description here](https://i.stack.imgur.com/K5OMM.png)](https://i.stack.imgur.com/K5OMM.png) + +According to the answers from the similar questions, I have tried followings: + +* Reinstalling package using `Update-Package –reinstall Newtonsoft.Json` +* Removing `dependentAssembly` config from `Web.config` for `Newtonsoft.Json` +* Changing `newVersion` to `6.0.0.0` and `7.0.0.0` in `dependentAssembly`. Doing so gave birth to new error. +* Also tried `Get-Project -All | Add-BindingRedirect`. It changes `newVersion` for `Newtonsoft.Json` to `4.5.0.0`. But issue remains unresolved. + +Please help me fixing this.",2015/09/27,"['https://Stackoverflow.com/questions/32806744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306394/']","After trying much of the above (and some other posts), I uninstalled with the package manager all of the following from the project affected: + +``` +Microsoft.AspNet.WebApi +Microsoft.AspNet.Client +Microsoft.AspNet.Core +Microsoft.AspNet.WebHost +Newtonsoft.Json + +``` + +Then reinstalled Microsoft.AspNet.WebApi, which auto installed .Client, .Core, .WebHost, .Json.","In my case, the following code was present in my local debug version of the solution, but not in my live server version of code. Adding the code to my server Web.config file fixed the problem. + +``` + + + + + + + + + + + + +```" +32806744,"First, It is not just duplicate. None of answers from following questions are working for me. + + + + + +I've just updated all my packages using Nuget Package Manager and I started receiving this error. + +**Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)** + +My Package Config has: + +``` + + +``` + +Web.config includes this piece of code: + +``` + + + + + +``` + +Properties from Reference for `Newtonsoft.Json` + +[![enter image description here](https://i.stack.imgur.com/K5OMM.png)](https://i.stack.imgur.com/K5OMM.png) + +According to the answers from the similar questions, I have tried followings: + +* Reinstalling package using `Update-Package –reinstall Newtonsoft.Json` +* Removing `dependentAssembly` config from `Web.config` for `Newtonsoft.Json` +* Changing `newVersion` to `6.0.0.0` and `7.0.0.0` in `dependentAssembly`. Doing so gave birth to new error. +* Also tried `Get-Project -All | Add-BindingRedirect`. It changes `newVersion` for `Newtonsoft.Json` to `4.5.0.0`. But issue remains unresolved. + +Please help me fixing this.",2015/09/27,"['https://Stackoverflow.com/questions/32806744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306394/']","After trying much of the above (and some other posts), I uninstalled with the package manager all of the following from the project affected: + +``` +Microsoft.AspNet.WebApi +Microsoft.AspNet.Client +Microsoft.AspNet.Core +Microsoft.AspNet.WebHost +Newtonsoft.Json + +``` + +Then reinstalled Microsoft.AspNet.WebApi, which auto installed .Client, .Core, .WebHost, .Json.","Run `Update-Package Newtonsoft.Json -Reinstall` + +It should remove the reference to your 4.5 version, and reinstall the newer version referenced in your package.config. It will also update the binding redirect, which should then be as follows: + +```xml + + + + + +``` + +Since you said in your question that you already tried this, you might want to *first* try removing the existing reference manually. You might also want to make sure the files aren't read-only on disk, or otherwise locked by source control." +32806744,"First, It is not just duplicate. None of answers from following questions are working for me. + + + + + +I've just updated all my packages using Nuget Package Manager and I started receiving this error. + +**Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)** + +My Package Config has: + +``` + + +``` + +Web.config includes this piece of code: + +``` + + + + + +``` + +Properties from Reference for `Newtonsoft.Json` + +[![enter image description here](https://i.stack.imgur.com/K5OMM.png)](https://i.stack.imgur.com/K5OMM.png) + +According to the answers from the similar questions, I have tried followings: + +* Reinstalling package using `Update-Package –reinstall Newtonsoft.Json` +* Removing `dependentAssembly` config from `Web.config` for `Newtonsoft.Json` +* Changing `newVersion` to `6.0.0.0` and `7.0.0.0` in `dependentAssembly`. Doing so gave birth to new error. +* Also tried `Get-Project -All | Add-BindingRedirect`. It changes `newVersion` for `Newtonsoft.Json` to `4.5.0.0`. But issue remains unresolved. + +Please help me fixing this.",2015/09/27,"['https://Stackoverflow.com/questions/32806744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306394/']","I know this is old, but I just ran into the same problem. My issue was that multiple projects in the solution used Newtonsoft.Json, but some were at different versions. I updated all of them to the most recent (9.0.1 as I type) and the problem went away. + +Anyway... if anyone is still dealing with this, make sure to update the package in EVERY project in the solution. + +HTH","check the 'Newtonsoft.Json' version in the project references. Add that version in the Web config. It will work. +For Example: +your Webconfig look like this: + +``` + + + + + +``` + +If your version in References is '9.0.0.0' +change to this: + +``` + + + + + +```" +32806744,"First, It is not just duplicate. None of answers from following questions are working for me. + + + + + +I've just updated all my packages using Nuget Package Manager and I started receiving this error. + +**Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)** + +My Package Config has: + +``` + + +``` + +Web.config includes this piece of code: + +``` + + + + + +``` + +Properties from Reference for `Newtonsoft.Json` + +[![enter image description here](https://i.stack.imgur.com/K5OMM.png)](https://i.stack.imgur.com/K5OMM.png) + +According to the answers from the similar questions, I have tried followings: + +* Reinstalling package using `Update-Package –reinstall Newtonsoft.Json` +* Removing `dependentAssembly` config from `Web.config` for `Newtonsoft.Json` +* Changing `newVersion` to `6.0.0.0` and `7.0.0.0` in `dependentAssembly`. Doing so gave birth to new error. +* Also tried `Get-Project -All | Add-BindingRedirect`. It changes `newVersion` for `Newtonsoft.Json` to `4.5.0.0`. But issue remains unresolved. + +Please help me fixing this.",2015/09/27,"['https://Stackoverflow.com/questions/32806744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306394/']","Run `Update-Package Newtonsoft.Json -Reinstall` + +It should remove the reference to your 4.5 version, and reinstall the newer version referenced in your package.config. It will also update the binding redirect, which should then be as follows: + +```xml + + + + + +``` + +Since you said in your question that you already tried this, you might want to *first* try removing the existing reference manually. You might also want to make sure the files aren't read-only on disk, or otherwise locked by source control.","1. In your VS solution explorer, remove the Newtonsoft.Json reference. +2. Download the 6.0 binary files at Newtonsoft binary files [here](https://github.com/JamesNK/Newtonsoft.Json/releases/download/6.0.8/Json60r8.zip) +3. Extract the files +4. Add the Newtonsoft library manually. From Visual Studio, right click Reference and select Add Reference +5. Click Browse +6. Navigate to the extracted files under Net45 and select Newtonsoft.Json.dll +7. If it does not work try using Net40 instead by going through the whole procedure again." +32806744,"First, It is not just duplicate. None of answers from following questions are working for me. + + + + + +I've just updated all my packages using Nuget Package Manager and I started receiving this error. + +**Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)** + +My Package Config has: + +``` + + +``` + +Web.config includes this piece of code: + +``` + + + + + +``` + +Properties from Reference for `Newtonsoft.Json` + +[![enter image description here](https://i.stack.imgur.com/K5OMM.png)](https://i.stack.imgur.com/K5OMM.png) + +According to the answers from the similar questions, I have tried followings: + +* Reinstalling package using `Update-Package –reinstall Newtonsoft.Json` +* Removing `dependentAssembly` config from `Web.config` for `Newtonsoft.Json` +* Changing `newVersion` to `6.0.0.0` and `7.0.0.0` in `dependentAssembly`. Doing so gave birth to new error. +* Also tried `Get-Project -All | Add-BindingRedirect`. It changes `newVersion` for `Newtonsoft.Json` to `4.5.0.0`. But issue remains unresolved. + +Please help me fixing this.",2015/09/27,"['https://Stackoverflow.com/questions/32806744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306394/']","I had this error myself, and first used `Update-Package –reinstall Newtonsoft.Json -IncludePrerelease` it didn't work, then used `Install-Package Newtonsoft.Json` . it worked.","run this command in the package manager console: + +``` +PM> Install-Package Newtonsoft.Json -Version 6.0.1 + +```" +32806744,"First, It is not just duplicate. None of answers from following questions are working for me. + + + + + +I've just updated all my packages using Nuget Package Manager and I started receiving this error. + +**Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)** + +My Package Config has: + +``` + + +``` + +Web.config includes this piece of code: + +``` + + + + + +``` + +Properties from Reference for `Newtonsoft.Json` + +[![enter image description here](https://i.stack.imgur.com/K5OMM.png)](https://i.stack.imgur.com/K5OMM.png) + +According to the answers from the similar questions, I have tried followings: + +* Reinstalling package using `Update-Package –reinstall Newtonsoft.Json` +* Removing `dependentAssembly` config from `Web.config` for `Newtonsoft.Json` +* Changing `newVersion` to `6.0.0.0` and `7.0.0.0` in `dependentAssembly`. Doing so gave birth to new error. +* Also tried `Get-Project -All | Add-BindingRedirect`. It changes `newVersion` for `Newtonsoft.Json` to `4.5.0.0`. But issue remains unresolved. + +Please help me fixing this.",2015/09/27,"['https://Stackoverflow.com/questions/32806744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306394/']",Add Newtonsoft reference in my MVC project solves the problem for me.,"run this command in the package manager console: + +``` +PM> Install-Package Newtonsoft.Json -Version 6.0.1 + +```" +32806744,"First, It is not just duplicate. None of answers from following questions are working for me. + + + + + +I've just updated all my packages using Nuget Package Manager and I started receiving this error. + +**Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)** + +My Package Config has: + +``` + + +``` + +Web.config includes this piece of code: + +``` + + + + + +``` + +Properties from Reference for `Newtonsoft.Json` + +[![enter image description here](https://i.stack.imgur.com/K5OMM.png)](https://i.stack.imgur.com/K5OMM.png) + +According to the answers from the similar questions, I have tried followings: + +* Reinstalling package using `Update-Package –reinstall Newtonsoft.Json` +* Removing `dependentAssembly` config from `Web.config` for `Newtonsoft.Json` +* Changing `newVersion` to `6.0.0.0` and `7.0.0.0` in `dependentAssembly`. Doing so gave birth to new error. +* Also tried `Get-Project -All | Add-BindingRedirect`. It changes `newVersion` for `Newtonsoft.Json` to `4.5.0.0`. But issue remains unresolved. + +Please help me fixing this.",2015/09/27,"['https://Stackoverflow.com/questions/32806744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306394/']","I know this is old, but I just ran into the same problem. My issue was that multiple projects in the solution used Newtonsoft.Json, but some were at different versions. I updated all of them to the most recent (9.0.1 as I type) and the problem went away. + +Anyway... if anyone is still dealing with this, make sure to update the package in EVERY project in the solution. + +HTH","1. In your VS solution explorer, remove the Newtonsoft.Json reference. +2. Download the 6.0 binary files at Newtonsoft binary files [here](https://github.com/JamesNK/Newtonsoft.Json/releases/download/6.0.8/Json60r8.zip) +3. Extract the files +4. Add the Newtonsoft library manually. From Visual Studio, right click Reference and select Add Reference +5. Click Browse +6. Navigate to the extracted files under Net45 and select Newtonsoft.Json.dll +7. If it does not work try using Net40 instead by going through the whole procedure again." +32806744,"First, It is not just duplicate. None of answers from following questions are working for me. + + + + + +I've just updated all my packages using Nuget Package Manager and I started receiving this error. + +**Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)** + +My Package Config has: + +``` + + +``` + +Web.config includes this piece of code: + +``` + + + + + +``` + +Properties from Reference for `Newtonsoft.Json` + +[![enter image description here](https://i.stack.imgur.com/K5OMM.png)](https://i.stack.imgur.com/K5OMM.png) + +According to the answers from the similar questions, I have tried followings: + +* Reinstalling package using `Update-Package –reinstall Newtonsoft.Json` +* Removing `dependentAssembly` config from `Web.config` for `Newtonsoft.Json` +* Changing `newVersion` to `6.0.0.0` and `7.0.0.0` in `dependentAssembly`. Doing so gave birth to new error. +* Also tried `Get-Project -All | Add-BindingRedirect`. It changes `newVersion` for `Newtonsoft.Json` to `4.5.0.0`. But issue remains unresolved. + +Please help me fixing this.",2015/09/27,"['https://Stackoverflow.com/questions/32806744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306394/']","Run `Update-Package Newtonsoft.Json -Reinstall` + +It should remove the reference to your 4.5 version, and reinstall the newer version referenced in your package.config. It will also update the binding redirect, which should then be as follows: + +```xml + + + + + +``` + +Since you said in your question that you already tried this, you might want to *first* try removing the existing reference manually. You might also want to make sure the files aren't read-only on disk, or otherwise locked by source control.","run this command in the package manager console: + +``` +PM> Install-Package Newtonsoft.Json -Version 6.0.1 + +```" +16982818,"(I'm not sure about the correctness of title) + +I have an `numpy.array` `f` as follows: + +``` +# id frame x y z + +``` + +What I want to do is to extract the trajectories for some specific `id`. For `id==1` I get for instance: + +``` +f_1 = f[ f[:,0]==1 ] + +``` + +and get + +``` +array([[ 1. , 55. , 381.51 , -135.476 , 163.751 ], + [ 1. , 56. , 369.176 , -134.842 , 163.751 ], + [ 1. , 57. , 357.499 , -134.204 , 163.751 ], + [ 1. , 58. , 346.65 , -133.786 , 163.751 ], + [ 1. , 59. , 336.602 , -133.762 , 163.751 ], + [ 1. , 60. , 326.762 , -135.157 , 163.751 ], + [ 1. , 61. , 315.77 , -135.898 , 163.751 ], + [ 1. , 62. , 303.806 , -136.855 , 163.751 ], + [ 1. , 63. , 291.273 , -138.255 , 163.751 ], + [ 1. , 64. , 278.767 , -139.824 , 163.751 ], + [ 1. , 65. , 266.778 , -141.123 , 163.751 ], + [ 1. , 66. , 255.773 , -142.42 , 163.751 ], + [ 1. , 67. , 244.864 , -143.314 , 163.751 ]]) + +``` + +My problem is I' m not sure I understand how it works. Normally I was expecting something like: + +``` +f_1 = f[ f[:,0]==1, : ] + +``` + +which also works and makes more sense to me. (take all columns but only those rows that fulfill the required condition) + +Can someone explain why this form also works and what exactly happens? + +``` +f_1 = f[ f[:,0]==1 ] + +```",2013/06/07,"['https://Stackoverflow.com/questions/16982818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1213793/']","For a 2D array asking only one index returns the line (with all columns) corresponding to that index, so that: + +``` +np.all( a[0] == a[0,:] ) +#True + +``` + +When you do `a[0]==1` you get a boolean array, like: + +``` +b = a[0]==1 +#array([True, True, False, False, True], dtype=bool) + +``` + +Which you can use through fancy indexing to obtain all the lines whose index has a corresponding `True` value in `b`. In this example, doing: + +``` +c = a[ b ] + +``` + +will get lines corresponding to indices `[0,1,4]`. The same result would be obtained by passing directly these indices, like `c = a[ [0,1,4] ]`.","Quoting from the [Tentative Numpy Tutorial](http://wiki.scipy.org/Tentative_NumPy_Tutorial): + +> +> ...When fewer indices are provided than the number of axes, the missing indices are considered complete slices... +> +> +> + +So `f[f[:,0]==1]` gets translated to `f[f[:,0]==1,:]` (or equivalently, to `f[f[:,0]==1,...]`) which are all the same thing from programmers' perspective." +42574844,"[![enter image description here](https://i.stack.imgur.com/Iovci.png)](https://i.stack.imgur.com/Iovci.png) + +this is my project structure, Failed to load resource: the server responded with a status of 404 (), ShowDetail.jsp is not found, which path i need to give in Route templateURL ? + +[![enter image description here](https://i.stack.imgur.com/HKeeG.png)](https://i.stack.imgur.com/Iovci.png) + +When click on name i need to populate details on another page, + +i am using Server side(Spring MVC) Service to fetch details. + +My client side code is in below snippet + +```js +var App = angular.module(""myApp"", ['ngRoute', 'angularUtils.directives.dirPagination']); +App.config(['$routeProvider', + function($routeProvider, $locationProvider) { + $routeProvider. + when('/detail/:username', { + templateUrl: 'showDetail.jsp', + controller: 'detailController' + }); + } +]); +angular.module('myApp').controller(""myController"", function($scope, $http) { + function getDetails(name) { + + $http.get(REST_SERVICE_URI + '/detail/' + name) + .then( + function(response) { + + self.detail = response.data; + + }, + function(errResponse) { + console.error('Error while fetching Users'); + + } + ); + + } +}); +``` + +```html + + + + + + + + + + + + +
            + + + + + + + + + + + + + + + + +
            +``` + +IndexController.java + +``` +@RequestMapping(value= ""/detail/{name}"",method = RequestMethod.GET) + public String getDetails(@PathVariable(""name"") String name) { + return ""showDetail""; + } + +``` + +MainController.java + +``` +@RequestMapping(value = ""/detail/{name}"", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) +public ResponseEntity getDetails(@PathVariable(""name"") String name) { + System.out.println(""Fetching detail with name "" + name); + Detail detail = userService.findByName(name); + if (detail == null) { + System.out.println(""Detail with id "" + name + "" not found""); + return new ResponseEntity(HttpStatus.NOT_FOUND); + } + return new ResponseEntity(detail, HttpStatus.OK); +} + +``` + +ServiceImpl.java + +``` +public Detail findByName(String name) { + for(Detail deatil : details){ + if(deatil.getFirstname().equalsIgnoreCase(name)){ + return deatil; + } + } + return null; +} + +``` + +These are my files, i am able to fetch details and getting in angularJS controller, when i click on a name field in table it should display corresponding details in another page, i can fetch the corresponding details, but page is not changing, i am having problem With routing in angular Js and SpringMVC, Please help me how to resolve this issue",2017/03/03,"['https://Stackoverflow.com/questions/42574844', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3639244/']","You can create a Map and map the integer to the String Value. + +Iterate the reference array and get it listed based on your order. + +Snippet: + +``` +Map maps = new HashMap(); +maps.put(1,""Red""); +maps.put(2,""White""); + +for(Integer a : values){ + System.out.println(maps.get(a)); +} + +```","You can use + +``` +Collections.swap(test,1,2); +Collections.swap(test,2,3); + +``` + +Documentation [Here](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int%29)" +54014687,"I have a DataFrame + +``` +>> test = pd.DataFrame({'A': ['a', 'b', 'b', 'b'], 'B': [1, 2, 3, 4], 'C': [np.nan, np.nan, np.nan, np.nan], 'D': [np.nan, np.nan, np.nan, np.nan]}) + A B C D +0 a 1 +1 b 2 +2 b 3 +3 b 4 + +``` + +I also have a dictionary, where `b` in `input_b` signifies that I'm only modifying rows where `row.A = b`. + +``` +>> input_b = {2: ['Moon', 'Elephant'], 4: ['Sun', 'Mouse']} + +``` + +How do I populate the DataFrame with values from the dictionary to get + +``` + A B C D +0 a 1 +1 b 2 Moon Elephant +2 b 3 +3 b 4 Sun Mouse + +```",2019/01/02,"['https://Stackoverflow.com/questions/54014687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6503670/']","This may not be the most efficient solution, but from what I understand it got the job done: + +``` +import pandas as pd +import numpy as np + +test = pd.DataFrame({'A': ['a', 'b', 'b', 'b'], 'B': [1, 2, 3, 4], + 'C': [np.nan, np.nan, np.nan, np.nan], + 'D': [np.nan, np.nan, np.nan, np.nan]}) + +input_b = {2: ['Moon', 'Elephant'], 4: ['Sun', 'Mouse']} + +for key, value in input_b.items(): + test.loc[test['B'] == key, ['C', 'D']] = value + +print(test) + +``` + +Yields: + +``` + A B C D +0 a 1 NaN NaN +1 b 2 Moon Elephant +2 b 3 NaN NaN +3 b 4 Sun Mouse + +``` + +This will get slower if the dictionary `input_b` gets too large (too many rows are being updated, too many iterations in the for loop), but should be relatively fast with small `input_b`'s even with large `test` dataframes. + +This answer also assumes the keys in the `input_b` dictionary refer to the values of the `B` column in the original dataframe, and will add repeated values in the `C` and `D` columns for repeated values in the `B` column.","Using `update` + +``` +test=test.set_index('B') +test.update(pd.DataFrame(input_b,index=['C','D']).T) +test=test.reset_index() +test + B A C D +0 1 a NaN NaN +1 2 b Moon Elephant +2 3 b NaN NaN +3 4 b Sun Mouse + +```" +54014687,"I have a DataFrame + +``` +>> test = pd.DataFrame({'A': ['a', 'b', 'b', 'b'], 'B': [1, 2, 3, 4], 'C': [np.nan, np.nan, np.nan, np.nan], 'D': [np.nan, np.nan, np.nan, np.nan]}) + A B C D +0 a 1 +1 b 2 +2 b 3 +3 b 4 + +``` + +I also have a dictionary, where `b` in `input_b` signifies that I'm only modifying rows where `row.A = b`. + +``` +>> input_b = {2: ['Moon', 'Elephant'], 4: ['Sun', 'Mouse']} + +``` + +How do I populate the DataFrame with values from the dictionary to get + +``` + A B C D +0 a 1 +1 b 2 Moon Elephant +2 b 3 +3 b 4 Sun Mouse + +```",2019/01/02,"['https://Stackoverflow.com/questions/54014687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6503670/']","This may not be the most efficient solution, but from what I understand it got the job done: + +``` +import pandas as pd +import numpy as np + +test = pd.DataFrame({'A': ['a', 'b', 'b', 'b'], 'B': [1, 2, 3, 4], + 'C': [np.nan, np.nan, np.nan, np.nan], + 'D': [np.nan, np.nan, np.nan, np.nan]}) + +input_b = {2: ['Moon', 'Elephant'], 4: ['Sun', 'Mouse']} + +for key, value in input_b.items(): + test.loc[test['B'] == key, ['C', 'D']] = value + +print(test) + +``` + +Yields: + +``` + A B C D +0 a 1 NaN NaN +1 b 2 Moon Elephant +2 b 3 NaN NaN +3 b 4 Sun Mouse + +``` + +This will get slower if the dictionary `input_b` gets too large (too many rows are being updated, too many iterations in the for loop), but should be relatively fast with small `input_b`'s even with large `test` dataframes. + +This answer also assumes the keys in the `input_b` dictionary refer to the values of the `B` column in the original dataframe, and will add repeated values in the `C` and `D` columns for repeated values in the `B` column.","You can use [`loc`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html) indexing after setting your index to `B`: + +``` +test = test.set_index('B') +test.loc[input_b, ['C', 'D']] = list(input_b.values()) +test = test.reset_index() + +print(test) + + B A C D +0 1 a NaN NaN +1 2 b Moon Elephant +2 3 b NaN NaN +3 4 b Sun Mouse + +```" +54014687,"I have a DataFrame + +``` +>> test = pd.DataFrame({'A': ['a', 'b', 'b', 'b'], 'B': [1, 2, 3, 4], 'C': [np.nan, np.nan, np.nan, np.nan], 'D': [np.nan, np.nan, np.nan, np.nan]}) + A B C D +0 a 1 +1 b 2 +2 b 3 +3 b 4 + +``` + +I also have a dictionary, where `b` in `input_b` signifies that I'm only modifying rows where `row.A = b`. + +``` +>> input_b = {2: ['Moon', 'Elephant'], 4: ['Sun', 'Mouse']} + +``` + +How do I populate the DataFrame with values from the dictionary to get + +``` + A B C D +0 a 1 +1 b 2 Moon Elephant +2 b 3 +3 b 4 Sun Mouse + +```",2019/01/02,"['https://Stackoverflow.com/questions/54014687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6503670/']","Using `apply` + +``` +test['C'] = test['B'].map(input_b).apply(lambda x: x[0] if type(x)==list else x) +test['D'] = test['B'].map(input_b).apply(lambda x: x[1] if type(x)==list else x) + +``` + +yields + +``` + A B C D +0 a 1 NaN NaN +1 b 2 Moon Elephant +2 b 3 NaN NaN +3 b 4 Sun Mouse + +```","Using `update` + +``` +test=test.set_index('B') +test.update(pd.DataFrame(input_b,index=['C','D']).T) +test=test.reset_index() +test + B A C D +0 1 a NaN NaN +1 2 b Moon Elephant +2 3 b NaN NaN +3 4 b Sun Mouse + +```" +54014687,"I have a DataFrame + +``` +>> test = pd.DataFrame({'A': ['a', 'b', 'b', 'b'], 'B': [1, 2, 3, 4], 'C': [np.nan, np.nan, np.nan, np.nan], 'D': [np.nan, np.nan, np.nan, np.nan]}) + A B C D +0 a 1 +1 b 2 +2 b 3 +3 b 4 + +``` + +I also have a dictionary, where `b` in `input_b` signifies that I'm only modifying rows where `row.A = b`. + +``` +>> input_b = {2: ['Moon', 'Elephant'], 4: ['Sun', 'Mouse']} + +``` + +How do I populate the DataFrame with values from the dictionary to get + +``` + A B C D +0 a 1 +1 b 2 Moon Elephant +2 b 3 +3 b 4 Sun Mouse + +```",2019/01/02,"['https://Stackoverflow.com/questions/54014687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6503670/']","Using `apply` + +``` +test['C'] = test['B'].map(input_b).apply(lambda x: x[0] if type(x)==list else x) +test['D'] = test['B'].map(input_b).apply(lambda x: x[1] if type(x)==list else x) + +``` + +yields + +``` + A B C D +0 a 1 NaN NaN +1 b 2 Moon Elephant +2 b 3 NaN NaN +3 b 4 Sun Mouse + +```","You can use [`loc`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html) indexing after setting your index to `B`: + +``` +test = test.set_index('B') +test.loc[input_b, ['C', 'D']] = list(input_b.values()) +test = test.reset_index() + +print(test) + + B A C D +0 1 a NaN NaN +1 2 b Moon Elephant +2 3 b NaN NaN +3 4 b Sun Mouse + +```" +3169164,"Using asp.net profiles, I've stored a complex type (class) and retrieved it. But it is returning a new object that is not initialized instead of null? Is this the expected behavior, if so how can I determine if I've saved data for the given user? + +should be some easy points for someone to pick up..",2010/07/02,"['https://Stackoverflow.com/questions/3169164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/254428/']","Your question is a little unclear, but I think you're asking why there's a non-null profile data object for a user who you haven't stored data for yet? + +[This article](http://msdn.microsoft.com/en-us/magazine/cc163724.aspx#S4) might hopefully clear it up for you. Some of the relevant bits: + +> +> A user profile is a collection of +> values that the ASP.NET 2.0 runtime +> groups as public fields of a +> dynamically generated class. The class +> is derived from a system-provided +> class and is extended with the +> addition of a few new members. The +> class doesn't have to be marked as +> Serializable, however its contents are +> persisted to the storage medium as +> individual properties. The storage +> occurs on a per-user basis and is +> preserved until an administrator +> deletes it. +> +> +> + +And further down: + +> +> When the application runs and a page +> is displayed, ASP.NET dynamically +> creates a profile object that contains +> properly typed data and assigns the +> current settings for the logged user +> to the properties defined in the data +> model. The profile object is added to +> the current HttpContext object and +> made available to pages through the +> Profile property. Assuming that the +> profile model has been defined to +> store a list of links as a collection, +> the following code snippet shows how +> to retrieve the list of favorite links +> that are created by a given user: +> +> +> ... +> +> +> This code assumes a Links property in +> the profile object that references a +> collection type. When the page is +> loaded, Links and other properties are +> initialized to contain the most +> recently stored values; when the page +> is unloaded their current contents are +> stored to the persistent medium. +> +> +> + +If you need to track whether a user has ever set profile data before, you might be able to use the [FindProfilesByUserName](http://msdn.microsoft.com/en-us/library/system.web.profile.sqlprofileprovider.findprofilesbyusername.aspx) function to check to see if a profile exists before you log them in.","A little late, but [UsingDefaultValue](https://learn.microsoft.com/en-us/dotnet/api/system.configuration.settingspropertyvalue.usingdefaultvalue?view=dotnet-plat-ext-3.1) tells you if the property value is coming from the user profile settings or if it's using a default. Another way you can get, kind of, the same result is using [Deserialized](https://learn.microsoft.com/en-us/dotnet/api/system.configuration.settingspropertyvalue.deserialized?view=dotnet-plat-ext-3.1)." +19778,"i am stuck to an issue where i have a List ID - list of Ids i have to find the LoginName of SPUser or SPGroup with the id in the ListID + +i tried the following but it threws exception as it did not find user when group id is there + +``` + foreach (var id in ID) + { + SPUser spUser = web.SiteUsers.GetByID(Convert.ToInt32(id)); + if (spUser != null) + { + lstUsers.Add(spUser.LoginName); + continue; + } + SPGroup spGroup = web.SiteGroups.GetByID(Convert.ToInt32(id )); + if (spGroup != null) + { + lstGroups.Add(spGroup.LoginName); + continue; + + } + + } + +``` + +please suggest what to do !!!",2011/09/20,"['https://sharepoint.stackexchange.com/questions/19778', 'https://sharepoint.stackexchange.com', 'https://sharepoint.stackexchange.com/users/2310/']","After breaking the inheritance of an item (item,list,web) you have to call `update()` on that object to make sure the settings are saved to the database. Once these are saved you can start adding/changing the permissions for that item. + +BreakRoleInheritance(false) will not copy the permissions of the parent to the new permissionset, supplying true will copy the permissions. + +**Updates** (see also Vedran Rasols [answer](https://sharepoint.stackexchange.com/questions/19771/powershell-item-level-permission-by-content-type/19792#19792)) + +* Using `foreach(item in list.items)` is not recommended, use an SPQuery to select the items and properties you really want, otherwise you will [fetch all data from the DB](https://web.archive.org/web/20120729085025/http://blog.dynatrace.com:80/2009/01/13/sharepoint-only-request-data-that-you-really-need/). See also this [MSDN Best Practices Article](https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-services/bb687949%28v=office.12%29#WorkingWithFoldersLists)! +* In theory you shouldn't have to call `update()`, but in some strange way in helped solving this issue. + +**bonus:** Note that when breaking inheritance on lists [the AllowUnsafeUpdate property of the parent web reverts to false](https://www.wictorwilen.se/Post/BreakRoleInheritance-and-AllowUnsafeUpdates.aspx), which can be annoying.","You need to take advantage of [SPQuery class](http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spquery.aspx). Using CAML query is much, much, much more faster then doing foreach. + +Here is script you 'really' want: + +``` +$webUrl = ""http://inside.national.com/Sales"" +$listName = ""2011Sales"" +$ctname = ""2011Sales"" +$groupname = ""Custom SP Group"" + +# Get web and list +$web = Get-SPWeb -Identity $webUrl +$list = $web.Lists[$listName] + +# Build CAML query +$caml=""{0}"" -f $ctname +$query = New-Object Microsoft.SharePoint.SPQuery +$query.Query = $caml +# Set scope to Recursive to include all items from folders and Document Sets +$query.ViewAttributes = ""Scope='Recursive'"" +# Get our data (only items with proper ct name) +$items = $list.GetItems($query) + +# Set Role Assignment +$spGroup = $web.SiteGroups[$groupname] +$spRoleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($spGroup) +$sproledefinition = $web.RoleDefinitions[""Contribute""] +$sproleassignment.RoleDefinitionBindings.Add($sproledefinition) + +foreach ($item in $items) { + # This is the fastest way of deleting all permissions + # First you restore inheritance + # And then you break it + $item.ResetRoleInheritance() + $item.BreakRoleInheritance($false) + + # Add new permission + $item.RoleAssignments.Add($spRoleAssignment) +} + +``` + +This script will update all items of desired Content Type (including items/files in folders and files in Document Sets). However it will not change permissions of parent Folders or Document Sets. + +I have tested this on my dev machine. Feel free to ask additional questions." +19778,"i am stuck to an issue where i have a List ID - list of Ids i have to find the LoginName of SPUser or SPGroup with the id in the ListID + +i tried the following but it threws exception as it did not find user when group id is there + +``` + foreach (var id in ID) + { + SPUser spUser = web.SiteUsers.GetByID(Convert.ToInt32(id)); + if (spUser != null) + { + lstUsers.Add(spUser.LoginName); + continue; + } + SPGroup spGroup = web.SiteGroups.GetByID(Convert.ToInt32(id )); + if (spGroup != null) + { + lstGroups.Add(spGroup.LoginName); + continue; + + } + + } + +``` + +please suggest what to do !!!",2011/09/20,"['https://sharepoint.stackexchange.com/questions/19778', 'https://sharepoint.stackexchange.com', 'https://sharepoint.stackexchange.com/users/2310/']","After breaking the inheritance of an item (item,list,web) you have to call `update()` on that object to make sure the settings are saved to the database. Once these are saved you can start adding/changing the permissions for that item. + +BreakRoleInheritance(false) will not copy the permissions of the parent to the new permissionset, supplying true will copy the permissions. + +**Updates** (see also Vedran Rasols [answer](https://sharepoint.stackexchange.com/questions/19771/powershell-item-level-permission-by-content-type/19792#19792)) + +* Using `foreach(item in list.items)` is not recommended, use an SPQuery to select the items and properties you really want, otherwise you will [fetch all data from the DB](https://web.archive.org/web/20120729085025/http://blog.dynatrace.com:80/2009/01/13/sharepoint-only-request-data-that-you-really-need/). See also this [MSDN Best Practices Article](https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-services/bb687949%28v=office.12%29#WorkingWithFoldersLists)! +* In theory you shouldn't have to call `update()`, but in some strange way in helped solving this issue. + +**bonus:** Note that when breaking inheritance on lists [the AllowUnsafeUpdate property of the parent web reverts to false](https://www.wictorwilen.se/Post/BreakRoleInheritance-and-AllowUnsafeUpdates.aspx), which can be annoying.","Here is the working code in case someone needs it. + +``` +$webUrl = ""http://inside.national.com/Sales"" +$web = Get-SPWeb $webUrl +$list = $web.Lists[""2011Sales""] +$ct = ""2011 Marketing"" +$spgroup = ""Custom SP Group"" +$rd=""Contribute"" + +foreach ($item in $list.items) { + If ($item.ContentType.Name -eq $ct) + { + $item.ResetRoleInheritance() # Not sure if this line is needed + $item.BreakRoleInheritance($false) # I tried $true but did not work, so leave it at $false + $item.SystemUpdate() # Very Important + + $group = $web.AllUsers[$spgroup] + $roledef = $web.RoleDefinitions[$rd] + $roleass = New-Object Microsoft.SharePoint.SPRoleAssignment($web.SiteGroups[$spgroup]) + $roleass.RoleDefinitionBindings.Add($roledef) + $item.RoleAssignments.Add($roleass) + $item.SystemUpdate() #Update item without changing the updated date + Write-Host $item.Name "" permission applied"" + } +} +$web.dispose() + +```" +10064581,"Since setting up my development environments on Mac OS X Lion (brand new macbook air purchased in January 2012), I have noticed that resolving to a virtual host is very slow (around 3 seconds) the first time but after that is fast as long as I continue loading it regularly. + +If I leave it untouched for a couple of minutes and then reload again, the first reload is (again) painfully slow; seems like something is being cached. + +As can be seen below I am not using the .local TLD. + +My setup: Apache 2 - MySQL - PHP installed and enabled - added a couple of virtual hosts one of which I created for localhost + +My /etc/hosts: + +``` +127.0.0.1 localhost +255.255.255.255 broadcasthost +::1 localhost +fe80::1%lo0 localhost +127.0.0.1 myproject.dev +::1 myproject.dev +fe80::1%lo0 myproject.dev + +``` + +My virtual host set-up in username.conf: + +``` +NameVirtualHost *:80 + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + + + ServerName localhost + DocumentRoot /Users/myusername/Dropbox/dev_envs/ + + + ServerName myproject.dev + DocumentRoot /Users/myusername/Dropbox/dev_envs/myprojectname + + +```",2012/04/08,"['https://Stackoverflow.com/questions/10064581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61232/']","I had the same problem, also on Lion. + +Strangely, my solution was the opposite of Jeremy's. I had a whole bunch of someproject.dev entries on one line in /etc/hosts. Loading a site on any of them the first time took forever, like a minute or so. If I used it again within 5 seconds or so it was very fast, but much longer and it would again take a minute. I had suspected all sorts of things, mysql connections, Ruby versions, Rails bugs, Apache, Phusion Passenger. Until I finally looked at the Console and realized that DNS lookups were being attempted. + +So, I put all of them on seperate lines: + +``` +127.0.0.1 localhost + +127.0.0.1 myproject.dev + +127.0.0.1 myotherproject.dev + +``` + +And suddenly everything was snappy again. Same on both my machines.","The trick that did it for me was adding + +``` +127.0.0.1 locahost + +``` + +on the first line of the host file. + +From all my virtual hosts, only the ones using a database were slow. I believe it's because the process of looking up ""localhost"" for the database connection slowed things down, since I only added the addresses for my virtual hosts and not ""localhost"" as well. Now it's all snappy again. :)" +10064581,"Since setting up my development environments on Mac OS X Lion (brand new macbook air purchased in January 2012), I have noticed that resolving to a virtual host is very slow (around 3 seconds) the first time but after that is fast as long as I continue loading it regularly. + +If I leave it untouched for a couple of minutes and then reload again, the first reload is (again) painfully slow; seems like something is being cached. + +As can be seen below I am not using the .local TLD. + +My setup: Apache 2 - MySQL - PHP installed and enabled - added a couple of virtual hosts one of which I created for localhost + +My /etc/hosts: + +``` +127.0.0.1 localhost +255.255.255.255 broadcasthost +::1 localhost +fe80::1%lo0 localhost +127.0.0.1 myproject.dev +::1 myproject.dev +fe80::1%lo0 myproject.dev + +``` + +My virtual host set-up in username.conf: + +``` +NameVirtualHost *:80 + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + + + ServerName localhost + DocumentRoot /Users/myusername/Dropbox/dev_envs/ + + + ServerName myproject.dev + DocumentRoot /Users/myusername/Dropbox/dev_envs/myprojectname + + +```",2012/04/08,"['https://Stackoverflow.com/questions/10064581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61232/']","I had the same problem and found it to be caused by enabling IPv6 on my LAN, but not having IPv6 configured correctly between my network and my ISP. Apparently the IPv6 DNS-server takes precedence over IPv4 DNS when the client is given both. It took a couple of seconds (on every attempt) for the client to find that the IPv6 DNS was unreachable or missing, and then falling back to IPv4 DNS.","This helped me: [Apache HTTP localhost randomly taking 5 seconds on macOS Monterey but fast on HTTPS](https://stackoverflow.com/questions/70698918/apache-http-localhost-randomly-taking-5-seconds-on-macos-monterey-but-fast-on-ht) + +``` +Turn off Keep Alive by adding: + +KeepAlive Off + +To your http.conf + +```" +10064581,"Since setting up my development environments on Mac OS X Lion (brand new macbook air purchased in January 2012), I have noticed that resolving to a virtual host is very slow (around 3 seconds) the first time but after that is fast as long as I continue loading it regularly. + +If I leave it untouched for a couple of minutes and then reload again, the first reload is (again) painfully slow; seems like something is being cached. + +As can be seen below I am not using the .local TLD. + +My setup: Apache 2 - MySQL - PHP installed and enabled - added a couple of virtual hosts one of which I created for localhost + +My /etc/hosts: + +``` +127.0.0.1 localhost +255.255.255.255 broadcasthost +::1 localhost +fe80::1%lo0 localhost +127.0.0.1 myproject.dev +::1 myproject.dev +fe80::1%lo0 myproject.dev + +``` + +My virtual host set-up in username.conf: + +``` +NameVirtualHost *:80 + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + + + ServerName localhost + DocumentRoot /Users/myusername/Dropbox/dev_envs/ + + + ServerName myproject.dev + DocumentRoot /Users/myusername/Dropbox/dev_envs/myprojectname + + +```",2012/04/08,"['https://Stackoverflow.com/questions/10064581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61232/']","There's another issue 10.7.\* to 10.8.4 for sites ending in `.local` which causes five second lookups. Details and solution courtesy Bram Van Damme’s [blog post found here](http://www.bram.us/2011/12/12/mamp-pro-slow-name-resolving-with-local-vhosts-in-lion-fix/). + +> +> “By default, any hostname ending in `.local` is treated as a Bonjour host rather than by querying the DNS server entries in Network preferences.” +> +> +> “To fix this problem (without having to rename each vhost) you need to add IPv6 entries for each of your vhosts in your `/etc/hosts` file:” +> +> +> + +``` +::1 mysite.local +fe80::1%lo0 mysite.local +127.0.0.1 mysite.local + +```","This helped me: [Apache HTTP localhost randomly taking 5 seconds on macOS Monterey but fast on HTTPS](https://stackoverflow.com/questions/70698918/apache-http-localhost-randomly-taking-5-seconds-on-macos-monterey-but-fast-on-ht) + +``` +Turn off Keep Alive by adding: + +KeepAlive Off + +To your http.conf + +```" +10064581,"Since setting up my development environments on Mac OS X Lion (brand new macbook air purchased in January 2012), I have noticed that resolving to a virtual host is very slow (around 3 seconds) the first time but after that is fast as long as I continue loading it regularly. + +If I leave it untouched for a couple of minutes and then reload again, the first reload is (again) painfully slow; seems like something is being cached. + +As can be seen below I am not using the .local TLD. + +My setup: Apache 2 - MySQL - PHP installed and enabled - added a couple of virtual hosts one of which I created for localhost + +My /etc/hosts: + +``` +127.0.0.1 localhost +255.255.255.255 broadcasthost +::1 localhost +fe80::1%lo0 localhost +127.0.0.1 myproject.dev +::1 myproject.dev +fe80::1%lo0 myproject.dev + +``` + +My virtual host set-up in username.conf: + +``` +NameVirtualHost *:80 + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + + + ServerName localhost + DocumentRoot /Users/myusername/Dropbox/dev_envs/ + + + ServerName myproject.dev + DocumentRoot /Users/myusername/Dropbox/dev_envs/myprojectname + + +```",2012/04/08,"['https://Stackoverflow.com/questions/10064581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61232/']","Ensuring that the host names are defined at the beginning of the file made the difference for me. +By default the line 127.0.0.1 localhost is already at the beginning, just add your entries on the same line.","The trick that did it for me was adding + +``` +127.0.0.1 locahost + +``` + +on the first line of the host file. + +From all my virtual hosts, only the ones using a database were slow. I believe it's because the process of looking up ""localhost"" for the database connection slowed things down, since I only added the addresses for my virtual hosts and not ""localhost"" as well. Now it's all snappy again. :)" +10064581,"Since setting up my development environments on Mac OS X Lion (brand new macbook air purchased in January 2012), I have noticed that resolving to a virtual host is very slow (around 3 seconds) the first time but after that is fast as long as I continue loading it regularly. + +If I leave it untouched for a couple of minutes and then reload again, the first reload is (again) painfully slow; seems like something is being cached. + +As can be seen below I am not using the .local TLD. + +My setup: Apache 2 - MySQL - PHP installed and enabled - added a couple of virtual hosts one of which I created for localhost + +My /etc/hosts: + +``` +127.0.0.1 localhost +255.255.255.255 broadcasthost +::1 localhost +fe80::1%lo0 localhost +127.0.0.1 myproject.dev +::1 myproject.dev +fe80::1%lo0 myproject.dev + +``` + +My virtual host set-up in username.conf: + +``` +NameVirtualHost *:80 + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + + + ServerName localhost + DocumentRoot /Users/myusername/Dropbox/dev_envs/ + + + ServerName myproject.dev + DocumentRoot /Users/myusername/Dropbox/dev_envs/myprojectname + + +```",2012/04/08,"['https://Stackoverflow.com/questions/10064581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61232/']","There's another issue 10.7.\* to 10.8.4 for sites ending in `.local` which causes five second lookups. Details and solution courtesy Bram Van Damme’s [blog post found here](http://www.bram.us/2011/12/12/mamp-pro-slow-name-resolving-with-local-vhosts-in-lion-fix/). + +> +> “By default, any hostname ending in `.local` is treated as a Bonjour host rather than by querying the DNS server entries in Network preferences.” +> +> +> “To fix this problem (without having to rename each vhost) you need to add IPv6 entries for each of your vhosts in your `/etc/hosts` file:” +> +> +> + +``` +::1 mysite.local +fe80::1%lo0 mysite.local +127.0.0.1 mysite.local + +```","A dumb issue that led me to waste some considerable time: after applying [@Cleverlemming's answer](https://stackoverflow.com/a/17982964/1588706), I figured out that there were duplicated entries on the hosts file. Something like: + +``` +::1 site1.local site2.local site1.local site3.local site4.local +fe80::1%lo0 site1.local site2.local site1.local site3.local site4.local +127.0.0.1 site1.local site2.local site1.local site3.local site4.local + +``` + +Then IP resolving for site3.local and site4.local takes these 5-seconds of death." +10064581,"Since setting up my development environments on Mac OS X Lion (brand new macbook air purchased in January 2012), I have noticed that resolving to a virtual host is very slow (around 3 seconds) the first time but after that is fast as long as I continue loading it regularly. + +If I leave it untouched for a couple of minutes and then reload again, the first reload is (again) painfully slow; seems like something is being cached. + +As can be seen below I am not using the .local TLD. + +My setup: Apache 2 - MySQL - PHP installed and enabled - added a couple of virtual hosts one of which I created for localhost + +My /etc/hosts: + +``` +127.0.0.1 localhost +255.255.255.255 broadcasthost +::1 localhost +fe80::1%lo0 localhost +127.0.0.1 myproject.dev +::1 myproject.dev +fe80::1%lo0 myproject.dev + +``` + +My virtual host set-up in username.conf: + +``` +NameVirtualHost *:80 + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + + + ServerName localhost + DocumentRoot /Users/myusername/Dropbox/dev_envs/ + + + ServerName myproject.dev + DocumentRoot /Users/myusername/Dropbox/dev_envs/myprojectname + + +```",2012/04/08,"['https://Stackoverflow.com/questions/10064581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61232/']","Make sure to put the IP v6 entries not in the line with localhost + +``` +::1 localhost + +``` + +the IP v6 entries go in a separate line + +``` +fe80::1%lo0 here and_here + +``` + +It is sometimes really fast now, but there are rare exceptions where the old lags come back. They might however be based on other reasons.","I had this same problem and finally realized I had the same host entry twice on the same line: + +e.g. + +``` +127.0.0.1 localhost host1 host2 host3 host4 host5 host1 host6 + +``` + +I removed the second instance of the same host (in the example above - host1) - and things immediately sped up. + +Felt a little silly when I discovered this, but when you've got 10 long host names on the same line and you're frequently adding / removing, it can be eaisly overlooked." +10064581,"Since setting up my development environments on Mac OS X Lion (brand new macbook air purchased in January 2012), I have noticed that resolving to a virtual host is very slow (around 3 seconds) the first time but after that is fast as long as I continue loading it regularly. + +If I leave it untouched for a couple of minutes and then reload again, the first reload is (again) painfully slow; seems like something is being cached. + +As can be seen below I am not using the .local TLD. + +My setup: Apache 2 - MySQL - PHP installed and enabled - added a couple of virtual hosts one of which I created for localhost + +My /etc/hosts: + +``` +127.0.0.1 localhost +255.255.255.255 broadcasthost +::1 localhost +fe80::1%lo0 localhost +127.0.0.1 myproject.dev +::1 myproject.dev +fe80::1%lo0 myproject.dev + +``` + +My virtual host set-up in username.conf: + +``` +NameVirtualHost *:80 + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + + + ServerName localhost + DocumentRoot /Users/myusername/Dropbox/dev_envs/ + + + ServerName myproject.dev + DocumentRoot /Users/myusername/Dropbox/dev_envs/myprojectname + + +```",2012/04/08,"['https://Stackoverflow.com/questions/10064581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61232/']","I had the exact same problem and it was driving me crazy! + +Put all your hosts file entries for localhost into one line like so: + +``` +127.0.0.1 localhost myproject.dev myotherproject.dev +::1 localhost +fe80::1%lo0 localhost + +``` + +Worked like a charm for me. Seems like a bug in Lion.","A dumb issue that led me to waste some considerable time: after applying [@Cleverlemming's answer](https://stackoverflow.com/a/17982964/1588706), I figured out that there were duplicated entries on the hosts file. Something like: + +``` +::1 site1.local site2.local site1.local site3.local site4.local +fe80::1%lo0 site1.local site2.local site1.local site3.local site4.local +127.0.0.1 site1.local site2.local site1.local site3.local site4.local + +``` + +Then IP resolving for site3.local and site4.local takes these 5-seconds of death." +10064581,"Since setting up my development environments on Mac OS X Lion (brand new macbook air purchased in January 2012), I have noticed that resolving to a virtual host is very slow (around 3 seconds) the first time but after that is fast as long as I continue loading it regularly. + +If I leave it untouched for a couple of minutes and then reload again, the first reload is (again) painfully slow; seems like something is being cached. + +As can be seen below I am not using the .local TLD. + +My setup: Apache 2 - MySQL - PHP installed and enabled - added a couple of virtual hosts one of which I created for localhost + +My /etc/hosts: + +``` +127.0.0.1 localhost +255.255.255.255 broadcasthost +::1 localhost +fe80::1%lo0 localhost +127.0.0.1 myproject.dev +::1 myproject.dev +fe80::1%lo0 myproject.dev + +``` + +My virtual host set-up in username.conf: + +``` +NameVirtualHost *:80 + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + + + ServerName localhost + DocumentRoot /Users/myusername/Dropbox/dev_envs/ + + + ServerName myproject.dev + DocumentRoot /Users/myusername/Dropbox/dev_envs/myprojectname + + +```",2012/04/08,"['https://Stackoverflow.com/questions/10064581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61232/']","I had the same problem, also on Lion. + +Strangely, my solution was the opposite of Jeremy's. I had a whole bunch of someproject.dev entries on one line in /etc/hosts. Loading a site on any of them the first time took forever, like a minute or so. If I used it again within 5 seconds or so it was very fast, but much longer and it would again take a minute. I had suspected all sorts of things, mysql connections, Ruby versions, Rails bugs, Apache, Phusion Passenger. Until I finally looked at the Console and realized that DNS lookups were being attempted. + +So, I put all of them on seperate lines: + +``` +127.0.0.1 localhost + +127.0.0.1 myproject.dev + +127.0.0.1 myotherproject.dev + +``` + +And suddenly everything was snappy again. Same on both my machines.","Specifying same host for IPv6 ::1 helped me. + +``` +127.0.0.1 something.local.mydomain.org +::1 something.local.mydomain.org + +```" +10064581,"Since setting up my development environments on Mac OS X Lion (brand new macbook air purchased in January 2012), I have noticed that resolving to a virtual host is very slow (around 3 seconds) the first time but after that is fast as long as I continue loading it regularly. + +If I leave it untouched for a couple of minutes and then reload again, the first reload is (again) painfully slow; seems like something is being cached. + +As can be seen below I am not using the .local TLD. + +My setup: Apache 2 - MySQL - PHP installed and enabled - added a couple of virtual hosts one of which I created for localhost + +My /etc/hosts: + +``` +127.0.0.1 localhost +255.255.255.255 broadcasthost +::1 localhost +fe80::1%lo0 localhost +127.0.0.1 myproject.dev +::1 myproject.dev +fe80::1%lo0 myproject.dev + +``` + +My virtual host set-up in username.conf: + +``` +NameVirtualHost *:80 + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + + + ServerName localhost + DocumentRoot /Users/myusername/Dropbox/dev_envs/ + + + ServerName myproject.dev + DocumentRoot /Users/myusername/Dropbox/dev_envs/myprojectname + + +```",2012/04/08,"['https://Stackoverflow.com/questions/10064581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61232/']","There's another issue 10.7.\* to 10.8.4 for sites ending in `.local` which causes five second lookups. Details and solution courtesy Bram Van Damme’s [blog post found here](http://www.bram.us/2011/12/12/mamp-pro-slow-name-resolving-with-local-vhosts-in-lion-fix/). + +> +> “By default, any hostname ending in `.local` is treated as a Bonjour host rather than by querying the DNS server entries in Network preferences.” +> +> +> “To fix this problem (without having to rename each vhost) you need to add IPv6 entries for each of your vhosts in your `/etc/hosts` file:” +> +> +> + +``` +::1 mysite.local +fe80::1%lo0 mysite.local +127.0.0.1 mysite.local + +```","I've run into this a bunch, too. I have a bunch of vhosts defined on two lines, one for IPv4 and one for IPv6. Moving the host I was trying to resolve to be first in the list sped it up. + +``` +127.0.0.1 faster.example.dev host1.example.dev host2.example.dev host3.example.dev host4.example.dev host5.example.dev host6.example.dev +::1 faster.example.dev host1.example.dev host2.example.dev host3.example.dev host4.example.dev host5.example.dev host6.example.dev + +```" +10064581,"Since setting up my development environments on Mac OS X Lion (brand new macbook air purchased in January 2012), I have noticed that resolving to a virtual host is very slow (around 3 seconds) the first time but after that is fast as long as I continue loading it regularly. + +If I leave it untouched for a couple of minutes and then reload again, the first reload is (again) painfully slow; seems like something is being cached. + +As can be seen below I am not using the .local TLD. + +My setup: Apache 2 - MySQL - PHP installed and enabled - added a couple of virtual hosts one of which I created for localhost + +My /etc/hosts: + +``` +127.0.0.1 localhost +255.255.255.255 broadcasthost +::1 localhost +fe80::1%lo0 localhost +127.0.0.1 myproject.dev +::1 myproject.dev +fe80::1%lo0 myproject.dev + +``` + +My virtual host set-up in username.conf: + +``` +NameVirtualHost *:80 + + + Options Indexes MultiViews + AllowOverride None + Order allow,deny + Allow from all + + + + ServerName localhost + DocumentRoot /Users/myusername/Dropbox/dev_envs/ + + + ServerName myproject.dev + DocumentRoot /Users/myusername/Dropbox/dev_envs/myprojectname + + +```",2012/04/08,"['https://Stackoverflow.com/questions/10064581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61232/']","On OSX El Capitan what worked for me was making a duplicate IPv6 entry right above the IPv4 entry like so + +``` +fe80::1%lo0 demo.test.dev +127.0.0.1 demo.test.dev + +```","Note: I am using Windows and XAMPP, however while researching the problem many people have had the same issue on Windows and Mac. Answer for reference for anyone finding this question as I have spent hours trying to find a solution that works for me: + +I have tried many solutions for the same problem including putting all of the hosts on one line, removing redundant hosts and virtualhosts, and also including the IPv6 lines - none of these *alone* were successful. + +The only solution which has *so far* appeared to work for me is a combination of all of the solutions: + +* Changing the domain I am using from mysite.**local** to mysite.**dev**. Inspired by [@Cleverlemming's answer.](https://stackoverflow.com/a/17982964/1588706) +* Including the IPv6 lines. +* Removing redundant virtualhosts and hosts (I commented them out). + +In my hosts file my hosts are currently on separate lines and so far the issue seems to be fixed. + +Good luck to anyone attempting to solve this issue and if anyone has any information to add please do so - this seems to be an issue affected a lot of people with no single known cause or solution." +15011569,"Lets say I have tables Student and Mentor + +Does anyone use naming convention for relationship as below? I think this way is good to see the relationships quickly. Would anyone suggest a better way? + +Student + +StudentID + +StudentName + +Student2MentorID",2013/02/21,"['https://Stackoverflow.com/questions/15011569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/783411/']","To start from scratch, - you probably know this already - there are several ways to represent your database schema, I mean, by using diagrams, for example [ER-diagrams](http://en.wikipedia.org/wiki/Entity%E2%80%93relationship_model#Diagramming_conventions) that helps you (and your team) stay up to date with your database's design and thus making it simpler to understand. + +Now, personally when it comes to implementation, I do use some kind of naming-convention. For example: + +* For large projects, I use double underscores to split between table categories, (ie. `hr__personnel`, `hr__clocks`, `hr__timetable`, `vehicles__cars`, `vehicles__trips`) and so on. +* Now, having a relationship between two tables, I do Include both (or all) of the involved table names. (ie. `hr__personnel_timetable`, `vehicles__cars_trips`, etc) +* Sometimes, (as we all know), we cannot follow strictly a standard, so in those cases I use my own criteria when choosing large relationships' names. +* As a rule, I also name table attributes by a three-letter preffix. For example, in my table `trips`, my fields will be `tri_id`,`tri_distance`, `tri_elapsed` +* Note also, that in the above item, I didn't include a Foreign Key. So here I go then. When it comes to FK's, It's easy for me (and my team) to realize that the field IS a FK. +If we follow the previous example, I would like to know who drives in each trip (to make it easier, we assume that only one person drives one trip). So my table now is something like this: `tri_id`, *`per_id`*, `tri_distance`, `tri_elapsed`. Now you can easily realize that per\_id is just a foreign field of the table. Just, another hint to help. + +Just by following these simple steps, you will save *hours*, and probably some headaches too. + +Hope this helps.","It is better to use underscores... +I suggest to simply use existing naming convention rules such as this one: +" +15011569,"Lets say I have tables Student and Mentor + +Does anyone use naming convention for relationship as below? I think this way is good to see the relationships quickly. Would anyone suggest a better way? + +Student + +StudentID + +StudentName + +Student2MentorID",2013/02/21,"['https://Stackoverflow.com/questions/15011569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/783411/']","I think: you can add prefix (3 letters) to table depending that module represents (scholar,sales,store) + +module: scholar ->**sc** + +table: **scStudent** ( IdStudent,nameStudent..) + +table: **scMentor**(IdMentor,nameMentor...) + +relationship + +**scMentorStudent** (**IdMentorStudent** pk..) + +You can use Microsoft's EF notation : + +","It is better to use underscores... +I suggest to simply use existing naming convention rules such as this one: +" +72461386,"Consider the following event: + +``` +$(`#selectpicker).on('change', function(){ +if(condition) {} else +{ + //canceel event change +} +}); + +``` + +How to cancel the change event based on specific condition therefore maintaining the same select picker value.",2022/06/01,"['https://Stackoverflow.com/questions/72461386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5946983/']","Is this what you are looking for? Set a variable for the current value and if an undesired value is selected we set the value of the select field back to the recent value. + +``` + + +let currentValue = $('#selectpicker').val(); +$('#selectpicker').on('change', function(){ + let newValue = $(this).val(); + + if(newValue == 3){ + console.log(""3 is not allowed""); + $(this).val(currentValue); + return; + } + currentValue = $('#selectpicker').val(); +}) + +``` + +You could also disable certain options with ""disabled"" keyword, but keep in mind that this can be easily bypassed from developer tools. + +``` + + +```","While you can stop the execution of the callback with `return false`, the value will already have changed when this event is triggered. If you want to return to the previous value, you have to store it somehow, either in a variable or in a `data` property on the element. Then you can set the value back in your condition, or update the variable when your cancel-condition is not met." +18400673,"In my rails app I have two tables - `device_ports` and `circuits`. My goal is to get a list of `device_ports` whose `id` is not being used in the `physical_port_id` column of the `circuits` table. + +I have done something similar before on other tables but here my query only returns one row when it should return 23 rows - there are 24 device ports for this device and one is in use. + +``` +select id, name, device_id, multiuse +from device_ports +where (device_id = 6 and multiuse = 1) +or device_ports.id not in (select physical_port_id from circuits) + +``` + +So this query gets all multiuse ports (so even if the id was referenced in the foreign key, this row should still be returned) and should also get all rows where the device\_id is 6 but is not referenced in circuits but only the multiuse row is being returned. + +The result from the query is + +``` +id | name | device_id | multiuse +------------------------------------ +268 | test-1 | 6 | 1 + +``` + +I did try to create an sql fiddle but the build just seems to timeout. + +``` +CREATE TABLE `device_ports` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `device_id` int(11) DEFAULT NULL, + `name` tinytext, + `speed` tinytext, + `multiuse` tinyint(1) DEFAULT NULL, + `created_at` datetime DEFAULT NULL, + `updated_at` datetime DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `id` (`id`) +) ENGINE=MyISAM AUTO_INCREMENT=291 DEFAULT CHARSET=latin1; + +INSERT INTO `device_ports` (`id`, `device_id`, `name`, `speed`, `multiuse`, `created_at`, `updated_at`) +*emphasized text*VALUES +(1, 1, 'Test Device Port', '100', 0, NULL, NULL), +(2, 1, 'Test Port 2', '300', 1, NULL, NULL), +(289, 6, 'test-22', '100', 0, NULL, NULL), +(290, 6, 'test-23', '100', 0, NULL, NULL), +(288, 6, 'test-21', '100', 0, NULL, NULL), +(287, 6, 'test-20', '100', 0, NULL, NULL), +(286, 6, 'test-19', '100', 0, NULL, NULL), +(284, 6, 'test-17', '100', 0, NULL, NULL), +(285, 6, 'test-18', '100', 0, NULL, NULL), +(283, 6, 'test-16', '100', 0, NULL, NULL), +(282, 6, 'test-15', '100', 0, NULL, NULL), +(281, 6, 'test-14', '100', 0, NULL, NULL), +(280, 6, 'test-13', '100', 0, NULL, NULL), +(279, 6, 'test-12', '100', 0, NULL, NULL), +(278, 6, 'test-11', '100', 0, NULL, NULL), +(277, 6, 'test-10', '100', 0, NULL, NULL), +(276, 6, 'test-9', '100', 0, NULL, NULL), +(275, 6, 'test-8', '100', 0, NULL, NULL), +(274, 6, 'test-7', '100', 0, NULL, NULL), +(273, 6, 'test-6', '100', 0, NULL, NULL), +(272, 6, 'test-5', '100', 0, NULL, NULL), +(271, 6, 'test-4', '100', 0, NULL, NULL), +(270, 6, 'test-3', '100', 0, NULL, NULL), +(269, 6, 'test-2', '100', 0, NULL, NULL), +(268, 6, 'test-1', '100', 1, NULL, NULL), +(267, 6, 'test-0', '100', 0, NULL, NULL); + +CREATE TABLE `circuits` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `organisation_id` int(11) DEFAULT NULL, + `physical_port_id` int(11) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=248 DEFAULT CHARSET=latin1; + +INSERT INTO `circuits` (`id`, `organisation_id`, `physical_port_id`) +VALUES (1, 125, 267); + +```",2013/08/23,"['https://Stackoverflow.com/questions/18400673', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/634120/']","You could try using a LEFT OUTER JOIN: + +``` +SELECT DISTINCT d.id, d.name, d.device_id, d.multiuse + FROM device_ports d + LEFT OUTER JOIN circuits c ON c.physical_port_id = d.id +WHERE + (c.physical_port_id IS NULL AND d.device_id = 6) + OR (d.multiuse = 1 AND d.device_id = 6) + ORDER BY d.id + +``` + +There are several techniques for this query, take a look at [What's the difference between NOT EXISTS vs. NOT IN vs. LEFT JOIN WHERE IS NULL?](https://stackoverflow.com/questions/2246772/whats-the-difference-between-not-exists-vs-not-in-vs-left-join-where-is-null).","``` +SELECT p.* + FROM device_ports p + LEFT + JOIN circuits c + ON c.physical_port_id = p.id + WHERE p.device_id = 6 + AND multiuse = 1 + AND c.id IS NULL; + +```" +29765504,"Currently coding in C#, I wonder if there is a way to factor the code as presented below + +``` +Entity1 = GetByName(""EntityName1""); +Entity2 = GetByName(""EntityName2""); +Entity3 = GetByName(""EntityName3""); + +``` + +The idea would be to get a single call in the code, factoring the code by placing the `entities` and the `strings` in a container and iterating on this container to get a single ""`GetByName()`"" line. Is there a way to do this?",2015/04/21,"['https://Stackoverflow.com/questions/29765504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4311207/']","You can use LINQ: + +``` +var names=new[]{""EntityName1"",""EntityName2"",""EntityName3"",.....}; +var entities=names.Select(name=>GetByName(name)).ToArray(); + +``` + +Without `ToArray`, `Select` will return an IEnumerable that will be reevalueated each time you enumerate it - that is, `GetByName` will be called each time you enumerate the enumerable. + +`ToArray()` or `ToList` will create an array (or list) you can use multiple times. + +You can also call `ToDictionary` if you want to be able to access the entities by name: + +``` +var entities=names.ToDictionary(name=>name,name=>GetByName(name)); + +``` + +All this assumes that the entities don't already exist or that `GetByName` has to do some significant work to retrieve them. If the entities exist you can simply put them in a `Dictionary`. If the entities have a `Name` property you can use `ToDictionary` to create the dictionary in one statement: + +``` +var entities=new []{entity1,entity2,entity3,...}; +var entitiesDict=entities.ToDictionary(entity=>entity.Name,entity=>entity); + +```","Do you mean something like the below (where `entities` is the collection of `Entity1`, `Entity1` & `Entity3`): + +``` +var results = entities.Select(e => GetByName(e.Name)); + +```" +29765504,"Currently coding in C#, I wonder if there is a way to factor the code as presented below + +``` +Entity1 = GetByName(""EntityName1""); +Entity2 = GetByName(""EntityName2""); +Entity3 = GetByName(""EntityName3""); + +``` + +The idea would be to get a single call in the code, factoring the code by placing the `entities` and the `strings` in a container and iterating on this container to get a single ""`GetByName()`"" line. Is there a way to do this?",2015/04/21,"['https://Stackoverflow.com/questions/29765504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4311207/']","You can use LINQ: + +``` +var names=new[]{""EntityName1"",""EntityName2"",""EntityName3"",.....}; +var entities=names.Select(name=>GetByName(name)).ToArray(); + +``` + +Without `ToArray`, `Select` will return an IEnumerable that will be reevalueated each time you enumerate it - that is, `GetByName` will be called each time you enumerate the enumerable. + +`ToArray()` or `ToList` will create an array (or list) you can use multiple times. + +You can also call `ToDictionary` if you want to be able to access the entities by name: + +``` +var entities=names.ToDictionary(name=>name,name=>GetByName(name)); + +``` + +All this assumes that the entities don't already exist or that `GetByName` has to do some significant work to retrieve them. If the entities exist you can simply put them in a `Dictionary`. If the entities have a `Name` property you can use `ToDictionary` to create the dictionary in one statement: + +``` +var entities=new []{entity1,entity2,entity3,...}; +var entitiesDict=entities.ToDictionary(entity=>entity.Name,entity=>entity); + +```","It depends on what you're looking for. If you need to set the variables in a single line, that won't work. You could play with reflection if you're dealing with fields or properties, but honestly that seems messier than what you've got already. + +If the data-structure doesn't matter, and you just need the data and are able to play with it as you see so fit, I'd probably enumerate it into a dictionary. Of course, that's pretty tightly coupled to what you've got now, which looks like it's a fake implementation anyway. + +If you want to do that, it's pretty straight-forward. It's your choice how you create the `IEnumerable` that's represented below as `entityNames`. You could use an array initializer as I do, you could use a `List` that you build over time, you could even `yield return` it in its own method. + +``` +var entityNames = new[] { ""EntityName1"", ""EntityName2"", ""EntityName3"" }; + +var dict = entityNames.ToDictionary(c => c, c => GetByName(c)); + +``` + +Then it's just a matter of checking those. + +``` +var entity1 = dict[""EntityName1""]; + +``` + +Or enumerating over the dictionary. + +``` +foreach(var kvp in dict) +{ + Console.WriteLine(""{0} - {1}"", kvp.Key, kvp.Value); +} + +``` + +But realistically, it's hard to know whether that's preferable to what you've already got." +29765504,"Currently coding in C#, I wonder if there is a way to factor the code as presented below + +``` +Entity1 = GetByName(""EntityName1""); +Entity2 = GetByName(""EntityName2""); +Entity3 = GetByName(""EntityName3""); + +``` + +The idea would be to get a single call in the code, factoring the code by placing the `entities` and the `strings` in a container and iterating on this container to get a single ""`GetByName()`"" line. Is there a way to do this?",2015/04/21,"['https://Stackoverflow.com/questions/29765504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4311207/']","You can use LINQ: + +``` +var names=new[]{""EntityName1"",""EntityName2"",""EntityName3"",.....}; +var entities=names.Select(name=>GetByName(name)).ToArray(); + +``` + +Without `ToArray`, `Select` will return an IEnumerable that will be reevalueated each time you enumerate it - that is, `GetByName` will be called each time you enumerate the enumerable. + +`ToArray()` or `ToList` will create an array (or list) you can use multiple times. + +You can also call `ToDictionary` if you want to be able to access the entities by name: + +``` +var entities=names.ToDictionary(name=>name,name=>GetByName(name)); + +``` + +All this assumes that the entities don't already exist or that `GetByName` has to do some significant work to retrieve them. If the entities exist you can simply put them in a `Dictionary`. If the entities have a `Name` property you can use `ToDictionary` to create the dictionary in one statement: + +``` +var entities=new []{entity1,entity2,entity3,...}; +var entitiesDict=entities.ToDictionary(entity=>entity.Name,entity=>entity); + +```","Ok, here is an idea. + +You can declare this function. + +``` +IReadOnlyDictionary InstantiateByName( + Func instantiator + params string[] names) +{ + return names.Distinct().ToDictionary( + name => name, + name => instantiator(name)) +} + +``` + +which you could call like this, + +``` +var entities = InstantiateByName( + GetByName, + ""EntityName1"", + ""EntityName2"", + ""EntityName3""); + +``` + +--- + +To push the over-engineering to the next level, + +you can install the Immutable Collections package, + +``` +PM> Install-Package Microsoft.Bcl.Immutable + +``` + +and modify the function slightly, + +``` +using Microsoft.Immutable.Collections; + +IReadOnlyDictionary InstantiateByName( + Func instantiator + params string[] names, + IEqualityComparer keyComparer = null, + IEqualityComparer valueComparer = null) +{ + if (keyComparer == null) + { + keyComparer = EqualityComparer.Default; + } + + if (valueComparer == null) + { + valueComparer = EqualityComparer.Default; + } + + return names.ToImmutableDictionary( + name => name, + name => instantiator(name), + keyComparer, + valueComparer); +} + +``` + +The function would be used in the exactly the same way. However, the caller is responsible for passing unique keys to the function but, an alternative equality comparer can be passed." +29765504,"Currently coding in C#, I wonder if there is a way to factor the code as presented below + +``` +Entity1 = GetByName(""EntityName1""); +Entity2 = GetByName(""EntityName2""); +Entity3 = GetByName(""EntityName3""); + +``` + +The idea would be to get a single call in the code, factoring the code by placing the `entities` and the `strings` in a container and iterating on this container to get a single ""`GetByName()`"" line. Is there a way to do this?",2015/04/21,"['https://Stackoverflow.com/questions/29765504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4311207/']","Do you mean something like the below (where `entities` is the collection of `Entity1`, `Entity1` & `Entity3`): + +``` +var results = entities.Select(e => GetByName(e.Name)); + +```","Ok, here is an idea. + +You can declare this function. + +``` +IReadOnlyDictionary InstantiateByName( + Func instantiator + params string[] names) +{ + return names.Distinct().ToDictionary( + name => name, + name => instantiator(name)) +} + +``` + +which you could call like this, + +``` +var entities = InstantiateByName( + GetByName, + ""EntityName1"", + ""EntityName2"", + ""EntityName3""); + +``` + +--- + +To push the over-engineering to the next level, + +you can install the Immutable Collections package, + +``` +PM> Install-Package Microsoft.Bcl.Immutable + +``` + +and modify the function slightly, + +``` +using Microsoft.Immutable.Collections; + +IReadOnlyDictionary InstantiateByName( + Func instantiator + params string[] names, + IEqualityComparer keyComparer = null, + IEqualityComparer valueComparer = null) +{ + if (keyComparer == null) + { + keyComparer = EqualityComparer.Default; + } + + if (valueComparer == null) + { + valueComparer = EqualityComparer.Default; + } + + return names.ToImmutableDictionary( + name => name, + name => instantiator(name), + keyComparer, + valueComparer); +} + +``` + +The function would be used in the exactly the same way. However, the caller is responsible for passing unique keys to the function but, an alternative equality comparer can be passed." +29765504,"Currently coding in C#, I wonder if there is a way to factor the code as presented below + +``` +Entity1 = GetByName(""EntityName1""); +Entity2 = GetByName(""EntityName2""); +Entity3 = GetByName(""EntityName3""); + +``` + +The idea would be to get a single call in the code, factoring the code by placing the `entities` and the `strings` in a container and iterating on this container to get a single ""`GetByName()`"" line. Is there a way to do this?",2015/04/21,"['https://Stackoverflow.com/questions/29765504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4311207/']","It depends on what you're looking for. If you need to set the variables in a single line, that won't work. You could play with reflection if you're dealing with fields or properties, but honestly that seems messier than what you've got already. + +If the data-structure doesn't matter, and you just need the data and are able to play with it as you see so fit, I'd probably enumerate it into a dictionary. Of course, that's pretty tightly coupled to what you've got now, which looks like it's a fake implementation anyway. + +If you want to do that, it's pretty straight-forward. It's your choice how you create the `IEnumerable` that's represented below as `entityNames`. You could use an array initializer as I do, you could use a `List` that you build over time, you could even `yield return` it in its own method. + +``` +var entityNames = new[] { ""EntityName1"", ""EntityName2"", ""EntityName3"" }; + +var dict = entityNames.ToDictionary(c => c, c => GetByName(c)); + +``` + +Then it's just a matter of checking those. + +``` +var entity1 = dict[""EntityName1""]; + +``` + +Or enumerating over the dictionary. + +``` +foreach(var kvp in dict) +{ + Console.WriteLine(""{0} - {1}"", kvp.Key, kvp.Value); +} + +``` + +But realistically, it's hard to know whether that's preferable to what you've already got.","Ok, here is an idea. + +You can declare this function. + +``` +IReadOnlyDictionary InstantiateByName( + Func instantiator + params string[] names) +{ + return names.Distinct().ToDictionary( + name => name, + name => instantiator(name)) +} + +``` + +which you could call like this, + +``` +var entities = InstantiateByName( + GetByName, + ""EntityName1"", + ""EntityName2"", + ""EntityName3""); + +``` + +--- + +To push the over-engineering to the next level, + +you can install the Immutable Collections package, + +``` +PM> Install-Package Microsoft.Bcl.Immutable + +``` + +and modify the function slightly, + +``` +using Microsoft.Immutable.Collections; + +IReadOnlyDictionary InstantiateByName( + Func instantiator + params string[] names, + IEqualityComparer keyComparer = null, + IEqualityComparer valueComparer = null) +{ + if (keyComparer == null) + { + keyComparer = EqualityComparer.Default; + } + + if (valueComparer == null) + { + valueComparer = EqualityComparer.Default; + } + + return names.ToImmutableDictionary( + name => name, + name => instantiator(name), + keyComparer, + valueComparer); +} + +``` + +The function would be used in the exactly the same way. However, the caller is responsible for passing unique keys to the function but, an alternative equality comparer can be passed." +517315,"I have created some domain users in ADUC and added them to the ""Domain Admins"" group. + +On a domain server when I try run a batch file that restart some services, with ""net stop "", ""net start "" and ""taskkill "", I get the following error message: + +``` +System error 5 has occured. +Access id denied. + +``` + +And if I try to run the batch file with ""Run as administrator"" I get the following error message: +""This file does not have a program associated with it for performing this action..."" + +It only works if I open an new cmd as administrator and rund the batch script from there. + +What rights do my domain admins account lack?",2012/12/10,"['https://superuser.com/questions/517315', 'https://superuser.com', 'https://superuser.com/users/179239/']","* insert a blank column in column C +* in `C1` put `=IF(A1=""gmail.com"",""EN"",B1)` and copy down +* copy and paste special value column C over the values in Column B +* delete the working column C + +For a partial search try something like + +`=IF(ISERROR(SEARCH(""gmail.com"",A1)>0),B1,""EN"")` in `C1` + +then copy down etc","Use `Sort & Filter`. + +Select column A and B (entirely) and apply the (auto)filter; select filter options on column A and chose text filters: contains. Set contains to ""gmail.com"", and apply filter. Column B will be filtered accordingly. + +Change the first cell in column B, and copy it (`Ctrl C`). Then select the remaining cells in column B and press `Ctrl V`." +517315,"I have created some domain users in ADUC and added them to the ""Domain Admins"" group. + +On a domain server when I try run a batch file that restart some services, with ""net stop "", ""net start "" and ""taskkill "", I get the following error message: + +``` +System error 5 has occured. +Access id denied. + +``` + +And if I try to run the batch file with ""Run as administrator"" I get the following error message: +""This file does not have a program associated with it for performing this action..."" + +It only works if I open an new cmd as administrator and rund the batch script from there. + +What rights do my domain admins account lack?",2012/12/10,"['https://superuser.com/questions/517315', 'https://superuser.com', 'https://superuser.com/users/179239/']","* insert a blank column in column C +* in `C1` put `=IF(A1=""gmail.com"",""EN"",B1)` and copy down +* copy and paste special value column C over the values in Column B +* delete the working column C + +For a partial search try something like + +`=IF(ISERROR(SEARCH(""gmail.com"",A1)>0),B1,""EN"")` in `C1` + +then copy down etc","Use an `IF` statement combined with a `RIGHT` function in column B. Place this formula in `B1`. + +``` +=IF(RIGHT(A1,9)=""gmail.com"",""EN"", ""HR"") + +``` + +This will look for the `gmail.com` and if it exists will populate the cell with `EN`, otherwise it will make it `HR`. + +To copy it down all the rows in the column, double click on the bottom right corner of the cell where the drag cross is." +517315,"I have created some domain users in ADUC and added them to the ""Domain Admins"" group. + +On a domain server when I try run a batch file that restart some services, with ""net stop "", ""net start "" and ""taskkill "", I get the following error message: + +``` +System error 5 has occured. +Access id denied. + +``` + +And if I try to run the batch file with ""Run as administrator"" I get the following error message: +""This file does not have a program associated with it for performing this action..."" + +It only works if I open an new cmd as administrator and rund the batch script from there. + +What rights do my domain admins account lack?",2012/12/10,"['https://superuser.com/questions/517315', 'https://superuser.com', 'https://superuser.com/users/179239/']","Use an `IF` statement combined with a `RIGHT` function in column B. Place this formula in `B1`. + +``` +=IF(RIGHT(A1,9)=""gmail.com"",""EN"", ""HR"") + +``` + +This will look for the `gmail.com` and if it exists will populate the cell with `EN`, otherwise it will make it `HR`. + +To copy it down all the rows in the column, double click on the bottom right corner of the cell where the drag cross is.","Use `Sort & Filter`. + +Select column A and B (entirely) and apply the (auto)filter; select filter options on column A and chose text filters: contains. Set contains to ""gmail.com"", and apply filter. Column B will be filtered accordingly. + +Change the first cell in column B, and copy it (`Ctrl C`). Then select the remaining cells in column B and press `Ctrl V`." +8727018,"I have been using some P/Invoke code to simulate a key press, but I can't work out how to press more than one key at once. I am trying to simulate pressing and holding CTRL and then pressing C and then V, so just a copy and paste. + +The code I am using so far is this, but so far I can only manage to press CTRL, not hold it and press C and V: + +``` +[DllImport(""user32.dll"", SetLastError = true)] +static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo); + +public const int VK_LCONTROL = 0xA2; + +static void Main(string[] args) +{ + keybd_event(VK_LCONTROL, 0, 0, 0); +} + +``` + +I would really appreciate any suggestions. Thanks.",2012/01/04,"['https://Stackoverflow.com/questions/8727018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/799586/']","The `dwFlags` controls if the key is released or not. + +Try the following: + +``` +keybd_event(VK_CONTROL, 0, 0, 0);// presses ctrl +keybd_event(0x43, 0, 0, 0); // presses c +keybd_event(0x43, 0, 2, 0); //releases c +keybd_event(VK_CONTROL, 0, 2, 0); //releases ctrl + +```","keybd\_event should be called twice for each keystroke, once to press it down, and once to release it, with the third argument including the bit KEYEVENTF\_KEYUP. You should of course press both keys down before releasing either. See [here](http://social.msdn.microsoft.com/Forums/en/netfxcompact/thread/d5d6097e-f221-452e-8b65-5659e2c9faaa) for a working example of pressing ""SHIFT+TAB"" using keybd\_event on the .NET Compact Framework (may be slight differences). + +Note that keybd\_event has been superseded by [SendInput](http://msdn.microsoft.com/en-us/library/windows/desktop/ms646310%28v=vs.85%29.aspx), but should still work." +7026438,"I am in the process of writing my own gridview implementation( Based of the tableview pattern). I have followed a datasource model similar to table view, but when I check if the data source responds to the message the call always fails. + +I have tried putting in break points and following execution, I even tried missing out the call to respondsToSelector. Nothing I try seems to work. What am I missing here? Thanks in advance + +**GridView.h** + +``` + ... + @protocol GridViewDataSource + - (NSInteger) numberOfRowsForGridView:(GridView *)gridView; + - (NSInteger) numberOfColumnsForGridView:(GridView *)gridView; + + - (GridViewCell *) cellForRow:(NSInteger) row column:(NSInteger )column; + @end + +``` + +**GridView.m** + +``` + ... + #pragma mark datasource methods + -(NSInteger)numberOfRowsForGridView + { + if( [dataSource respondsToSelector:@selector(numberOfRowsForGridView:)] ) + return [dataSource numberOfRowsForGridView:self]; + // NSLog(@""Failed, dataSource does not implement properly""); + return 0; + } + + -(NSInteger)numberOfColumnsForGridView + { + if( [dataSource respondsToSelector:@selector(numberOfColumnsForGridView:)] ) + return [dataSource numberOfColumnsForGridView:self]; + return 0; + } + + -(GridViewCell *)cellForRow:(NSInteger)row column:(NSInteger)column + { + if( [dataSource respondsToSelector:@selector(cellForRow:column:)]) + return [dataSource cellForRow:row column:column]; + return nil; + } + +``` + +**GridViewAppDelegate.h** + +``` + ... + @interface GridViewAppDelegate : NSObject + ... + +``` + +**GridViewAppDelegate.m** + +``` + #pragma mark datasource methods + -(NSInteger)numberOfRowsForGridView:(GridView *)gridView + { + return 1; + } + + -(NSInteger)numberOfColumnsForGridView:(GridView *)gridView + { + return 1; + } + + -(GridViewCell *)cellForRow:(NSInteger)row column:(NSInteger)column + { + CGRect frame = [view bounds]; + + GridViewCell *cell = [[GridViewCell alloc]initWithFrame:frame]; + return cell; + } + +```",2011/08/11,"['https://Stackoverflow.com/questions/7026438', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/299450/']","Is your `dataSource` object `nil`? + +Any message sent to `nil` will return `NO` for boolean results *(0 for numbers, and `nil` for objects as well)*.",Have you checked whether `dataSource` is non-nil? +13124,"``` +\documentclass{article} + +\usepackage{tikz} + +\begin{document} + +% DOES NOT WORK +%\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse (\p and 1); + +%WORKS +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse (1 and \p); + +\end{document} + +``` + +`(1 and \p)` works but `(\p and 1)` does not, why?",2011/03/10,"['https://tex.stackexchange.com/questions/13124', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/2099/']","The `( and )` syntax is old and, if not deprecated, at least not encouraged any more. The current way to do is is to use `[x radius]` and `[y radius]`: + +``` +\documentclass{article} + +\usepackage{tikz} + +\begin{document} + +% WORKS with current syntax +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse [x radius=\p, y radius=1]; + +%WORKS +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse [x radius=1, y radius=\p]; + +\end{document} + +```","``` +\documentclass{article} +\usepackage{tikz} +\begin{document} +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse (\p cm and 1 cm); +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse (1 cm and \p cm); +\end{document} + +``` + +problem with the parser, I suppose ! and the remark of Jake is fine, better now it's to use `x radius` and `y radius`" +13124,"``` +\documentclass{article} + +\usepackage{tikz} + +\begin{document} + +% DOES NOT WORK +%\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse (\p and 1); + +%WORKS +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse (1 and \p); + +\end{document} + +``` + +`(1 and \p)` works but `(\p and 1)` does not, why?",2011/03/10,"['https://tex.stackexchange.com/questions/13124', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/2099/']","Spaces after TeX commands are ignored, thus by using `\p and 1` you'll get an equivalent of, say, `1and 1`, which you can verify to give the same error. Therefore we just need to restore the space: + +``` +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse (\p{} and 1); + +``` + +Note that, as Jake mentions, this syntax is deprecated (refer to the [TikZ manual](http://ctan.org/pkg/pgf)).","``` +\documentclass{article} +\usepackage{tikz} +\begin{document} +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse (\p cm and 1 cm); +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse (1 cm and \p cm); +\end{document} + +``` + +problem with the parser, I suppose ! and the remark of Jake is fine, better now it's to use `x radius` and `y radius`" +13124,"``` +\documentclass{article} + +\usepackage{tikz} + +\begin{document} + +% DOES NOT WORK +%\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse (\p and 1); + +%WORKS +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse (1 and \p); + +\end{document} + +``` + +`(1 and \p)` works but `(\p and 1)` does not, why?",2011/03/10,"['https://tex.stackexchange.com/questions/13124', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/2099/']","Spaces after TeX commands are ignored, thus by using `\p and 1` you'll get an equivalent of, say, `1and 1`, which you can verify to give the same error. Therefore we just need to restore the space: + +``` +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse (\p{} and 1); + +``` + +Note that, as Jake mentions, this syntax is deprecated (refer to the [TikZ manual](http://ctan.org/pkg/pgf)).","The `( and )` syntax is old and, if not deprecated, at least not encouraged any more. The current way to do is is to use `[x radius]` and `[y radius]`: + +``` +\documentclass{article} + +\usepackage{tikz} + +\begin{document} + +% WORKS with current syntax +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse [x radius=\p, y radius=1]; + +%WORKS +\tikz \foreach \p in {1,2,...,3} \draw (\p,0) ellipse [x radius=1, y radius=\p]; + +\end{document} + +```" +26009586,"I've had a look into the Documentation and Examples (`http://83.212.101.132/`) but I can't find anything. + +Is it even possible? + +In large scale projects, like the one I'm working on right now, I most definitely prefer to use OOP. And not being able to support it would be a big letdown.",2014/09/24,"['https://Stackoverflow.com/questions/26009586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4037009/']","I assume you have a toolchain that lets you build applications for your embedded linux platform. This should include gdb (named something like arm-linux-gdb). + +Next check if linux for your board already includes gdb/gdbserver. If it does, you don't have to build anything. If it does not, configure gdb like this: + +``` +./path/to/gdb/source/configure --host=arm-linux --target=arm-linux --prefix=/path/to/installation/directory +``` + +Then make and make install. +Note that --host and --target will probably match your toolchains prefix. + +As part of this installation you will get gdbserver. Install it on your board. + +Then use it, as explained [here](https://sourceware.org/gdb/current/onlinedocs/gdb/Server.html). It depends on your connection type (TCP, serial), but you need to run program under gdbserver on board (gdbserver binary), then run you toolchain's gdb on PC and connect to board using ""target remote"" command.","Remote debugging of embedded systems: GDB, as a server, must be compiled into the debugging target build in order to support connected GDB clients. When running on the client side, there must exist a copy of the target source as well as an unstripped (of symbols) version of the executable. + +GCC compilation should be done with the -g flag. + +On the target/server side, run with + +gdbserver --attach or gdbserver host: +On the client side, run gdb and then + +(gdb) target remote IP:PORT +What gdb client to run? Must be built with the right target processor in mind, for example + +.../toolchain/bin/powerpc-linux-gdb core/mydaemon/src/mydaemon -x gdb-command-script +-x is a filename option + +Hope this helps!" +26009586,"I've had a look into the Documentation and Examples (`http://83.212.101.132/`) but I can't find anything. + +Is it even possible? + +In large scale projects, like the one I'm working on right now, I most definitely prefer to use OOP. And not being able to support it would be a big letdown.",2014/09/24,"['https://Stackoverflow.com/questions/26009586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4037009/']","Have you already looked at [Buildroot](http://buildroot.uclibc.org/)? It will take care of cross-compiler and root file system. You can choose to compile host and target gdb/gdbserver, so that you'll have everything from one hand. See BR's [documentation](http://nightly.buildroot.org/manual.html#_advanced_usage).","Remote debugging of embedded systems: GDB, as a server, must be compiled into the debugging target build in order to support connected GDB clients. When running on the client side, there must exist a copy of the target source as well as an unstripped (of symbols) version of the executable. + +GCC compilation should be done with the -g flag. + +On the target/server side, run with + +gdbserver --attach or gdbserver host: +On the client side, run gdb and then + +(gdb) target remote IP:PORT +What gdb client to run? Must be built with the right target processor in mind, for example + +.../toolchain/bin/powerpc-linux-gdb core/mydaemon/src/mydaemon -x gdb-command-script +-x is a filename option + +Hope this helps!" +26009586,"I've had a look into the Documentation and Examples (`http://83.212.101.132/`) but I can't find anything. + +Is it even possible? + +In large scale projects, like the one I'm working on right now, I most definitely prefer to use OOP. And not being able to support it would be a big letdown.",2014/09/24,"['https://Stackoverflow.com/questions/26009586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4037009/']","Remote debugging of embedded systems: +GDB, as a server, must be compiled into the debugging target build in order to support connected GDB clients. When running on the client side, there must exist a copy of the target source as well as an unstripped (of symbols) version of the executable. + +GCC compilation should be done with the -g flag. + +On the target/server side, run with + +``` +gdbserver --attach or gdbserver host: + +``` + +On the client side, run gdb and then + +``` +(gdb) target remote IP:PORT + +``` + +What gdb client to run? Must be built with the right target processor in mind, for example + +``` +.../toolchain/bin/powerpc-linux-gdb core/mydaemon/src/mydaemon -x gdb-command-script + +``` + +-x is a filename option + +Hope this helps!","Remote debugging of embedded systems: GDB, as a server, must be compiled into the debugging target build in order to support connected GDB clients. When running on the client side, there must exist a copy of the target source as well as an unstripped (of symbols) version of the executable. + +GCC compilation should be done with the -g flag. + +On the target/server side, run with + +gdbserver --attach or gdbserver host: +On the client side, run gdb and then + +(gdb) target remote IP:PORT +What gdb client to run? Must be built with the right target processor in mind, for example + +.../toolchain/bin/powerpc-linux-gdb core/mydaemon/src/mydaemon -x gdb-command-script +-x is a filename option + +Hope this helps!" +29234,"In an upcoming campaign I'm planning, I would like a combat encounter to take place on a small sphere, with gravity pointing in towards the center. I'd like a sphere about 50' in diameter - something large enough to allow plenty of movement on its surface, but small enough so that players can typically run around it in a few turns. + +My problem is setting up the map. My first thought is to purchase a to-scale foam craft sphere, and provide miniatures with small pins so that they stick into the ""board."" The problem with this, tho, is that I would either need to draw on a geodesic grid by hand or go grid-less, which my group has not done before. + +My second thought is to simply use a flat map with ""wrapping"" edges, so that it acts somewhat sphere-like. The problems with this are that it distorts the distances greatly, and, more importantly, doesn't show the affect that the curvature of the sphere has on line-of-sight. I could get around this by imposing a circular limit to line-of-sight, but I feel it loses much of the effect. + +Has anyone attempted to run grid-based combat on a non-flat surface like this? What tools and rules made the combat go smoothly without ignoring important aspects of the unique terrain?",2013/10/07,"['https://rpg.stackexchange.com/questions/29234', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/2161/']","The line-of-sight benefits are not actually very much, if any. If you've every played wargames with model-based LOS, you're familiar with the excruciating process of eyeballing, using bits of string, and finally arguing over whether being able to draw LOS to a teeny bit of the tip of a sword sticking up above terrain counts as having LOS or not. + +Using real LOS, you lose much of the time saved by using a grid. Either go gridless on a sphere and measure everything in real inches, or use a flat, imprecise abstraction with extra LOS limits and movement rules to roughly emulate a spherical surface. Besides which, there's no good tiling of squares onto a sphere that doesn't introduce aberrations in how they connect to each other. To get regularity you have to use a different tile shape, at which point you'd have to make up new rules for adjacency and AOE coverage.","If you are free to alter the dimensions of your planet, you can use any [one of these nice projections](http://en.wikipedia.org/wiki/List_of_map_projections) of a sphere's surface. + +Note that the projections have 24 squares across and top to bottom (15 degrees lat/long each) ie. a 24x24 grid. At 5' per grid square you end up with a circumference of 120' and a 19' radius. + +Note that most projections lose a lot of latitude squares near the poles. + +Now the trick becomes distance to visual horizon. But again the internet provides a [handy calculator](http://www.neoprogrammics.com/spheres/distance_to_horizon.php). + +Using this tool, assuming 6' person gives a surface to horizon of 13'. Making an assumption that double that is hidden. So absolute LOS = 26' = 5 or 6 squares. For fun give anyone in squares 5 and 6 a cover save." +29234,"In an upcoming campaign I'm planning, I would like a combat encounter to take place on a small sphere, with gravity pointing in towards the center. I'd like a sphere about 50' in diameter - something large enough to allow plenty of movement on its surface, but small enough so that players can typically run around it in a few turns. + +My problem is setting up the map. My first thought is to purchase a to-scale foam craft sphere, and provide miniatures with small pins so that they stick into the ""board."" The problem with this, tho, is that I would either need to draw on a geodesic grid by hand or go grid-less, which my group has not done before. + +My second thought is to simply use a flat map with ""wrapping"" edges, so that it acts somewhat sphere-like. The problems with this are that it distorts the distances greatly, and, more importantly, doesn't show the affect that the curvature of the sphere has on line-of-sight. I could get around this by imposing a circular limit to line-of-sight, but I feel it loses much of the effect. + +Has anyone attempted to run grid-based combat on a non-flat surface like this? What tools and rules made the combat go smoothly without ignoring important aspects of the unique terrain?",2013/10/07,"['https://rpg.stackexchange.com/questions/29234', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/2161/']","The line-of-sight benefits are not actually very much, if any. If you've every played wargames with model-based LOS, you're familiar with the excruciating process of eyeballing, using bits of string, and finally arguing over whether being able to draw LOS to a teeny bit of the tip of a sword sticking up above terrain counts as having LOS or not. + +Using real LOS, you lose much of the time saved by using a grid. Either go gridless on a sphere and measure everything in real inches, or use a flat, imprecise abstraction with extra LOS limits and movement rules to roughly emulate a spherical surface. Besides which, there's no good tiling of squares onto a sphere that doesn't introduce aberrations in how they connect to each other. To get regularity you have to use a different tile shape, at which point you'd have to make up new rules for adjacency and AOE coverage.","3d movement in D&D is made by dividing the space in cubes. Each cube that's less than 50% filled is a void space, each cube that's not is all filled. If you build a sphere made of cubes you'll get sections similar to a small circle drawn in Paint. + +If you get a sphere, sunlight (which rays are parallel) and a transparent sheet with parallel lines you can trace the projection of these lines on the sphere. Rotating the sphere exactly 90° on the 3 axis of the sheet will get you a gridded sheet. The elements of the grid near to the axes will be squared, and the boundaries between those areas will feature triangular elements. + +It's fine, I've explained earlier what they are, corners of a cube. Despite being triangular, they still count as squares. + +--- + +As an alternative, this really is a cube, but it looks like a sphere + +[![One practical way to map a square grid to a sphere](https://i.stack.imgur.com/EiHe4.jpg)](https://i.stack.imgur.com/EiHe4.jpg)" +29234,"In an upcoming campaign I'm planning, I would like a combat encounter to take place on a small sphere, with gravity pointing in towards the center. I'd like a sphere about 50' in diameter - something large enough to allow plenty of movement on its surface, but small enough so that players can typically run around it in a few turns. + +My problem is setting up the map. My first thought is to purchase a to-scale foam craft sphere, and provide miniatures with small pins so that they stick into the ""board."" The problem with this, tho, is that I would either need to draw on a geodesic grid by hand or go grid-less, which my group has not done before. + +My second thought is to simply use a flat map with ""wrapping"" edges, so that it acts somewhat sphere-like. The problems with this are that it distorts the distances greatly, and, more importantly, doesn't show the affect that the curvature of the sphere has on line-of-sight. I could get around this by imposing a circular limit to line-of-sight, but I feel it loses much of the effect. + +Has anyone attempted to run grid-based combat on a non-flat surface like this? What tools and rules made the combat go smoothly without ignoring important aspects of the unique terrain?",2013/10/07,"['https://rpg.stackexchange.com/questions/29234', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/2161/']","Mike Krahulik of Penny Arcade modeled spherical, planar combat in *[D&D in the Elemental Chaos part 1](http://www.penny-arcade.com/2010/06/28/dd-in-the-elemental-chaos-part-1)* and *[D&D in the Elemental Chaos part 2](http://www.penny-arcade.com/2010/06/30/dd-in-the-elemental-chaos-part-2)*. + +A concern exists that LOE and AOE in Krahulik's models, as well as, prolonged combat and movement were not possible in the models documented. + +However, both context of Krahulik's efforts and his entries, he notes that the oddites of modeling the grid on the sphere as well as the success of the models in play. + +Krahulik talks about ""...I was drawing these squares on a curved surface they got sort of wonky in some places, but that is why **I made separate [areas] of grid zones on each planet.**"" The photo of these grids clearly shows Krahulik ""solving for wonky"" with compromises to aesthetic problems by ignoring the curvature of the sphere and scale at the polar coordinates. + +![enter image description here](https://i.stack.imgur.com/Qs5qf.jpg) + +Image © Copyright 1998-2013 Penny Arcade, Inc. + +The disconnected grid addresses the ""wonkiness"" as well as LOS...and likely solved for AOE too (constrained within the ""separate areas of grid zones""). Nearby grid zones could be handled as a ""hand wave"" or even built-in as player-GM expectation. + +Both articles are great resources for creatively solving a problem and delivering an exciting table experience. + +**Hexagons** + +Read [*Geodesic Discrete Global Grid Systems*](http://webpages.sou.edu/~sahrk/dgg/pubs/gdggs03.pdf) by Kevin Sahr, Denis White, and A. Jon Kimerling. I skimmed it, but it offers some great ideas to **achieve full coverage with hexagons.** The research is quite detailed and expounds at length regarding the popularity and resolution available with hexagons.","If you are free to alter the dimensions of your planet, you can use any [one of these nice projections](http://en.wikipedia.org/wiki/List_of_map_projections) of a sphere's surface. + +Note that the projections have 24 squares across and top to bottom (15 degrees lat/long each) ie. a 24x24 grid. At 5' per grid square you end up with a circumference of 120' and a 19' radius. + +Note that most projections lose a lot of latitude squares near the poles. + +Now the trick becomes distance to visual horizon. But again the internet provides a [handy calculator](http://www.neoprogrammics.com/spheres/distance_to_horizon.php). + +Using this tool, assuming 6' person gives a surface to horizon of 13'. Making an assumption that double that is hidden. So absolute LOS = 26' = 5 or 6 squares. For fun give anyone in squares 5 and 6 a cover save." +29234,"In an upcoming campaign I'm planning, I would like a combat encounter to take place on a small sphere, with gravity pointing in towards the center. I'd like a sphere about 50' in diameter - something large enough to allow plenty of movement on its surface, but small enough so that players can typically run around it in a few turns. + +My problem is setting up the map. My first thought is to purchase a to-scale foam craft sphere, and provide miniatures with small pins so that they stick into the ""board."" The problem with this, tho, is that I would either need to draw on a geodesic grid by hand or go grid-less, which my group has not done before. + +My second thought is to simply use a flat map with ""wrapping"" edges, so that it acts somewhat sphere-like. The problems with this are that it distorts the distances greatly, and, more importantly, doesn't show the affect that the curvature of the sphere has on line-of-sight. I could get around this by imposing a circular limit to line-of-sight, but I feel it loses much of the effect. + +Has anyone attempted to run grid-based combat on a non-flat surface like this? What tools and rules made the combat go smoothly without ignoring important aspects of the unique terrain?",2013/10/07,"['https://rpg.stackexchange.com/questions/29234', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/2161/']","Mike Krahulik of Penny Arcade modeled spherical, planar combat in *[D&D in the Elemental Chaos part 1](http://www.penny-arcade.com/2010/06/28/dd-in-the-elemental-chaos-part-1)* and *[D&D in the Elemental Chaos part 2](http://www.penny-arcade.com/2010/06/30/dd-in-the-elemental-chaos-part-2)*. + +A concern exists that LOE and AOE in Krahulik's models, as well as, prolonged combat and movement were not possible in the models documented. + +However, both context of Krahulik's efforts and his entries, he notes that the oddites of modeling the grid on the sphere as well as the success of the models in play. + +Krahulik talks about ""...I was drawing these squares on a curved surface they got sort of wonky in some places, but that is why **I made separate [areas] of grid zones on each planet.**"" The photo of these grids clearly shows Krahulik ""solving for wonky"" with compromises to aesthetic problems by ignoring the curvature of the sphere and scale at the polar coordinates. + +![enter image description here](https://i.stack.imgur.com/Qs5qf.jpg) + +Image © Copyright 1998-2013 Penny Arcade, Inc. + +The disconnected grid addresses the ""wonkiness"" as well as LOS...and likely solved for AOE too (constrained within the ""separate areas of grid zones""). Nearby grid zones could be handled as a ""hand wave"" or even built-in as player-GM expectation. + +Both articles are great resources for creatively solving a problem and delivering an exciting table experience. + +**Hexagons** + +Read [*Geodesic Discrete Global Grid Systems*](http://webpages.sou.edu/~sahrk/dgg/pubs/gdggs03.pdf) by Kevin Sahr, Denis White, and A. Jon Kimerling. I skimmed it, but it offers some great ideas to **achieve full coverage with hexagons.** The research is quite detailed and expounds at length regarding the popularity and resolution available with hexagons.","3d movement in D&D is made by dividing the space in cubes. Each cube that's less than 50% filled is a void space, each cube that's not is all filled. If you build a sphere made of cubes you'll get sections similar to a small circle drawn in Paint. + +If you get a sphere, sunlight (which rays are parallel) and a transparent sheet with parallel lines you can trace the projection of these lines on the sphere. Rotating the sphere exactly 90° on the 3 axis of the sheet will get you a gridded sheet. The elements of the grid near to the axes will be squared, and the boundaries between those areas will feature triangular elements. + +It's fine, I've explained earlier what they are, corners of a cube. Despite being triangular, they still count as squares. + +--- + +As an alternative, this really is a cube, but it looks like a sphere + +[![One practical way to map a square grid to a sphere](https://i.stack.imgur.com/EiHe4.jpg)](https://i.stack.imgur.com/EiHe4.jpg)" +29234,"In an upcoming campaign I'm planning, I would like a combat encounter to take place on a small sphere, with gravity pointing in towards the center. I'd like a sphere about 50' in diameter - something large enough to allow plenty of movement on its surface, but small enough so that players can typically run around it in a few turns. + +My problem is setting up the map. My first thought is to purchase a to-scale foam craft sphere, and provide miniatures with small pins so that they stick into the ""board."" The problem with this, tho, is that I would either need to draw on a geodesic grid by hand or go grid-less, which my group has not done before. + +My second thought is to simply use a flat map with ""wrapping"" edges, so that it acts somewhat sphere-like. The problems with this are that it distorts the distances greatly, and, more importantly, doesn't show the affect that the curvature of the sphere has on line-of-sight. I could get around this by imposing a circular limit to line-of-sight, but I feel it loses much of the effect. + +Has anyone attempted to run grid-based combat on a non-flat surface like this? What tools and rules made the combat go smoothly without ignoring important aspects of the unique terrain?",2013/10/07,"['https://rpg.stackexchange.com/questions/29234', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/2161/']","I would print out a [flattened geodesic sphere](http://sci-toys.com/scitoys/scitoys/mathematics/dome/paper_dome/color_complete.gif) for the minis alongside a printed out and [assembled version of the same](http://sci-toys.com/scitoys/scitoys/mathematics/dome/dome.html#paper_dome), using post-it notes or similar to reference where the minis map to on the sphere. + +For movement, it's triangles instead of squares. Movement along a side is adjacent triangles. I would probably disallow movement across corners, just to make things simpler.","If you are free to alter the dimensions of your planet, you can use any [one of these nice projections](http://en.wikipedia.org/wiki/List_of_map_projections) of a sphere's surface. + +Note that the projections have 24 squares across and top to bottom (15 degrees lat/long each) ie. a 24x24 grid. At 5' per grid square you end up with a circumference of 120' and a 19' radius. + +Note that most projections lose a lot of latitude squares near the poles. + +Now the trick becomes distance to visual horizon. But again the internet provides a [handy calculator](http://www.neoprogrammics.com/spheres/distance_to_horizon.php). + +Using this tool, assuming 6' person gives a surface to horizon of 13'. Making an assumption that double that is hidden. So absolute LOS = 26' = 5 or 6 squares. For fun give anyone in squares 5 and 6 a cover save." +29234,"In an upcoming campaign I'm planning, I would like a combat encounter to take place on a small sphere, with gravity pointing in towards the center. I'd like a sphere about 50' in diameter - something large enough to allow plenty of movement on its surface, but small enough so that players can typically run around it in a few turns. + +My problem is setting up the map. My first thought is to purchase a to-scale foam craft sphere, and provide miniatures with small pins so that they stick into the ""board."" The problem with this, tho, is that I would either need to draw on a geodesic grid by hand or go grid-less, which my group has not done before. + +My second thought is to simply use a flat map with ""wrapping"" edges, so that it acts somewhat sphere-like. The problems with this are that it distorts the distances greatly, and, more importantly, doesn't show the affect that the curvature of the sphere has on line-of-sight. I could get around this by imposing a circular limit to line-of-sight, but I feel it loses much of the effect. + +Has anyone attempted to run grid-based combat on a non-flat surface like this? What tools and rules made the combat go smoothly without ignoring important aspects of the unique terrain?",2013/10/07,"['https://rpg.stackexchange.com/questions/29234', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/2161/']","I would print out a [flattened geodesic sphere](http://sci-toys.com/scitoys/scitoys/mathematics/dome/paper_dome/color_complete.gif) for the minis alongside a printed out and [assembled version of the same](http://sci-toys.com/scitoys/scitoys/mathematics/dome/dome.html#paper_dome), using post-it notes or similar to reference where the minis map to on the sphere. + +For movement, it's triangles instead of squares. Movement along a side is adjacent triangles. I would probably disallow movement across corners, just to make things simpler.","3d movement in D&D is made by dividing the space in cubes. Each cube that's less than 50% filled is a void space, each cube that's not is all filled. If you build a sphere made of cubes you'll get sections similar to a small circle drawn in Paint. + +If you get a sphere, sunlight (which rays are parallel) and a transparent sheet with parallel lines you can trace the projection of these lines on the sphere. Rotating the sphere exactly 90° on the 3 axis of the sheet will get you a gridded sheet. The elements of the grid near to the axes will be squared, and the boundaries between those areas will feature triangular elements. + +It's fine, I've explained earlier what they are, corners of a cube. Despite being triangular, they still count as squares. + +--- + +As an alternative, this really is a cube, but it looks like a sphere + +[![One practical way to map a square grid to a sphere](https://i.stack.imgur.com/EiHe4.jpg)](https://i.stack.imgur.com/EiHe4.jpg)" +29234,"In an upcoming campaign I'm planning, I would like a combat encounter to take place on a small sphere, with gravity pointing in towards the center. I'd like a sphere about 50' in diameter - something large enough to allow plenty of movement on its surface, but small enough so that players can typically run around it in a few turns. + +My problem is setting up the map. My first thought is to purchase a to-scale foam craft sphere, and provide miniatures with small pins so that they stick into the ""board."" The problem with this, tho, is that I would either need to draw on a geodesic grid by hand or go grid-less, which my group has not done before. + +My second thought is to simply use a flat map with ""wrapping"" edges, so that it acts somewhat sphere-like. The problems with this are that it distorts the distances greatly, and, more importantly, doesn't show the affect that the curvature of the sphere has on line-of-sight. I could get around this by imposing a circular limit to line-of-sight, but I feel it loses much of the effect. + +Has anyone attempted to run grid-based combat on a non-flat surface like this? What tools and rules made the combat go smoothly without ignoring important aspects of the unique terrain?",2013/10/07,"['https://rpg.stackexchange.com/questions/29234', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/2161/']","1. Buy a soccer ball +2. Add velcro +3. ??? +4. Profit + +On a more serious note, you'd need to sort out how movement would work, and possibly subdivide each patch into 5 or 6 triangles depending on the size of the pieces you're velcroing on. + +Additionally, you might want to prop the soccer ball up on stilts so that you could have units on the entire world.","If you are free to alter the dimensions of your planet, you can use any [one of these nice projections](http://en.wikipedia.org/wiki/List_of_map_projections) of a sphere's surface. + +Note that the projections have 24 squares across and top to bottom (15 degrees lat/long each) ie. a 24x24 grid. At 5' per grid square you end up with a circumference of 120' and a 19' radius. + +Note that most projections lose a lot of latitude squares near the poles. + +Now the trick becomes distance to visual horizon. But again the internet provides a [handy calculator](http://www.neoprogrammics.com/spheres/distance_to_horizon.php). + +Using this tool, assuming 6' person gives a surface to horizon of 13'. Making an assumption that double that is hidden. So absolute LOS = 26' = 5 or 6 squares. For fun give anyone in squares 5 and 6 a cover save." +29234,"In an upcoming campaign I'm planning, I would like a combat encounter to take place on a small sphere, with gravity pointing in towards the center. I'd like a sphere about 50' in diameter - something large enough to allow plenty of movement on its surface, but small enough so that players can typically run around it in a few turns. + +My problem is setting up the map. My first thought is to purchase a to-scale foam craft sphere, and provide miniatures with small pins so that they stick into the ""board."" The problem with this, tho, is that I would either need to draw on a geodesic grid by hand or go grid-less, which my group has not done before. + +My second thought is to simply use a flat map with ""wrapping"" edges, so that it acts somewhat sphere-like. The problems with this are that it distorts the distances greatly, and, more importantly, doesn't show the affect that the curvature of the sphere has on line-of-sight. I could get around this by imposing a circular limit to line-of-sight, but I feel it loses much of the effect. + +Has anyone attempted to run grid-based combat on a non-flat surface like this? What tools and rules made the combat go smoothly without ignoring important aspects of the unique terrain?",2013/10/07,"['https://rpg.stackexchange.com/questions/29234', 'https://rpg.stackexchange.com', 'https://rpg.stackexchange.com/users/2161/']","1. Buy a soccer ball +2. Add velcro +3. ??? +4. Profit + +On a more serious note, you'd need to sort out how movement would work, and possibly subdivide each patch into 5 or 6 triangles depending on the size of the pieces you're velcroing on. + +Additionally, you might want to prop the soccer ball up on stilts so that you could have units on the entire world.","3d movement in D&D is made by dividing the space in cubes. Each cube that's less than 50% filled is a void space, each cube that's not is all filled. If you build a sphere made of cubes you'll get sections similar to a small circle drawn in Paint. + +If you get a sphere, sunlight (which rays are parallel) and a transparent sheet with parallel lines you can trace the projection of these lines on the sphere. Rotating the sphere exactly 90° on the 3 axis of the sheet will get you a gridded sheet. The elements of the grid near to the axes will be squared, and the boundaries between those areas will feature triangular elements. + +It's fine, I've explained earlier what they are, corners of a cube. Despite being triangular, they still count as squares. + +--- + +As an alternative, this really is a cube, but it looks like a sphere + +[![One practical way to map a square grid to a sphere](https://i.stack.imgur.com/EiHe4.jpg)](https://i.stack.imgur.com/EiHe4.jpg)" +34569249,"I saw the following program on a site and I cannot understand the output . + + +``` +#include +using namespace std; + +int i; + +class A +{ +public: + ~A() + { + i=10; + } +}; + +int foo() +{ + i=3; + A ob; + return i; +} + +int main() +{ + cout <<""\n 1) Before calling i is ""< +> why did i see this and where exactly is destruction getting called . +> +> +> + +I believe the instance destructor is called when that instance goes out of scope. You might test it the following way (by controlling the scope of the instance -- see bar() below) + +Note - to reduce confusion, I 1) renamed the global and 2) explicitly controlled when the foo or bar is called w.r.t. subsequent cout. + +``` +int g; // uninitialized! + +class A +{ +public: + ~A() + { + g=10; + } +}; + +int foo() +{ + g=3; + A ob; + return g; +} // <<<<<<<<<<< ob destructor called here + +int bar() +{ + g=3; + { + A ob; + } // <<<<<<<<<<< ob destructor called here + return g; +} + +int t272(void) +{ + g = 0; // force to 0 + std::cout << ""\n 1) Before calling foo g is "" << g; + + int fooRetVal = foo(); // control when called + // do not leave up to compiler + + std::cout << ""\n 2) after foo, g = "" << g + << ""\n 3) fooRetVal = "" << fooRetVal + << ""\n 4) and now g = "" << g + << std::endl; + + g = 0; // force to 0 + std::cout << ""\n 1) Before calling bar g is "" << g; + + int barRetVal = bar(); // control when called + // do not leave up to compiler + + std::cout << ""\n 2) after bar, g = "" << g + << ""\n 3) barRetVal = "" << barRetVal + << ""\n 4) and now g = "" << g + << std::endl; + + return (0); +} + +``` + +With the output + +``` +1) Before calling foo g is 0 +2) after foo, g = 10 +3) fooRetVal = 3 <<< dtor called after return of foo +4) and now g = 10 + +1) Before calling bar g is 0 +2) after bar, g = 10 +3) barRetVal = 10 <<< dtor was called before return of bar +4) and now g = 10 + +```" +34569249,"I saw the following program on a site and I cannot understand the output . + + +``` +#include +using namespace std; + +int i; + +class A +{ +public: + ~A() + { + i=10; + } +}; + +int foo() +{ + i=3; + A ob; + return i; +} + +int main() +{ + cout <<""\n 1) Before calling i is ""< +> why did i see this and where exactly is destruction getting called . +> +> +> + +I believe the instance destructor is called when that instance goes out of scope. You might test it the following way (by controlling the scope of the instance -- see bar() below) + +Note - to reduce confusion, I 1) renamed the global and 2) explicitly controlled when the foo or bar is called w.r.t. subsequent cout. + +``` +int g; // uninitialized! + +class A +{ +public: + ~A() + { + g=10; + } +}; + +int foo() +{ + g=3; + A ob; + return g; +} // <<<<<<<<<<< ob destructor called here + +int bar() +{ + g=3; + { + A ob; + } // <<<<<<<<<<< ob destructor called here + return g; +} + +int t272(void) +{ + g = 0; // force to 0 + std::cout << ""\n 1) Before calling foo g is "" << g; + + int fooRetVal = foo(); // control when called + // do not leave up to compiler + + std::cout << ""\n 2) after foo, g = "" << g + << ""\n 3) fooRetVal = "" << fooRetVal + << ""\n 4) and now g = "" << g + << std::endl; + + g = 0; // force to 0 + std::cout << ""\n 1) Before calling bar g is "" << g; + + int barRetVal = bar(); // control when called + // do not leave up to compiler + + std::cout << ""\n 2) after bar, g = "" << g + << ""\n 3) barRetVal = "" << barRetVal + << ""\n 4) and now g = "" << g + << std::endl; + + return (0); +} + +``` + +With the output + +``` +1) Before calling foo g is 0 +2) after foo, g = 10 +3) fooRetVal = 3 <<< dtor called after return of foo +4) and now g = 10 + +1) Before calling bar g is 0 +2) after bar, g = 10 +3) barRetVal = 10 <<< dtor was called before return of bar +4) and now g = 10 + +```" +39332,"> +> [Galatians 5:19 Now](https://biblehub.com/galatians/5-19.htm) the works of the flesh are manifest, which are +> these; Adultery, fornication, uncleanness, lasciviousness, +> +> +> + +What is the difference between adultery, fornication, uncleanness & lasciviousness in the verse above? I looked into the Greek from [this website](http://www.godrules.net/library/kjvstrongs/kjvstrongsgal5.htm) but could not understand well.",2019/03/06,"['https://hermeneutics.stackexchange.com/questions/39332', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/26800/']","The word ἀδελφός (adelphos) occurs well over 300 times in the NT for which BDAG has two basic meanings: + +> +> (1) **a male from the same womb as the reference person, *brother***, +> eg, **Matt 1:2, 11, 4:18, 21, Gal 1:19**, etc. … Hence there is no +> doubt that in Luke 21:16 that the plural ""adelphoi"" = brothers and +> sisters … +> +> +> **(2) a person viewed as a brother in terms of a close affinity, *brother, fellow member, member, associate*** +> +> +> (a) one who shares beliefs eg, matt 12:50, Mark 3:35 … +> +> +> (b) a compatriot Lev 10:4, 15:3, 12, 17:15, Acts 2:29, 3:17 etc. +> +> +> (c) without reference to a common nationality or faith, neighbor 9or +> an intimate friend), eg, Matt 5:22, 7:3, etc. +> +> +> (d) Form of addressused by a king to persons in very high position - +> (used in classical, non-Biblical literature) +> +> +> + +I have only included the highlights from BDAG to provide the general idea. For more detail consult BDAG. However, it appears correct that ""adelphos"" can, indeed, be used in the sense of fellow countryman or compatriot, or even close associate.","In I John 2:12, the very next verse, John speaks to 'little children'. + +In such a context, it is my own understanding that the 'brother' referred to in the previous few verses would be a sibling. Or like a sibling - namely a brother in Christ. + +To hate one's own Christian brother is a terrible thing. I believe that is what John is talking about." +39332,"> +> [Galatians 5:19 Now](https://biblehub.com/galatians/5-19.htm) the works of the flesh are manifest, which are +> these; Adultery, fornication, uncleanness, lasciviousness, +> +> +> + +What is the difference between adultery, fornication, uncleanness & lasciviousness in the verse above? I looked into the Greek from [this website](http://www.godrules.net/library/kjvstrongs/kjvstrongsgal5.htm) but could not understand well.",2019/03/06,"['https://hermeneutics.stackexchange.com/questions/39332', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/26800/']","The word ἀδελφός (adelphos) occurs well over 300 times in the NT for which BDAG has two basic meanings: + +> +> (1) **a male from the same womb as the reference person, *brother***, +> eg, **Matt 1:2, 11, 4:18, 21, Gal 1:19**, etc. … Hence there is no +> doubt that in Luke 21:16 that the plural ""adelphoi"" = brothers and +> sisters … +> +> +> **(2) a person viewed as a brother in terms of a close affinity, *brother, fellow member, member, associate*** +> +> +> (a) one who shares beliefs eg, matt 12:50, Mark 3:35 … +> +> +> (b) a compatriot Lev 10:4, 15:3, 12, 17:15, Acts 2:29, 3:17 etc. +> +> +> (c) without reference to a common nationality or faith, neighbor 9or +> an intimate friend), eg, Matt 5:22, 7:3, etc. +> +> +> (d) Form of addressused by a king to persons in very high position - +> (used in classical, non-Biblical literature) +> +> +> + +I have only included the highlights from BDAG to provide the general idea. For more detail consult BDAG. However, it appears correct that ""adelphos"" can, indeed, be used in the sense of fellow countryman or compatriot, or even close associate.","The definition is found in Greek Lexicon de Thayer: Thayer’s Greek Lexicon Strong’s NT 80: ἀδελφός ἀδελφός, (οῦ, ὁ (from ἆ copulative and δελφύς, **from the same womb**), however, the word was used for the father Jacob in Genesis 37:3-4 with four different wives (septuagint). There was an advance of meaning of the word for Jacob. All these were brother cousins (adelphos) by the same father." +39332,"> +> [Galatians 5:19 Now](https://biblehub.com/galatians/5-19.htm) the works of the flesh are manifest, which are +> these; Adultery, fornication, uncleanness, lasciviousness, +> +> +> + +What is the difference between adultery, fornication, uncleanness & lasciviousness in the verse above? I looked into the Greek from [this website](http://www.godrules.net/library/kjvstrongs/kjvstrongsgal5.htm) but could not understand well.",2019/03/06,"['https://hermeneutics.stackexchange.com/questions/39332', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/26800/']","The word ἀδελφός (adelphos) occurs well over 300 times in the NT for which BDAG has two basic meanings: + +> +> (1) **a male from the same womb as the reference person, *brother***, +> eg, **Matt 1:2, 11, 4:18, 21, Gal 1:19**, etc. … Hence there is no +> doubt that in Luke 21:16 that the plural ""adelphoi"" = brothers and +> sisters … +> +> +> **(2) a person viewed as a brother in terms of a close affinity, *brother, fellow member, member, associate*** +> +> +> (a) one who shares beliefs eg, matt 12:50, Mark 3:35 … +> +> +> (b) a compatriot Lev 10:4, 15:3, 12, 17:15, Acts 2:29, 3:17 etc. +> +> +> (c) without reference to a common nationality or faith, neighbor 9or +> an intimate friend), eg, Matt 5:22, 7:3, etc. +> +> +> (d) Form of addressused by a king to persons in very high position - +> (used in classical, non-Biblical literature) +> +> +> + +I have only included the highlights from BDAG to provide the general idea. For more detail consult BDAG. However, it appears correct that ""adelphos"" can, indeed, be used in the sense of fellow countryman or compatriot, or even close associate.","**What's the meaning of brother in 1 John 2.9-11?** + +In context of John's writings,the expression ""brothers"" refers to the anointed brothers of Christ, more commonly known as ""saints"" they are also referred to as ""the least of these brothers or sisters of mine. + +Matthew 25:40 NET + +> +> 40"" And the king will answer them,[d] ‘I tell you the truth,[e] just +> as you did it for one of **the least of these brothers** or sisters[f] of +> mine, you did it for me."" +> +> +>" +34459128,"I have Form1 and Form2 simultaneously active, Form2 has a TabControl and I want button click event on Form1 to change 'Enable' property of tabControl on Form2 + +TabControl on Form2 is set to `tabControl1.enabled = false;` and Form1 acts as a login form for Form2, so I need a Login button on Form1 to enable 'tabControl1' on Form2 + +I can access the property by setting `private System.Windows.Forms.TabControl tabControl1;` to 'Public', still, using the following on button click event on Form1 doesn't do anything. + +``` +Form2 formnew2 = new Form2(); +formnew2.tabControl1.Enabled = true; + +``` + +Can someone please provide a simple example to help me understand or link to a previously answered question",2015/12/25,"['https://Stackoverflow.com/questions/34459128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2095012/']","You get this error since `xxxSlider.value` is of type `Float`, whereas `UIColor` initialiser calls for type `CGFloat` for all four arguments. + +You can redeem this error by changing the line into: + +``` +colorView.backgroundColor = UIColor(red: CGFloat(redSlider.value), green: CGFloat(greenSlider.value), blue: CGFloat(blueSlider.value), alpha: 1.0) + +``` + +However, to achieve the goal of your program, there are more issues that needs to be addressed. I'll go through these below. + +--- + +First of all, you have one `@IBAction` as well as one `@IBOutlet` connected to each slider. With former (action), the latter is really not needed. Hence, remove the `@IBOutlet` connections (code as well as connections) + +``` +@IBOutlet weak var redSlider: UISlider! // remove (also remove connection) +@IBOutlet weak var greenSlider: UISlider! // ... +@IBOutlet weak var blueSlider: UISlider! // ... + +``` + +Now, in your `@IBAction`:s, you define a local variable that is never used + +``` +var red = CGFloat(sender.value) // in @IBAction func redValueChanged(... +var green = CGFloat(sender.value) // ... +var blue = CGFloat(sender.value) // ... + +``` + +In their current form, you don't need these, so remove these also. + +Instead, in the scope of the class (see full program below), declare three class variables to hold the current value of each slide (note: these are not to be defined *within* a class method/action/function). Moreover, let these be of type `CGFloat` rather than `Float`, as initialiser of `UIColor` that we use to change background colour takes arguments of type `CGFloat`: + +``` +var redValue: CGFloat = 0.5 // 0.5: middle slider (init) +var greenValue: CGFloat = 0.5 +var blueValue: CGFloat = 0.5 + +``` + +In your `@IBAction` closures, change these class variables by the `sender.value` (which holds slider value). After update of variable value, call your `displayColors()` method (that we will look at shortly). + +``` +// Actions +@IBAction func redValueChanged(sender: UISlider) { + redValue = CGFloat(sender.value) + displayColors() +} + +@IBAction func greenValueChanged(sender: UISlider) { + greenValue = CGFloat(sender.value) + displayColors() +} + +@IBAction func blueValueChanged(sender: UISlider) { + blueValue = CGFloat(sender.value) + displayColors() +} + +``` + +Your `displayColors()` can be simplified simply to: + +``` +func displayColors() { + colorView.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0) +} + +``` + +Finally, not that the overridden method `viewDidLoad()` is only called once when the ViewController is loaded, so in this case, you can see this as an initialiser for your ViewController. The only thing we want to do here is set the default colour: RGB(0.5, 0.5, 0.5) = gray. + +``` +override func viewDidLoad() { + super.viewDidLoad() + + // Initial BG color (viewDidLoad() loads only once when ViewController view loads) + colorView.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0) +} + +``` + +And we're done! + +--- + +Wrapping it up, your ViewController class should now look like the following + +``` +import UIKit + +class ViewController: UIViewController { + + // Properties + var redValue: CGFloat = 0.5 + var greenValue: CGFloat = 0.5 + var blueValue: CGFloat = 0.5 + + @IBOutlet weak var colorView: UIView! + + // Actions + @IBAction func redValueChanged(sender: UISlider) { + redValue = CGFloat(sender.value) + displayColors() + } + + @IBAction func greenValueChanged(sender: UISlider) { + greenValue = CGFloat(sender.value) + displayColors() + } + + @IBAction func blueValueChanged(sender: UISlider) { + blueValue = CGFloat(sender.value) + displayColors() + } + + func displayColors() { + colorView.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0) + } + + override func viewDidLoad() { + super.viewDidLoad() + + // Initial BG color (viewDidLoad() loads only once when ViewController view loads) + colorView.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0) + } +} + +``` + +Running your app produces the following behaviour: + +[![enter image description here](https://i.stack.imgur.com/jJGuP.gif)](https://i.stack.imgur.com/jJGuP.gif)","`CGFloat` and `Float` are technically different types. The Swift programming language does not do any numeric type conversion / coercion. As such, you must explicitly convert from `Float` to `CGFloat` using one of the constructors on `CGFloat`. + +``` +colorView.backgroundColor = UIColor(red: CGFloat(redSlider.value), green: CGFloat(greenSlider.value), blue: CGFloat(blueSlider.value), alpha: 1.0) + +``` + +You can read more about [Numeric Type Conversion](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID324) in [The Swift Programming Language](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/)." +34459128,"I have Form1 and Form2 simultaneously active, Form2 has a TabControl and I want button click event on Form1 to change 'Enable' property of tabControl on Form2 + +TabControl on Form2 is set to `tabControl1.enabled = false;` and Form1 acts as a login form for Form2, so I need a Login button on Form1 to enable 'tabControl1' on Form2 + +I can access the property by setting `private System.Windows.Forms.TabControl tabControl1;` to 'Public', still, using the following on button click event on Form1 doesn't do anything. + +``` +Form2 formnew2 = new Form2(); +formnew2.tabControl1.Enabled = true; + +``` + +Can someone please provide a simple example to help me understand or link to a previously answered question",2015/12/25,"['https://Stackoverflow.com/questions/34459128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2095012/']","You get this error since `xxxSlider.value` is of type `Float`, whereas `UIColor` initialiser calls for type `CGFloat` for all four arguments. + +You can redeem this error by changing the line into: + +``` +colorView.backgroundColor = UIColor(red: CGFloat(redSlider.value), green: CGFloat(greenSlider.value), blue: CGFloat(blueSlider.value), alpha: 1.0) + +``` + +However, to achieve the goal of your program, there are more issues that needs to be addressed. I'll go through these below. + +--- + +First of all, you have one `@IBAction` as well as one `@IBOutlet` connected to each slider. With former (action), the latter is really not needed. Hence, remove the `@IBOutlet` connections (code as well as connections) + +``` +@IBOutlet weak var redSlider: UISlider! // remove (also remove connection) +@IBOutlet weak var greenSlider: UISlider! // ... +@IBOutlet weak var blueSlider: UISlider! // ... + +``` + +Now, in your `@IBAction`:s, you define a local variable that is never used + +``` +var red = CGFloat(sender.value) // in @IBAction func redValueChanged(... +var green = CGFloat(sender.value) // ... +var blue = CGFloat(sender.value) // ... + +``` + +In their current form, you don't need these, so remove these also. + +Instead, in the scope of the class (see full program below), declare three class variables to hold the current value of each slide (note: these are not to be defined *within* a class method/action/function). Moreover, let these be of type `CGFloat` rather than `Float`, as initialiser of `UIColor` that we use to change background colour takes arguments of type `CGFloat`: + +``` +var redValue: CGFloat = 0.5 // 0.5: middle slider (init) +var greenValue: CGFloat = 0.5 +var blueValue: CGFloat = 0.5 + +``` + +In your `@IBAction` closures, change these class variables by the `sender.value` (which holds slider value). After update of variable value, call your `displayColors()` method (that we will look at shortly). + +``` +// Actions +@IBAction func redValueChanged(sender: UISlider) { + redValue = CGFloat(sender.value) + displayColors() +} + +@IBAction func greenValueChanged(sender: UISlider) { + greenValue = CGFloat(sender.value) + displayColors() +} + +@IBAction func blueValueChanged(sender: UISlider) { + blueValue = CGFloat(sender.value) + displayColors() +} + +``` + +Your `displayColors()` can be simplified simply to: + +``` +func displayColors() { + colorView.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0) +} + +``` + +Finally, not that the overridden method `viewDidLoad()` is only called once when the ViewController is loaded, so in this case, you can see this as an initialiser for your ViewController. The only thing we want to do here is set the default colour: RGB(0.5, 0.5, 0.5) = gray. + +``` +override func viewDidLoad() { + super.viewDidLoad() + + // Initial BG color (viewDidLoad() loads only once when ViewController view loads) + colorView.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0) +} + +``` + +And we're done! + +--- + +Wrapping it up, your ViewController class should now look like the following + +``` +import UIKit + +class ViewController: UIViewController { + + // Properties + var redValue: CGFloat = 0.5 + var greenValue: CGFloat = 0.5 + var blueValue: CGFloat = 0.5 + + @IBOutlet weak var colorView: UIView! + + // Actions + @IBAction func redValueChanged(sender: UISlider) { + redValue = CGFloat(sender.value) + displayColors() + } + + @IBAction func greenValueChanged(sender: UISlider) { + greenValue = CGFloat(sender.value) + displayColors() + } + + @IBAction func blueValueChanged(sender: UISlider) { + blueValue = CGFloat(sender.value) + displayColors() + } + + func displayColors() { + colorView.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0) + } + + override func viewDidLoad() { + super.viewDidLoad() + + // Initial BG color (viewDidLoad() loads only once when ViewController view loads) + colorView.backgroundColor = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0) + } +} + +``` + +Running your app produces the following behaviour: + +[![enter image description here](https://i.stack.imgur.com/jJGuP.gif)](https://i.stack.imgur.com/jJGuP.gif)","In my app using Swift 4, I am using this to convert Float to CGFloat: + +``` +let slider = sender as? UISlider +let val = CGFloat((slider?.value)!) + +``` + +And then using the variable val as needed, which in my case is for hue, saturation and brightness, e.g. + +``` +coolButton.saturation = val + +```" +34459128,"I have Form1 and Form2 simultaneously active, Form2 has a TabControl and I want button click event on Form1 to change 'Enable' property of tabControl on Form2 + +TabControl on Form2 is set to `tabControl1.enabled = false;` and Form1 acts as a login form for Form2, so I need a Login button on Form1 to enable 'tabControl1' on Form2 + +I can access the property by setting `private System.Windows.Forms.TabControl tabControl1;` to 'Public', still, using the following on button click event on Form1 doesn't do anything. + +``` +Form2 formnew2 = new Form2(); +formnew2.tabControl1.Enabled = true; + +``` + +Can someone please provide a simple example to help me understand or link to a previously answered question",2015/12/25,"['https://Stackoverflow.com/questions/34459128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2095012/']","`CGFloat` and `Float` are technically different types. The Swift programming language does not do any numeric type conversion / coercion. As such, you must explicitly convert from `Float` to `CGFloat` using one of the constructors on `CGFloat`. + +``` +colorView.backgroundColor = UIColor(red: CGFloat(redSlider.value), green: CGFloat(greenSlider.value), blue: CGFloat(blueSlider.value), alpha: 1.0) + +``` + +You can read more about [Numeric Type Conversion](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID324) in [The Swift Programming Language](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/).","In my app using Swift 4, I am using this to convert Float to CGFloat: + +``` +let slider = sender as? UISlider +let val = CGFloat((slider?.value)!) + +``` + +And then using the variable val as needed, which in my case is for hue, saturation and brightness, e.g. + +``` +coolButton.saturation = val + +```" +92034,"The gospel of Matthew records that after Jesus’ death, the Pharisees and teachers of the Law went to Pilate to ask for a guard, since they remembered that Jesus said he would rise again on the third day. + +> +> “The next day, the one after Preparation Day, the chief priests and the Pharisees went to Pilate. “Sir,” they said, “we remember that while he was still alive that deceiver said, ‘After three days I will rise again.’ So give the order for the tomb to be made secure until the third day. Otherwise, his disciples may come and steal the body and tell the people that he has been raised from the dead. This last deception will be worse than the first.”” +> ‭‭Matthew‬ ‭27:62-64‬ ‭ +> +> +> + +However, part of the whole surprise of Jesus’ resurrection was that despite Jesus telling everyone he would rise again, the disciples still didn’t understand it. + +Further, the concept of a resurrection like the one of Jesus being physically resurrected was basically a new and radical concept that was not widely believed at all. + +So: + +How is it that the Jews would be aware of Jesus’ resurrecting on the third day when the disciples weren’t? + +And how can they have been so aware of it to the point of sending guards to the tomb? Was sending a guard to the tomb of a dead person even a common thing during that time if people don’t even rise from the dead? + +What happened to all the guards? If the tomb stone had been rolled away and people spread the rumour that Jesus’ body had been stolen, would the guards not have faced strong discipline for letting Jesus’ body be “stolen”? (in accordance with what Matthew writes about people believing the body was stolen) + +I don’t understand why a guard would be sent to the tomb of a dead person (especially since the Pharisees believed Jesus was just a human!), and I don’t understand how the Pharisees could remember that Jesus would rise from the dead on the third day (when the disciples couldn’t), yet also still spread a rumour that his body was stolen, especially if they knew they had guards there in the first place. + +I hear skeptics talk about how Matthew made up the guard story as an apologetic resource to defend the empty tomb, so if I could get some defence/ clarification on this and the questions above that would greatly help.",2022/07/30,"['https://christianity.stackexchange.com/questions/92034', 'https://christianity.stackexchange.com', 'https://christianity.stackexchange.com/users/59680/']","The Pharisees did not believe that a crucified Jesus of Nazareth would ever rise from the dead. Had they believed he was the foretold Messiah, they would have taken the possibility of that seriously. Given that they wanted this Jesus out of the way due to his claims, they wanted him to stay out of the way once they'd got the Roman authorities to crucify him. That was when they remembered that one of Jesus' claims while alive was that he would rise from the dead, and ***that*** made them think of tricks his disciples might employ to deceive people into thinking Christ was now alive. + +The verse you quote is very clear in showing their reasoning behind asking for a guard at the tomb: ""his disciples may come and steal the body and tell the people that he has been raised from the dead. This last deception will be worse than the first."" They'd also called Jesus *""that deceiver""* to Pilate, so they did not believe Jesus would actually arise (vs.63). + +This categorically proves that these men did ***not*** believe Jesus would rise from the dead. But given that, while alive, Jesus three times stated to his disciples that he would arise, the simple reason why the disciples were not full of faith about that was that Jesus' arrest and sentence to crucifixion was a bombshell, and they no doubt thought they could be rounded up next, hence the way they kept out of sight behind locked doors. They supposed Jesus would triumph over the Romans, not that the Romans would kill him! + +The Pharisees, however, knew that if a trick was played, with the corpse of Jesus taken away in the night, the disciples could then spread a story that he had been resurrected, and that deception would be far harder for them to deal with. So they asked Pilate for permission to set a seal and a guard over the tomb, that happened, and when the guards reported the miracle of the resurrection, they were bribed to spread the lie that, while they were asleep, the disciples came to do just that. + +It's very plainly stated in the gospel account. Why would skeptical disbelief about Matthew's account require more consideration than Matthew's account, for Matthew saw with his own eyes the resurrected Christ? There's no way Matthew would need to invent *""an apologetic resource to defend the empty tomb,""* when the empty tomb was the proof the disciples needed to restore their faith in Jesus' promise that, on the third day, he would be raised! Proof substantiated shortly after by the followers then seeing the living Christ, and even touching his wounds, and eating with him. Then when they went to the mountain specified in Galilee, he met with them to give parting instructions, and they saw him literally ascend, bodily, up into the sky till clouds hid him from their sight. + +So, **the answer to your main question is that the Pharisees did ***not*** anticipate Jesus' resurrection (at any time, let alone before the disciples started to believe in it). The Pharisees never, at any point, expected Jesus to arise from the dead.** They ***did*** expect the disciples to do a trick to deceive the populace that that had happened, and that was the reason for them getting a Roman guard placed, with a sealed stone over the tomb. Their actions were those of total disbelievers who wanted to second-guess the disciples. They guessed wrong, for the resurrection happened before any of the women followers even got to the tomb, to then tell the disciples they'd seen the risen Christ. The strange thing is that the last two sentences of the text you quote answers your question. And Matthew 28:11-15 deals with your other question about the guards.","**The Pharisees' reasoning** + +The Pharisees did not believe Jesus would rise on the third day. They knew that Jesus had prophesied it would happen, and they wanted to prevent anyone from believing the prophecy had been fulfilled through deception on the part of the disciples (by stealing the body). + +The Pharisees did not simply want to kill Jesus, they wanted to destroy His movement. Having Him put to death by crucifixion would be humiliating, and having Him put to death *by Rome* would intimate that His teachings were opposed by the might of Rome. The slow, tortuous death by crucifixion also afforded ample opportunity to mock Him as He suffered (see Matthew 27:39-43). + +They realized that if Jesus were thought to have risen from the dead, it could further strengthen His movement (it did). This is what is meant by ""This last deception will be worse than the first"". + +If the Pharisees genuinely believed Jesus was the Son God who would conquer death...of course they wouldn't have posted a guard! What chance would the guards have against the power of God? It was because the Pharisees *did not believe* in Jesus that the posting of the guard (to prevent theft of the body) made sense in their twisted, doubting minds. + +-- + +**The disciples' struggle to believe** + +That the promised Messiah would be put to death by Rome, rather than conquering Rome, was so foreign to contemporary thought that many of Jesus' followers genuinely entertained doubts when they saw Jesus arrested and put to death. Forasmuch as He had told Him it would happen, they were shocked and grieving. + +It is not that the Pharisees understood Jesus' prophecy and the disciples did not, rather: + +* The Pharisees didn't believe in Jesus before He died and still didn't believe after He died +* The disciples did believe in Jesus before He died and were struggling to believe after He died + +-- + +**The apologetic value of the story of the guards** + +Posting a guard at a tomb was not standard practice; it was specifically to prevent the theft of Jesus' body--which the Pharisees realized could fuel Jesus' movement--that guards were posted in this case. + +Although the Pharisees did believe in the resurrection (the Sadducees did not), they believed it would happen only at the end of the world, and certainly not begin in their own lifetimes. + +As William Lane Craig (and others) have pointed out, the argument between the Pharisees and the believers in Christ presupposes the empty tomb: + +> +> Christian: 'The Lord is risen!' +> +> +> Jew: 'No, his disciples stole away his body.' +> +> +> Christian: 'The guard at the tomb would have prevented any such +> theft.' +> +> +> Jew: 'No, his disciples stole away his body while the guard slept.' +> +> +> Christian: 'The chief priests bribed the guard to say this.' ([source](https://www.reasonablefaith.org/writings/scholarly-writings/historical-jesus/the-guard-at-the-tomb)) +> +> +> + +As Craig further points out: + +> +> The sleeping of the guard could only have been a Jewish development, as it would serve no purpose to the Christian polemic (*ibid*) +> +> +> + +The argument would have never progressed this far unless both sides agreed: + +1. The tomb was empty & +2. There was a guard posted + +The Pharisees had no reason to agree to those points unless they were incontrovertibly true. + +-- + +**The reliability of Matthew** + +My work on the Synoptic Problem & the authorship of the Gospels leads me decisively to the conclusion that the Gospel of Matthew was written in or near Judea within a few years of Easter. If this is true, Matthew's defense of the resurrection would be ineffective--as his evidence could be easily rebutted by people who were there and knew what really happened--unless the claims he made about the tomb & guards were actually true. + +This is why the account of the guards is found only in Matthew--Matthew's audience (in/near Judea) has the ability to fact check this part of the story. Mark's audience in Rome, Luke's audience in Greece, and John's audience in Ephesus, would have no ability to validate the story about the guards, so the account about the guards would at best be a distraction from the main point they were trying to make. But for Matthew, writing to the local population, the story about the guards was potent, verifiable evidence of the veracity of his claims. + +The Jewish leaders had every incentive in the world to produce a crucified body and squash the nascent Christian movement. The fact that they were unable to do so stands resolutely in favor of the view that Jesus really was buried in a tomb and the tomb really was found empty a few days later. + +Matthew could only get away with his claims about the empty tomb & the guards if: + +1. Everybody in the area knew it was true OR +2. The text was written so long after the fact that the people familiar with the events were dead. + +This is why atheists work so hard to claim that the Gospel of Matthew was written a generation or more after Easter. For my work demonstrating that the Gospel of Matthew was written by the apostle Matthew well within the lifetime and geographic reach of eyewitnesses, see this video series: [Who When & Why - the Writing of the Gospels](https://youtube.com/playlist?list=PLGACqQS4ut5iFeKqqvQPK_dzMnjF7NBhw)" +92034,"The gospel of Matthew records that after Jesus’ death, the Pharisees and teachers of the Law went to Pilate to ask for a guard, since they remembered that Jesus said he would rise again on the third day. + +> +> “The next day, the one after Preparation Day, the chief priests and the Pharisees went to Pilate. “Sir,” they said, “we remember that while he was still alive that deceiver said, ‘After three days I will rise again.’ So give the order for the tomb to be made secure until the third day. Otherwise, his disciples may come and steal the body and tell the people that he has been raised from the dead. This last deception will be worse than the first.”” +> ‭‭Matthew‬ ‭27:62-64‬ ‭ +> +> +> + +However, part of the whole surprise of Jesus’ resurrection was that despite Jesus telling everyone he would rise again, the disciples still didn’t understand it. + +Further, the concept of a resurrection like the one of Jesus being physically resurrected was basically a new and radical concept that was not widely believed at all. + +So: + +How is it that the Jews would be aware of Jesus’ resurrecting on the third day when the disciples weren’t? + +And how can they have been so aware of it to the point of sending guards to the tomb? Was sending a guard to the tomb of a dead person even a common thing during that time if people don’t even rise from the dead? + +What happened to all the guards? If the tomb stone had been rolled away and people spread the rumour that Jesus’ body had been stolen, would the guards not have faced strong discipline for letting Jesus’ body be “stolen”? (in accordance with what Matthew writes about people believing the body was stolen) + +I don’t understand why a guard would be sent to the tomb of a dead person (especially since the Pharisees believed Jesus was just a human!), and I don’t understand how the Pharisees could remember that Jesus would rise from the dead on the third day (when the disciples couldn’t), yet also still spread a rumour that his body was stolen, especially if they knew they had guards there in the first place. + +I hear skeptics talk about how Matthew made up the guard story as an apologetic resource to defend the empty tomb, so if I could get some defence/ clarification on this and the questions above that would greatly help.",2022/07/30,"['https://christianity.stackexchange.com/questions/92034', 'https://christianity.stackexchange.com', 'https://christianity.stackexchange.com/users/59680/']","The Pharisees did not believe that a crucified Jesus of Nazareth would ever rise from the dead. Had they believed he was the foretold Messiah, they would have taken the possibility of that seriously. Given that they wanted this Jesus out of the way due to his claims, they wanted him to stay out of the way once they'd got the Roman authorities to crucify him. That was when they remembered that one of Jesus' claims while alive was that he would rise from the dead, and ***that*** made them think of tricks his disciples might employ to deceive people into thinking Christ was now alive. + +The verse you quote is very clear in showing their reasoning behind asking for a guard at the tomb: ""his disciples may come and steal the body and tell the people that he has been raised from the dead. This last deception will be worse than the first."" They'd also called Jesus *""that deceiver""* to Pilate, so they did not believe Jesus would actually arise (vs.63). + +This categorically proves that these men did ***not*** believe Jesus would rise from the dead. But given that, while alive, Jesus three times stated to his disciples that he would arise, the simple reason why the disciples were not full of faith about that was that Jesus' arrest and sentence to crucifixion was a bombshell, and they no doubt thought they could be rounded up next, hence the way they kept out of sight behind locked doors. They supposed Jesus would triumph over the Romans, not that the Romans would kill him! + +The Pharisees, however, knew that if a trick was played, with the corpse of Jesus taken away in the night, the disciples could then spread a story that he had been resurrected, and that deception would be far harder for them to deal with. So they asked Pilate for permission to set a seal and a guard over the tomb, that happened, and when the guards reported the miracle of the resurrection, they were bribed to spread the lie that, while they were asleep, the disciples came to do just that. + +It's very plainly stated in the gospel account. Why would skeptical disbelief about Matthew's account require more consideration than Matthew's account, for Matthew saw with his own eyes the resurrected Christ? There's no way Matthew would need to invent *""an apologetic resource to defend the empty tomb,""* when the empty tomb was the proof the disciples needed to restore their faith in Jesus' promise that, on the third day, he would be raised! Proof substantiated shortly after by the followers then seeing the living Christ, and even touching his wounds, and eating with him. Then when they went to the mountain specified in Galilee, he met with them to give parting instructions, and they saw him literally ascend, bodily, up into the sky till clouds hid him from their sight. + +So, **the answer to your main question is that the Pharisees did ***not*** anticipate Jesus' resurrection (at any time, let alone before the disciples started to believe in it). The Pharisees never, at any point, expected Jesus to arise from the dead.** They ***did*** expect the disciples to do a trick to deceive the populace that that had happened, and that was the reason for them getting a Roman guard placed, with a sealed stone over the tomb. Their actions were those of total disbelievers who wanted to second-guess the disciples. They guessed wrong, for the resurrection happened before any of the women followers even got to the tomb, to then tell the disciples they'd seen the risen Christ. The strange thing is that the last two sentences of the text you quote answers your question. And Matthew 28:11-15 deals with your other question about the guards.","The leaders of the people requested a guard be posted because they listened and understood what was spoken to them. They identified Jesus of Nazareth as the Christ, and wanted him dead. Once dead, they where concerned an event would happen. + +They likely where unsure what exactly would happen. Jesus mentioned he would raise up the Temple in three days, and the statement confused them. But they would have known the Christ would be cut off, yet live. + +1. Though the birth of the Christ can't be predicted from reading the Prophets, his approximate lifespan can be identified in advance. +2. All Jerusalem was disturbed at the arrival of the Magi. It was now known the Christ was born, his family and location identified. At his birth, Joseph had registered with the tax and cencus, as being of the House of David. +3. Jesus opened the eyes of the blind. A sign. +4. He healed lepers, and instructed them to present themselves to the Priest. The Priest where required to preform the Offering for the Leper in the Day of His Cleansing. Never before preformed by the Priesthood, it was a sign. +5. He raised the dead. +6. The leaders could predict the Christ's entry into the Temple to an approximate one hour window. +7. When examined by the Priest, Jesus told the leaders in person, the Parable of the Husband Men. He stated the men knew who the Heir was, planned to kill him, and seize the inheritance. The leaders listened and understood Jesus was referring to them. + +These are only a few selected items of evidence condemning the leaders of the people. They understood they were killing the Christ. The Christ was not a mere mortal, as the Son of God, he is simply not going to stay in a tomb. He would not see corruption, as foretold of the Holy One. + +The Sign of Jonah was mentioned to the leaders, as a Sign to their generation, just as Jonah was dead for three days and three nights. The leaders would have known any resurrection would occur around dawn on Sunday." +17269744,"HTML: + +```html + + Accepted
            + + Contracted
            + + Pending
            + + Pre-Authorized
            + + Show Deleted
            + +  Treated
            + +``` + +MY javascript function with jquery but it does not work. +called this function on a button click.Wen i click on button `alert(""hi"");` is fired but not `alert(index);` Also explain my main question and just me the way for this question + +```js + function ShowHideDxColumn() { + alert(""hi""); + $("".ckhdisplay"").each(function (index) { + if ($(this).is("":checked"")) { + alert(index); + } + }); + } + +``` + +thank u",2013/06/24,"['https://Stackoverflow.com/questions/17269744', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2194674/']","You have a typo, `.ckhdisplay` should be `.chkdisplay`. Because of that, your `.each` call has no elements to iterate over because there are none with the given class. + +``` + function ShowHideDxColumn() { + alert(""hi""); + $("".chkdisplay"").each(function (index) { + if ($(this).is("":checked"")) { + alert(index); + } + }); + } + +``` + +You actually don't really need the condiiton in the each, you can just select the checked checkboxes: + +``` +$("".chkdisplay:checked"").each(function(index){ + console.log(this); +}); + +```","Please try this: + +``` +$.each($("".chkdisplay""), function(index, element) { + if ($(this).attr('checked')){ + alert(index); + } +}); + +```" +37694419,"I need to pass checkbox Boolean value(True or False) from below java method to java script function. + +Java Method:: + +``` +M1() { + generatedXML.append(""
            ""); + generatedXML.append("" +> [**ΠΕΤΡΟΥ Α΄ 5:5 (SBLGNT)**](http://www.biblegateway.com/passage/?search=1%20peter%205:5&version=SBLGNT) +> +> ὁμοίως, νεώτεροι, ὑποτάγητε **πρεσβυτέροις**. πάντες δὲ ἀλλήλοις τὴν ταπεινοφροσύνην ἐγκομβώσασθε, ὅτι Ὁ θεὸς ὑπερηφάνοις ἀντιτάσσεται ταπεινοῖς δὲ δίδωσιν χάριν. +> +> +> [**1 Peter 5:5 (ESV)**](http://www.biblegateway.com/passage/?search=1%20peter%205:5&version=ESV) +> +> Likewise, you who are younger, be subject to **the elders**. Clothe yourselves, all of you, with humility toward one another, for ""God opposes the proud but gives grace to the humble."" +> +> +> + +Does the Greek text have any indication as to whether this means + +* the elders of the local church, or +* all elderly people in general? + +Which way should the passage be interpreted?",2011/10/06,"['https://hermeneutics.stackexchange.com/questions/142', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/93/']","They are the pillars of the early church, not only the *old ones* – although they are from the group of the old and experienced.1 According to verse 2a they shall *""be shepherds of God's flock""*. + +The technical use of the word πρεσβύτεροι for the heads of a community was usual for OT-Jewish region and ""understandable"" for the hellenistic environment.2 + +--- + +1: Leonahrt Goppelt, *Der erste Petrusbrief*, Göttingen 71912, p. 321 + +2: Bornkamm, ''Theologisches Wörterbuch zum Neuen Testament'', p. 660-666","Semitic society (Jews, Arabs, etc.) is organized in tribes. One is not ""elected"" by a ""committee"". An elder from one family would not in any way rule over another man's family. Each family was represented in public life by the alpha male of their clan. The alpha male was by default the eldest male but if that's not an option it could be another. Respect for one's elders was crucial to an orderly society. Notice that even Egypt was organized with elders: + +> +> Gen\_50:7 And Joseph went up to bury his father: and with him went up +> all the servants of Pharaoh, the elders of his house, and all the +> elders of the land of Egypt, +> +> +> + +Conspicuously absent from Paul's list of offices (which were temporary) is ""elder"": + +> +> Eph 4:11 And it is he who gifted some to be **apostles, others to be +> prophets, others to be evangelists, and still others to be pastors and +> teachers**, Eph 4:12 to equip the saints, to do the work of ministry, +> and to build up the body of the Messiah Eph 4:13 until all of us are +> united in the faith and in the full knowledge of God's Son, and until +> we attain mature adulthood and the full standard of development in the +> Messiah. Eph 4:14 Then we will no longer be little children, tossed +> like waves and blown about by every wind of doctrine, by people's +> trickery, or by clever strategies that would lead us astray. +> +> +> + +So Peter knows nothing of the ""Elders"" in modern Churches who act as a board of directors over all of the families of the assemblies. Presbyterian style ""Board of Elders"" has more in common with a Roman Senate than with the thousands of years of Semitic representation by the alpha male of the family. + +My primary source for my observation is the scriptures themselves. The last mention of elders in the scriptures prior to the NT is 3 Maccabees 1:25: + +> +> 3Ma\_1:25 The elders who surrounded the king strove in many ways to +> divert his haughty mind from the design which he had formed. +> +> +> + +Obviously these are not Presbyterians but rather Jews interacting with the king. + +Joseph, War, mentions the elders as well: + +> +> And when he was at Antioch, he wrote to him, and commanded him to come +> to him quickly to Ptolemais: upon which Jonathan did not intermit the +> siege of the citadel, but **took with him the elders of the people**, +> and the priests, and carried with him gold, and silver, and garments, +> and a great number of presents of friendship, and came to Demetrius, +> and presented him with them, and thereby pacified the king's anger. +> +> +> + +For more background see: + +" +62542223,"Anyone has a better idea to tackle this problem. + +I have this table + +``` ++------+------+ +|Id |Value | ++------+------+ +|1 |0 | ++------+------+ +|1 |5 | ++------+------+ +|2 |0 | ++------+------+ +|2 |1 | ++------+------+ +|3 |0 | ++------+------+ + +``` + +So my goal is to get the distinct Id and get the first non-zero value if it exist. + +Which would look like this + +``` ++------+------+ +|Id |Value | ++------+------+ +|1 |5 | ++------+------+ +|2 |1 | ++------+------+ +|3 |0 | ++------+------+ + +``` + +One of my idea is to SUM the Value since the expectation the rest are 0 but that won't work because their would be a possibility of having more than 1 value. + +In this case I don't care which value I get as long as I got only one non-zero. + +Is this possible in SQL or should I do this in backend? + +MySQL Version: 5.7.26",2020/06/23,"['https://Stackoverflow.com/questions/62542223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4099041/']","If you are running MySQL 8.0, you can use `row_number()` - but you need an ordering column, otherwise the notion of ""first"" value is not defined. I assumed `ordering_id`: + +``` +select id, value +from ( + select + t.*, + row_number() over( + partition by id + order by (value = 0), ordering_id + ) rn + from mytable t +) t +where rn = 1 + +``` + +In earlier versions, one option is to use a subquery. Assuming that the primary key of your table is `pk`, you would do: + +``` +select t.id, t.value +from mytable t +where t.pk = ( + select t1.pk + from mytable t1 + where t1.id = t.id + order by (value = 0), ordering_id + limit 1 +) + +```","This solution work for my need: [How can I select only the first distinct match from a field in MySQL?](https://stackoverflow.com/questions/15010763/how-can-i-select-only-the-first-distinct-match-from-a-field-in-mysql) + +Instead of using MIN, I used MAX so it will get the biggest value (In my scenario this is ok since I don't care which non-zero I get as long it exist) + +Cheers" +1231716,"I'm wondering if anyone has knowledge of any kind of modplayer library for iphone? I've searched, but couldn't find anything.",2009/08/05,"['https://Stackoverflow.com/questions/1231716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125386/']","There's no reason we (the Roo team) cannot make the MavenPathResolver allow custom paths to be used, and one of the intentional reasons I created a PathResolver abstraction was to support customisation of common path locations not only to Maven non-default locations but also to other build systems like Ant+Ivy. all base Roo add-ons have been written to use the PathResolver so it shouldn't be a major effort to support this. Please add an enhancement request to the [Roo Jira instance](https://jira.springsource.org/browse/ROO) if you'd still like this support.","You can modify Maven to use a different set of conventions. The standard set are inherited from the [Maven super POM](http://maven.apache.org/guides/introduction/introduction-to-the-pom.html) and can be overridden by redefining the relevant property. + +For example, to change the sources directory from src/main/java to src, the test directory to test-src, and the resources directory from src/main/resources to resources you would set the following in your POM: + +``` + + src + test-src + + + resources + + + + +``` + +Be aware that a few plugins might not use the standard properties to access the locations (e.g. hardcoding target/classes instead of using ${project.build.outputDirectory}, so you might have the odd problem. + +--- + +Update: It looks like Roo currently has these [properties hardcoded](https://fisheye.springsource.org/browse/~raw,r=1/spring-roo/trunk/addon-maven/src/main/java/org/springframework/roo/addon/maven/MavenPathResolver.java). You may be able to replace the MavenPathResolver or add an additional resolver to use the custom properties. + +If this is a real problem for you, you can [raise a request](http://jira.springframework.org/browse/ROO) to get the MavenPathResolver modified to allow custom locations." +1231716,"I'm wondering if anyone has knowledge of any kind of modplayer library for iphone? I've searched, but couldn't find anything.",2009/08/05,"['https://Stackoverflow.com/questions/1231716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125386/']","You can modify Maven to use a different set of conventions. The standard set are inherited from the [Maven super POM](http://maven.apache.org/guides/introduction/introduction-to-the-pom.html) and can be overridden by redefining the relevant property. + +For example, to change the sources directory from src/main/java to src, the test directory to test-src, and the resources directory from src/main/resources to resources you would set the following in your POM: + +``` + + src + test-src + + + resources + + + + +``` + +Be aware that a few plugins might not use the standard properties to access the locations (e.g. hardcoding target/classes instead of using ${project.build.outputDirectory}, so you might have the odd problem. + +--- + +Update: It looks like Roo currently has these [properties hardcoded](https://fisheye.springsource.org/browse/~raw,r=1/spring-roo/trunk/addon-maven/src/main/java/org/springframework/roo/addon/maven/MavenPathResolver.java). You may be able to replace the MavenPathResolver or add an additional resolver to use the custom properties. + +If this is a real problem for you, you can [raise a request](http://jira.springframework.org/browse/ROO) to get the MavenPathResolver modified to allow custom locations.",As of Roo 1.2 it is not implemented. +1231716,"I'm wondering if anyone has knowledge of any kind of modplayer library for iphone? I've searched, but couldn't find anything.",2009/08/05,"['https://Stackoverflow.com/questions/1231716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125386/']","There's no reason we (the Roo team) cannot make the MavenPathResolver allow custom paths to be used, and one of the intentional reasons I created a PathResolver abstraction was to support customisation of common path locations not only to Maven non-default locations but also to other build systems like Ant+Ivy. all base Roo add-ons have been written to use the PathResolver so it shouldn't be a major effort to support this. Please add an enhancement request to the [Roo Jira instance](https://jira.springsource.org/browse/ROO) if you'd still like this support.",As of Roo 1.2 it is not implemented. +8252731,"In my Java project I need to add versioning control to the files(Like SVN), maintain different versions to the same named files in same folder. Please help me how to do this in java programming. +Eg: in my project,i maintained a folder which have set of images which are uploaded by user.but user can upload same named image n number of times.to overcome this overhead i planned to maintain versioning to each image which are same (same named).",2011/11/24,"['https://Stackoverflow.com/questions/8252731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/736260/']",Source control code is not the way to do this. Rename the files to a uuid as they get uploaded and build a map of original filename->uuid filename with timestamps that you can then lookup or expire as needed.,"I agree with awm. Version control is not for binary files. However, if you insist to do it like that, SVN has an API that you can use. You can access it directly from your code to commit code, update code, etc. + +Here's a place to start: + +Go checkout out the SVNClientManager under ""Subversion Client and IDE Integrations + +Subversion clients and IDE integrations"" + +Good look. + +(of course, I haven't used SVN in ages... I 'git' joy from a much better tool... :-))" +1167669,"For odd integers $n$, can you prove that $10^n+1$ is **not** a perfect square?",2015/02/27,"['https://math.stackexchange.com/questions/1167669', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']","Lead the equation $10^n = (a-1)(a+1)$ to a contradiction. For instance the prime factor $5$ can appear only in one of those $2$ factors, so we have $5^n \leq a+1$, hence $(a-1)(a+1) \geq 5^n(5^n-2) > 10^n$, contradiction!","> +> In general, let $a\in\mathbb{P}$ (prime numbers) and suppose $a^n+1$ is a perfect square for some $n\in\mathbb{N}\setminus\{1\}.$ +> +> +> + +Then there is $x\in\mathbb{N}$ such that $x^2=a^n+1$ and therefore $a^n=(x+1)(x-1).$ Then we can write $a^p=x+1$ and $a^q=x-1$ for some integers $p,q\in\mathbb{N}\cup\{0\}$ such that $p+q=n$ and $p>q.$ This clearly implies $a^p-a^q=2.$ + +* If $q=0,$ we get $a=3$ and $p=1$ which implies $$3^1+1=2^2.$$ +* If $q\neq 0,$ we get $a=2$ and $p=2, q=1$ which implies $$2^3+1=3^2.$$" +1167669,"For odd integers $n$, can you prove that $10^n+1$ is **not** a perfect square?",2015/02/27,"['https://math.stackexchange.com/questions/1167669', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']","Since $10\equiv1\pmod3$, it suffices to note that $1^n+1=2$ is not a quadratic residue modulo $3$. (We don't even need the assumption that $n$ is odd.)","> +> In general, let $a\in\mathbb{P}$ (prime numbers) and suppose $a^n+1$ is a perfect square for some $n\in\mathbb{N}\setminus\{1\}.$ +> +> +> + +Then there is $x\in\mathbb{N}$ such that $x^2=a^n+1$ and therefore $a^n=(x+1)(x-1).$ Then we can write $a^p=x+1$ and $a^q=x-1$ for some integers $p,q\in\mathbb{N}\cup\{0\}$ such that $p+q=n$ and $p>q.$ This clearly implies $a^p-a^q=2.$ + +* If $q=0,$ we get $a=3$ and $p=1$ which implies $$3^1+1=2^2.$$ +* If $q\neq 0,$ we get $a=2$ and $p=2, q=1$ which implies $$2^3+1=3^2.$$" +13853,"I've implemented a sprite batch class that uses a sampler array so that I can select a texture to use based on the gl\_PrimitiveID. The idea was to be able to draw sprites that use different textures in a single draw call. I've managed to get it to compile the shaders and run, but the sampler indexing part does not seem to work, although I did not get any OpenGL error. I've done a bit of research and found out that it doesn't seem possible to index into a sampler array with an index that is not a compile-time constant or uniform variable. + +Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once?",2011/06/18,"['https://gamedev.stackexchange.com/questions/13853', 'https://gamedev.stackexchange.com', 'https://gamedev.stackexchange.com/users/2940/']","You can use multitexturing to do this - because you can bind a different texture to each texture unit you can then use your uniforms to select which one. The limit is hardware dependent, but usually no less than 8 and very occasionally as small as 4. + + + +Multitexturing predates shaders so support is fairly global. + +This does mean not using a sampler array and instead using your own logic - ""just"" unroll a binary search, or even better use some bit magic. + +It is however fastest to use one texture for all calls and for it to be an atlas of some kind.","The MSDN documentation for HLSL seems to think that you can only do this in Direct3D 10. Of course, OpenGL and Direct3D don't always exactly match their functionality, but it's usually pretty close, since the same cards target OpenGL and DirectX. + +It could be that it is legal- just not for a target of the version that you are using." +13853,"I've implemented a sprite batch class that uses a sampler array so that I can select a texture to use based on the gl\_PrimitiveID. The idea was to be able to draw sprites that use different textures in a single draw call. I've managed to get it to compile the shaders and run, but the sampler indexing part does not seem to work, although I did not get any OpenGL error. I've done a bit of research and found out that it doesn't seem possible to index into a sampler array with an index that is not a compile-time constant or uniform variable. + +Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once?",2011/06/18,"['https://gamedev.stackexchange.com/questions/13853', 'https://gamedev.stackexchange.com', 'https://gamedev.stackexchange.com/users/2940/']","> +> Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once? +> +> +> + +It is not necessarily the ""only"" way, but it is the *best* way. It is the way that works on anything, from the lowly Voodoo 1 all the way to the Radeon 6990. It doesn't require shaders (though they can be useful with this). + +All it requires is a bit of pre-processing on your end to put all of the images in one large image. This is hardly an onerous burden. + +That being said, how many sprites do you intend to draw per frame? If it's less than a couple of hundred, an atlas isn't that important to your rendering performance. Texture atlases matter most for things like particle systems and fonts, because you're drawing lots of them.","The MSDN documentation for HLSL seems to think that you can only do this in Direct3D 10. Of course, OpenGL and Direct3D don't always exactly match their functionality, but it's usually pretty close, since the same cards target OpenGL and DirectX. + +It could be that it is legal- just not for a target of the version that you are using." +13853,"I've implemented a sprite batch class that uses a sampler array so that I can select a texture to use based on the gl\_PrimitiveID. The idea was to be able to draw sprites that use different textures in a single draw call. I've managed to get it to compile the shaders and run, but the sampler indexing part does not seem to work, although I did not get any OpenGL error. I've done a bit of research and found out that it doesn't seem possible to index into a sampler array with an index that is not a compile-time constant or uniform variable. + +Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once?",2011/06/18,"['https://gamedev.stackexchange.com/questions/13853', 'https://gamedev.stackexchange.com', 'https://gamedev.stackexchange.com/users/2940/']","You can use multitexturing to do this - because you can bind a different texture to each texture unit you can then use your uniforms to select which one. The limit is hardware dependent, but usually no less than 8 and very occasionally as small as 4. + + + +Multitexturing predates shaders so support is fairly global. + +This does mean not using a sampler array and instead using your own logic - ""just"" unroll a binary search, or even better use some bit magic. + +It is however fastest to use one texture for all calls and for it to be an atlas of some kind.","> +> Am I doing something wrong or is building a texture atlas the only way to draw sprites that use different textures at once? +> +> +> + +It is not necessarily the ""only"" way, but it is the *best* way. It is the way that works on anything, from the lowly Voodoo 1 all the way to the Radeon 6990. It doesn't require shaders (though they can be useful with this). + +All it requires is a bit of pre-processing on your end to put all of the images in one large image. This is hardly an onerous burden. + +That being said, how many sprites do you intend to draw per frame? If it's less than a couple of hundred, an atlas isn't that important to your rendering performance. Texture atlases matter most for things like particle systems and fonts, because you're drawing lots of them." +9952128,"First I am using the jQuery colorbox plugin that is working fine so far but then I want to close the colorbox using a button. Unfortunately I can't just trigger the click event on that button by selecting its ID using jQuery, instead of that the button must call a javascript function called closepan() (this behavior is unfortunately mandatory for me). + +I tried to create the function + +``` +closepan() { +$.colorbox.close(); +} + +``` + +**first case** : inside the + +``` +$(document).ready(function(){...}); + +``` + +but then I got the error closepan is undefined. + +**second case** : before the + +``` +$(document).ready(function(){...}); + +``` + +but then it's the colorbox method that is undefined! + +I gave up after gazillion hours of fiddling with several solutions I've found all around stackoverflow.com regarding this topic! I can't figure out how to make this working! + +In other words, how to create a function named closepan() that can execute $.colorbox.close(); while being available globally for my button?",2012/03/31,"['https://Stackoverflow.com/questions/9952128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1207999/']","No matter where you create a variable or function if you create it on `window` it will be available globally. + +``` +window.closepan = function() { + // hello there +} + +```","``` +function closepan() { + if($.colorbox) { + $.colorbox.close(); + } +} + +``` + +However, at the point where someone clicks your button all external scripts should have been loaded so that check shouldn't be necessary..." +9952128,"First I am using the jQuery colorbox plugin that is working fine so far but then I want to close the colorbox using a button. Unfortunately I can't just trigger the click event on that button by selecting its ID using jQuery, instead of that the button must call a javascript function called closepan() (this behavior is unfortunately mandatory for me). + +I tried to create the function + +``` +closepan() { +$.colorbox.close(); +} + +``` + +**first case** : inside the + +``` +$(document).ready(function(){...}); + +``` + +but then I got the error closepan is undefined. + +**second case** : before the + +``` +$(document).ready(function(){...}); + +``` + +but then it's the colorbox method that is undefined! + +I gave up after gazillion hours of fiddling with several solutions I've found all around stackoverflow.com regarding this topic! I can't figure out how to make this working! + +In other words, how to create a function named closepan() that can execute $.colorbox.close(); while being available globally for my button?",2012/03/31,"['https://Stackoverflow.com/questions/9952128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1207999/']","No matter where you create a variable or function if you create it on `window` it will be available globally. + +``` +window.closepan = function() { + // hello there +} + +```","Don't forget to put the keyword `function` in front of your declaration... + +``` +function closepan() { + $.colorbox.close(); +} + +``` + +Working [JSFiddle](http://jsfiddle.net/axZqY/8/)" +4528085,"Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button + +``` +
            + +```",2010/12/24,"['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/']","Since toggling using `style` like: + +```js +myElement.style.display = someBoolState ? ""block"" : ""none"" + +``` + +is a really bad idea, here are some examples in JS, jQuery, HTML, CSS: + +JavaScript [.classList.toggle()](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) +==================================================================================================== + +```js +const elToggle = document.querySelector(""#toggle""); +const elContent = document.querySelector(""#content""); + +elToggle.addEventListener(""click"", function() { + elContent.classList.toggle(""is-hidden""); +}); +``` + +```css +.is-hidden { + display: none; +} +``` + +```html + +
            Some content...
            +``` + +The beauty of the above is that the styling is purely handled where it should, and that's in your stylesheet. Also, by removing the `.is-hidden` class your element will regain its original *`display`* mode, being it `block`, `table`, `flex`, or whatever. + +jQuery .toggle() +================ + +[`.toggle()`*Docs*](http://api.jquery.com/toggle/) + +[`.fadeToggle()`*Docs*](http://api.jquery.com/fadetoggle/) + +[`.slideToggle()`*Docs*](http://api.jquery.com/slidetoggle/) + +```js +$(""#toggle"").on(""click"", function(){ + $(""#content"").toggle(); // .fadeToggle() // .slideToggle() +}); +``` + +```css +#content{ + display:none; +} +``` + +```html + + +
            Some content...
            +``` + +jQuery - Toggle [`.toggleClass()`*Docs*](http://api.jquery.com/toggleclass/) +============================================================================ + +`.toggle()` toggles an element's `display` `""block""/""none""` values + +```js +$(""#toggle"").on(""click"", function(){ + $(""#content"").toggleClass(""show""); +}); +``` + +```css +#content{ + display:none; +} +#content.show{ + display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */ +} +``` + +```html + + +
            Some content...
            +``` + +HTML5 - Toggle using `` and `
            ` +================================================ + +(unsupported on IE and Opera Mini) + +```html +
            + TOGGLE +

            Some content...

            +
            +``` + +HTML - Toggle using `checkbox` +============================== + +```css +[id^=toggle], +[id^=toggle] + *{ + display:none; +} +[id^=toggle]:checked + *{ + display:block; +} +``` + +```html + + + +
            Some content...
            +``` + +HTML - Switch using `radio` +=========================== + +```css +[id^=switch], +[id^=switch] + *{ + display:none; +} +[id^=switch]:checked + *{ + display:block; +} +``` + +```html + + + + +
            1 Merol Muspi...
            + + +
            2 Lorem Ipsum...
            +``` + +CSS - Switch using `:target` +============================ + +(just to make sure you have it in your arsenal) + +```css +[id^=switch] + *{ + display:none; +} +[id^=switch]:target + *{ + display:block; +} +``` + +```html +SHOW 1 +SHOW 2 + + +
            1 Merol Muspi ...
            + + +
            2 Lorem Ipsum...
            +``` + +--- + +Animating class transition +-------------------------- + +If you pick one of JS / jQuery way to actually toggle a `className`, you can always add animated transitions to your element, here's a basic example: + +```js +const elToggle = document.querySelector(""#toggle""); +const elContent = document.querySelector(""#content""); + +elToggle.addEventListener(""click"", () => { + elContent.classList.toggle(""is-hidden""); +}); +``` + +```css +#content { + display: inline-flex; /* or whatever */ + transition: 0.6s; +} + +.is-hidden { + position: relative; + visibility: hidden; + opacity: 0; + transform: scale(0); +} +``` + +```html + +
            Some Togglable content...
            +```","``` + + + +``` + +And the html + +``` +
            Hello World
            + + +```" +4528085,"Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button + +``` +
            + +```",2010/12/24,"['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/']","**Pure JavaScript:** + +``` +var button = document.getElementById('button'); // Assumes element with id='button' + +button.onclick = function() { + var div = document.getElementById('newpost'); + if (div.style.display !== 'none') { + div.style.display = 'none'; + } + else { + div.style.display = 'block'; + } +}; + +``` + +[### SEE DEMO](http://jsfiddle.net/andrewwhitaker/hefGK/) + +**jQuery**: + +``` +$(""#button"").click(function() { + // assumes element with id='button' + $(""#newpost"").toggle(); +}); + +``` + +[### SEE DEMO](http://jsfiddle.net/andrewwhitaker/KpFRb/)","Here's a plain Javascript way of doing toggle: + +``` + + +
            asdf
            + + +```" +4528085,"Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button + +``` +
            + +```",2010/12/24,"['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/']","Try with opacity + +```css +div { transition: all 0.4s ease } +.hide { opacity: 0; } +``` + +```html + + +
            Hello
            +```","``` + + + +``` + +And the html + +``` +
            Hello World
            + + +```" +4528085,"Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button + +``` +
            + +```",2010/12/24,"['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/']","Since toggling using `style` like: + +```js +myElement.style.display = someBoolState ? ""block"" : ""none"" + +``` + +is a really bad idea, here are some examples in JS, jQuery, HTML, CSS: + +JavaScript [.classList.toggle()](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) +==================================================================================================== + +```js +const elToggle = document.querySelector(""#toggle""); +const elContent = document.querySelector(""#content""); + +elToggle.addEventListener(""click"", function() { + elContent.classList.toggle(""is-hidden""); +}); +``` + +```css +.is-hidden { + display: none; +} +``` + +```html + +
            Some content...
            +``` + +The beauty of the above is that the styling is purely handled where it should, and that's in your stylesheet. Also, by removing the `.is-hidden` class your element will regain its original *`display`* mode, being it `block`, `table`, `flex`, or whatever. + +jQuery .toggle() +================ + +[`.toggle()`*Docs*](http://api.jquery.com/toggle/) + +[`.fadeToggle()`*Docs*](http://api.jquery.com/fadetoggle/) + +[`.slideToggle()`*Docs*](http://api.jquery.com/slidetoggle/) + +```js +$(""#toggle"").on(""click"", function(){ + $(""#content"").toggle(); // .fadeToggle() // .slideToggle() +}); +``` + +```css +#content{ + display:none; +} +``` + +```html + + +
            Some content...
            +``` + +jQuery - Toggle [`.toggleClass()`*Docs*](http://api.jquery.com/toggleclass/) +============================================================================ + +`.toggle()` toggles an element's `display` `""block""/""none""` values + +```js +$(""#toggle"").on(""click"", function(){ + $(""#content"").toggleClass(""show""); +}); +``` + +```css +#content{ + display:none; +} +#content.show{ + display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */ +} +``` + +```html + + +
            Some content...
            +``` + +HTML5 - Toggle using `` and `
            ` +================================================ + +(unsupported on IE and Opera Mini) + +```html +
            + TOGGLE +

            Some content...

            +
            +``` + +HTML - Toggle using `checkbox` +============================== + +```css +[id^=toggle], +[id^=toggle] + *{ + display:none; +} +[id^=toggle]:checked + *{ + display:block; +} +``` + +```html + + + +
            Some content...
            +``` + +HTML - Switch using `radio` +=========================== + +```css +[id^=switch], +[id^=switch] + *{ + display:none; +} +[id^=switch]:checked + *{ + display:block; +} +``` + +```html + + + + +
            1 Merol Muspi...
            + + +
            2 Lorem Ipsum...
            +``` + +CSS - Switch using `:target` +============================ + +(just to make sure you have it in your arsenal) + +```css +[id^=switch] + *{ + display:none; +} +[id^=switch]:target + *{ + display:block; +} +``` + +```html +SHOW 1 +SHOW 2 + + +
            1 Merol Muspi ...
            + + +
            2 Lorem Ipsum...
            +``` + +--- + +Animating class transition +-------------------------- + +If you pick one of JS / jQuery way to actually toggle a `className`, you can always add animated transitions to your element, here's a basic example: + +```js +const elToggle = document.querySelector(""#toggle""); +const elContent = document.querySelector(""#content""); + +elToggle.addEventListener(""click"", () => { + elContent.classList.toggle(""is-hidden""); +}); +``` + +```css +#content { + display: inline-flex; /* or whatever */ + transition: 0.6s; +} + +.is-hidden { + position: relative; + visibility: hidden; + opacity: 0; + transform: scale(0); +} +``` + +```html + +
            Some Togglable content...
            +```","Here's a plain Javascript way of doing toggle: + +``` + + +
            asdf
            + + +```" +4528085,"Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button + +``` +
            + +```",2010/12/24,"['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/']","Here's a plain Javascript way of doing toggle: + +``` + + +
            asdf
            + + +```","You could use the following: + +`mydiv.style.display === 'block' = (mydiv.style.display === 'block' ? 'none' : 'block');`" +4528085,"Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button + +``` +
            + +```",2010/12/24,"['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/']","Try with opacity + +```css +div { transition: all 0.4s ease } +.hide { opacity: 0; } +``` + +```html + + +
            Hello
            +```","This is how I hide and show content using a class. changing the class to nothing will change the display to block, changing the class to 'a' will show the display as none. + +``` + + + + + + + + + +

            Testing

            +
            + + + +```" +4528085,"Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button + +``` +
            + +```",2010/12/24,"['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/']","Look at [jQuery Toggle](http://api.jquery.com/toggle/) + +**HTML:** + +``` +
            Hello World
            + + +``` + +**jQuery:** + +``` +jQuery(document).ready(function(){ + jQuery('#hideshow').live('click', function(event) { + jQuery('#content').toggle('show'); + }); +}); + +``` + +For versions of jQuery 1.7 and newer use + +``` +jQuery(document).ready(function(){ + jQuery('#hideshow').on('click', function(event) { + jQuery('#content').toggle('show'); + }); +}); + +``` + +For reference, kindly check this [**demo**](http://jsfiddle.net/vVsAn/1/)","This is how I hide and show content using a class. changing the class to nothing will change the display to block, changing the class to 'a' will show the display as none. + +``` + + + + + + + + + +

            Testing

            +
            + + + +```" +4528085,"Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button + +``` +
            + +```",2010/12/24,"['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/']","**Pure JavaScript:** + +``` +var button = document.getElementById('button'); // Assumes element with id='button' + +button.onclick = function() { + var div = document.getElementById('newpost'); + if (div.style.display !== 'none') { + div.style.display = 'none'; + } + else { + div.style.display = 'block'; + } +}; + +``` + +[### SEE DEMO](http://jsfiddle.net/andrewwhitaker/hefGK/) + +**jQuery**: + +``` +$(""#button"").click(function() { + // assumes element with id='button' + $(""#newpost"").toggle(); +}); + +``` + +[### SEE DEMO](http://jsfiddle.net/andrewwhitaker/KpFRb/)","Try with opacity + +```css +div { transition: all 0.4s ease } +.hide { opacity: 0; } +``` + +```html + + +
            Hello
            +```" +4528085,"Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button + +``` +
            + +```",2010/12/24,"['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/']","Since toggling using `style` like: + +```js +myElement.style.display = someBoolState ? ""block"" : ""none"" + +``` + +is a really bad idea, here are some examples in JS, jQuery, HTML, CSS: + +JavaScript [.classList.toggle()](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) +==================================================================================================== + +```js +const elToggle = document.querySelector(""#toggle""); +const elContent = document.querySelector(""#content""); + +elToggle.addEventListener(""click"", function() { + elContent.classList.toggle(""is-hidden""); +}); +``` + +```css +.is-hidden { + display: none; +} +``` + +```html + +
            Some content...
            +``` + +The beauty of the above is that the styling is purely handled where it should, and that's in your stylesheet. Also, by removing the `.is-hidden` class your element will regain its original *`display`* mode, being it `block`, `table`, `flex`, or whatever. + +jQuery .toggle() +================ + +[`.toggle()`*Docs*](http://api.jquery.com/toggle/) + +[`.fadeToggle()`*Docs*](http://api.jquery.com/fadetoggle/) + +[`.slideToggle()`*Docs*](http://api.jquery.com/slidetoggle/) + +```js +$(""#toggle"").on(""click"", function(){ + $(""#content"").toggle(); // .fadeToggle() // .slideToggle() +}); +``` + +```css +#content{ + display:none; +} +``` + +```html + + +
            Some content...
            +``` + +jQuery - Toggle [`.toggleClass()`*Docs*](http://api.jquery.com/toggleclass/) +============================================================================ + +`.toggle()` toggles an element's `display` `""block""/""none""` values + +```js +$(""#toggle"").on(""click"", function(){ + $(""#content"").toggleClass(""show""); +}); +``` + +```css +#content{ + display:none; +} +#content.show{ + display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */ +} +``` + +```html + + +
            Some content...
            +``` + +HTML5 - Toggle using `` and `
            ` +================================================ + +(unsupported on IE and Opera Mini) + +```html +
            + TOGGLE +

            Some content...

            +
            +``` + +HTML - Toggle using `checkbox` +============================== + +```css +[id^=toggle], +[id^=toggle] + *{ + display:none; +} +[id^=toggle]:checked + *{ + display:block; +} +``` + +```html + + + +
            Some content...
            +``` + +HTML - Switch using `radio` +=========================== + +```css +[id^=switch], +[id^=switch] + *{ + display:none; +} +[id^=switch]:checked + *{ + display:block; +} +``` + +```html + + + + +
            1 Merol Muspi...
            + + +
            2 Lorem Ipsum...
            +``` + +CSS - Switch using `:target` +============================ + +(just to make sure you have it in your arsenal) + +```css +[id^=switch] + *{ + display:none; +} +[id^=switch]:target + *{ + display:block; +} +``` + +```html +SHOW 1 +SHOW 2 + + +
            1 Merol Muspi ...
            + + +
            2 Lorem Ipsum...
            +``` + +--- + +Animating class transition +-------------------------- + +If you pick one of JS / jQuery way to actually toggle a `className`, you can always add animated transitions to your element, here's a basic example: + +```js +const elToggle = document.querySelector(""#toggle""); +const elContent = document.querySelector(""#content""); + +elToggle.addEventListener(""click"", () => { + elContent.classList.toggle(""is-hidden""); +}); +``` + +```css +#content { + display: inline-flex; /* or whatever */ + transition: 0.6s; +} + +.is-hidden { + position: relative; + visibility: hidden; + opacity: 0; + transform: scale(0); +} +``` + +```html + +
            Some Togglable content...
            +```","This is how I hide and show content using a class. changing the class to nothing will change the display to block, changing the class to 'a' will show the display as none. + +``` + + + + + + + + + +

            Testing

            +
            + + + +```" +4528085,"Hopefully this is an easy question. I have a `div` that I want to toggle hidden/shown with a button + +``` +
            + +```",2010/12/24,"['https://Stackoverflow.com/questions/4528085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547794/']","Try with opacity + +```css +div { transition: all 0.4s ease } +.hide { opacity: 0; } +``` + +```html + + +
            Hello
            +```","You could use the following: + +`mydiv.style.display === 'block' = (mydiv.style.display === 'block' ? 'none' : 'block');`" +30831806,"I'm new to mysqli prepare statement and was surprised to find out the || doesn't work as expected in mysqli prepare statement query. +I have a function which check whether the user registered, and its evaluation should be based upon the unique row id and email address.Besides, since the id column and the email column are of different type, which are `Int(11)` and `VARCHAR` respectively, so I assumed it's going to have some trouble using `bind_param` because the different data type + +``` +public function checkUserRegistered($iden){ + //The iden can be either a id or a email address + $stmt = $this->connection->prepare(""SELECT `id` FROM `$this->table_name` WHERE (`email`= ? || `id`= ?) LIMIT 1 ""); + $stmt->bind_param('s',$iden); // s or i ? + if($stmt->execute()){ + $result = $stmt->get_result(); + if($result->num_rows ==1){ + $stmt->close(); + return true; + }else{ + return false; + } + } + } + +``` + +What is the right way of doing this, do I have to use separate functions instead?",2015/06/14,"['https://Stackoverflow.com/questions/30831806', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3500129/']","You need to bind two params like this: + +``` +$stmt->bind_param('si',$iden, $iden); + +``` + +as you have set two '?'. + +s means string, i means integer, b is blob and d is double.","The problem is you have specified that in the prepare statement you want to bind two values. But in the bindValue statement you are only binding one value. Also coming to the issue that $iden can be the email or number then I think the best way is to generate conditional statements for them. So if I was you, I will go with: + +``` +public function checkUserRegistered($iden){ +//making sure $iden is not empty +if ($iden) { + //if $iden is a number is equal to id + if (is_numeric($iden)) { + $stmt = $this->connection->prepare(""SELECT `id` FROM `$this->table_name` WHERE `id`= ? LIMIT 1 ""); + + $stmt->bind_param('i',$iden); //because id is an integer + } else { + //then $iden is a varchar which is the email + $stmt = $this->connection->prepare(""SELECT `id` FROM `$this->table_name` WHERE `email`= ? LIMIT 1 ""); + + $stmt->bind_param('s',$iden); //because email is a string + } + + if ($stmt->execute()) { + $result = $stmt->get_result(); + + if($result->num_rows ==1){ + $stmt->close(); + return true; + }else{ + return false; + } + } +} + +``` + +}" +436326,"Let $V$ be an irreducible finite dimensional complex representation of the product of groups $G\times H$. Is it necessarily isomorphic to a tensor product of irreducible representation of $G$ and $H$? If not what is a counter-example, and under what extra assumptions this is known to be true? + +Remark. I think for continuous representations of compact groups this is true.",2022/12/11,"['https://mathoverflow.net/questions/436326', 'https://mathoverflow.net', 'https://mathoverflow.net/users/16183/']","If your groups are finite, then Andy’s [answer](https://mathoverflow.net/a/436339/2383) is perfectly fine. If you want to do topological groups you must be slightly (but not much) more careful. First since we are dealing with finite dimensional representations, algebraic and topological reducibility are the same. + +It is enough to prove that your irreducible representation decomposes as a tensor product in the case of discrete groups. For if it is isomorphic to one of the form $U\otimes V$, then since the linear isomorphism is continuous, it is enough to observe that restricting the original representation to $G$ gives $\dim V$ copies of $U$ and restricting to $H$ gives $\dim U$ copies of $V$ and so $U$ and $V$ must give continuous representations of $G$, $H$. + +So we may assume that $G$, $H$ are discrete and we are dealing with no topology. Then replacing $G$, $H$ with their group algebras and $\mathbb C$ by algebras over an algebraically closed field, it suffices to show that if $A$, $B$ are $K$-algebras with $K$ algebraically closed, then any finite dimensional irreducible representation of $A\otimes B$ is equivalent to a tensor product of irreducible representations of $A$ and $B$. + +But the image of $A$ and $B$ under any finite dimensional representation is a finite dimensional algebra and so without loss of generality we may assume that $A$, $B$ are finite dimensional. + +The crux of the matter, which is basically Andy’s proof in different words, is the special case that $A,B$ are matrix algebras over $K$. Then $M\_n(K)\otimes M\_m(K)\cong M\_{nm}(K)$ and the isomorphism intertwines the actions on $K^n\otimes K^m\cong K^{nm}$. Thus in the case $A$, $B$ are matrix algebras then the unique $A\otimes B$ irreducible rep is the tensor product of the unique irreducible $A$ and $B$ reps. Since arbitrary semisimple algebras over an algebraically closed field are finite direct products of matrix algebras and tensor product distributes over direct product, this handles the case $A$, $B$ are semisimple and also shows that $A\otimes B$ is semisimple in this case. + +$\DeclareMathOperator\rad{rad}$If $A$, $B$ are general finite dimensional $K$-algebras with $K$-algebraically closed, then $A/{\rad(A)}\otimes B/{\rad(B)}$ is semisimple by the above. Moreover, the kernel of the natural map $A\otimes B\to A/{\rad(A)}\otimes B/{\rad(B)}$ is easily checked to be $A\otimes \rad(B)+\rad(A)\otimes B$, which is a nilpotent ideal. Thus $(A\otimes B)/{\rad(A\otimes B)}\cong A/{\rad(A)}\otimes B/{\rad(B)}$ and so the desired result that irreducible reps are tensor products follows since $C$ and $C/{\rad(C)}$ have the same irreducible reps for any $K$-algebra $C$. + +**Simpler proof** +Here is an argument along the line of Andy's that works for arbitrary groups or even algebras that avoids the radical and just uses Burnside's theorem that a finite dimensional representation of a $K$-algebra over an algebraically closed field $K$ is irreducible if and only if it is surjective. + +Let $A,B$ be $K$-algebras (not necessarily finite dimensional) with $K$-algebraically closed (they could be group algebras) and let $W$ be a finite dimensional irreducible $A\otimes B$-module. Let $U$ be an irreducible $A$-subrepresentation of $W$. Then the sum $S$ of all irreducible $A$-submodules of $W$ isomorphic to $U$ is invariant under any $A$-enomorphism of $W$ and hence under $B$ as the $B$-action commutes with $A$. Hence $S$ is $A\otimes B$-invariant and so $S=W$ by irreducibility. Thus $W\cong U^m$ for some $m$ as an $A$-module (this is a standard argument). Thus, up to isomorphism, we may assume that $W=U\otimes V$ with $V$ a vector space of dimension $m$ and where $A$ acts via matrices of the form $\rho(a)\otimes 1$ where $\rho$ is the irreducible representation associated to $U$. By Burnside, $\rho$ is onto $End\_k(U)$. But since $End\_K(U\otimes V)= End\_k(U)\otimes End\_k(V)$, it follows that the centralizer of $End\_K(U)\otimes 1$ in $End\_K(W)$ is $1\otimes End\_k(V)$. Since the action of $B$ commutes with that of $A$, as a representation of $B$, we have $W$ is of the form $b\mapsto 1\otimes \psi(b)$ for some representation $\psi$ of $B$ on $V$. Clearly, if $V$ is not irreducible, then neither is $U\otimes V$ and so we are done.","Most books on the representation theory of finite groups prove this using character theory. This is an efficient way of proving it, but I think it doesn’t give much insight into why it is true (and what other settings it generalizes to). I wrote up a more direct proof [here](https://www3.nd.edu/%7Eandyp/notes/RepOfProducts.pdf)." +38838407,"Let's say we have a dictionary + +``` +dict = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 } + +``` + +How would I go about printing the code so it looks like: + +> +> Dollar 12, Half-Coin 4, Quarter 3, Dime 7 +> +> +>",2016/08/08,"['https://Stackoverflow.com/questions/38838407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5255751/']","Use `','.join()`, passing in a generator of strings. + +``` +d = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 } +print ', '.join('{} {}'.format(k,v) for k,v in d.items()) + +``` + +Result: + +``` +Half-Coin 4, Quarter 3, Dollar 12, Dime 7 + +``` + +If you want the results to be in a predictable order, you'll need to sort the items. + +``` +order=('Dollar', 'Half-Coin', 'Quarter', 'Dime') +d = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 } +print ', '.join('{} {}'.format(k,d[k]) for k in sorted(d, key=order.index)) + +``` + +Result: + +``` +Dollar 12, Half-Coin 4, Quarter 3, Dime 7 + +``` + +Ps. Don't name your variables with names of builtin types. Your name eclipses the builtin name, so subsequent code won't be able to call `dict()`, for example.","``` +dict = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 } + +out="""" +for i in dict: + out += i+"" ""+str(dict[i])+"", "" + +print out[:-2] + +``` + +result: + +``` +Half-Coin 4, Quarter 3, Dollar 12, Dime 7 + +```" +38838407,"Let's say we have a dictionary + +``` +dict = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 } + +``` + +How would I go about printing the code so it looks like: + +> +> Dollar 12, Half-Coin 4, Quarter 3, Dime 7 +> +> +>",2016/08/08,"['https://Stackoverflow.com/questions/38838407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5255751/']","Use `','.join()`, passing in a generator of strings. + +``` +d = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 } +print ', '.join('{} {}'.format(k,v) for k,v in d.items()) + +``` + +Result: + +``` +Half-Coin 4, Quarter 3, Dollar 12, Dime 7 + +``` + +If you want the results to be in a predictable order, you'll need to sort the items. + +``` +order=('Dollar', 'Half-Coin', 'Quarter', 'Dime') +d = { 'Dollar': 12, 'Half-Coin': 4, 'Quarter': 3, 'Dime': 7 } +print ', '.join('{} {}'.format(k,d[k]) for k in sorted(d, key=order.index)) + +``` + +Result: + +``` +Dollar 12, Half-Coin 4, Quarter 3, Dime 7 + +``` + +Ps. Don't name your variables with names of builtin types. Your name eclipses the builtin name, so subsequent code won't be able to call `dict()`, for example.","``` +"", "".join([x +"" ""+str(dict[x]) for x in dict.keys()]) + +```" +295247,"I want to plot a polynomial that is parametrized by an additional parameter d. I took samples of the domain of d and stored the coefficients of the polynomial for each of these samples in a table: + +``` +d a0 a1 a2 a3 a4 +0 0.31632 0.038794 -0.637117 0.457322 -0.0940009 +0.002 0.316319 0.0387949 -0.637115 0.457321 -0.0940008 +0.4 0.130744 0.0171396 -0.292042 0.2209 -0.0479512 +... + +``` + +Now I would like to plot up to 100 of these polynomials into the same plot. +Is there a way that does not require me to hand code each polynomial to plot or to sample each polynomial in an external tool? (Doing so from within the Latex tool chain would be fine.) + +To summarize it: In my case, the rows of the table don't represent coordinates to plot but coefficients of polynomials that I want to plot. Therefore, I don't see how to use pgfplot's `\addplot table` to get the output that I want. + +The effect of the code should be like + +``` +\documentclass{standalone} +\usepackage{pgfplots, pgfplotstable} +\pgfplotsset{compat=1.12} +\begin{document} + +\begin{tikzpicture} + \begin{axis}[domain=0:2] + \addplot[mark=none] {0.31632 + x*(0.038794 + x*(-0.637117 + x*(0.457322 + x*-0.0940009)))}; + \addplot[mark=none] {0.311765 + x*(0.0408345 + x*(-0.633668 + x*(0.454718 + x*-0.0935363)))}; + \addplot[mark=none] {0.130744 + x*(0.0171396 + x*(-0.292042 + x*(0.2209 + x*-0.0479512)))}; + \end{axis} +\end{tikzpicture} +\end{document} + +``` + +but without the manual repetition. + +The result would look like: + +[![Resulting output](https://i.stack.imgur.com/04F4X.png)](https://i.stack.imgur.com/04F4X.png)",2016/02/22,"['https://tex.stackexchange.com/questions/295247', 'https://tex.stackexchange.com', 'https://tex.stackexchange.com/users/28004/']","Here's a way that uses a `pgfplotsinvokeforeach` approach. + +[![enter image description here](https://i.stack.imgur.com/pH66q.png)](https://i.stack.imgur.com/pH66q.png) + +There are a few important parts, including: + +``` +% declare a polynomial function +\pgfmathdeclarefunction{mypoly}{6}{% + % #1: a0 + % #2: a1 + % #3: a2 + % #4: a3 + % #5: a4 + % #6: x + \pgfmathparse{#1+#2*#6% + +#3*#6^2% + +#4*#6^3% + +#5*#6^4}% +} + +``` + +which, as you can see, defines your polynomial. + +You'll see that this is invoked in the `addplot` command as + +``` + \addplot[domain=0:2,red,thick]{mypoly(\aZero,\aOne,\aTwo,\aThree,\aFour,x)}; + +``` + +Here's the complete code: + +``` +% arara: pdflatex +% !arara: indent: {overwrite: yes} +\documentclass[tikz]{standalone} +\usepackage{pgfplotstable} +\pgfplotsset{compat=1.12} + +% read in the coefficients +\pgfplotstableread[col sep=space]{ + d a0 a1 a2 a3 a4 + 0 0.31632 0.038794 -0.637117 0.457322 -0.0940009 + 1 0.311765 0.0408345 -0.633668 0.454718 -0.0935363 + 2 0.130744 0.0171396 -0.292042 0.2209 -0.0479512 + }\coefficients + +% count number of rows +\pgfplotstablegetrowsof\coefficients +\pgfmathsetmacro\numberofrows{\pgfplotsretval-1} + +% declare a polynomial function +\pgfmathdeclarefunction{mypoly}{6}{% + % #1: a0 + % #2: a1 + % #3: a2 + % #4: a3 + % #5: a4 + % #6: x + \pgfmathparse{#1+#2*#6% + +#3*#6^2% + +#4*#6^3% + +#5*#6^4}% +} + +\begin{document} + +\begin{tikzpicture} + \begin{axis}[domain=0:2] + % loop through the rows of the table + \pgfplotsinvokeforeach{0,...,\numberofrows}{ + % define each of a0, a1, a2, a3, a4 + % a0 + \pgfplotstablegetelem{#1}{[index]1}\of\coefficients + \pgfmathsetmacro{\aZero}{\pgfplotsretval} + % a1 + \pgfplotstablegetelem{#1}{[index]2}\of\coefficients + \pgfmathsetmacro{\aOne}{\pgfplotsretval} + % a2 + \pgfplotstablegetelem{#1}{[index]3}\of\coefficients + \pgfmathsetmacro{\aTwo}{\pgfplotsretval} + % a3 + \pgfplotstablegetelem{#1}{[index]4}\of\coefficients + \pgfmathsetmacro{\aThree}{\pgfplotsretval} + % a4 + \pgfplotstablegetelem{#1}{[index]5}\of\coefficients + \pgfmathsetmacro{\aFour}{\pgfplotsretval} + % add the polynomial plot + \addplot[domain=0:2,red,thick]{mypoly(\aZero,\aOne,\aTwo,\aThree,\aFour,x)}; + } + \end{axis} +\end{tikzpicture} +\end{document} + +```","I would probably just use a scripting language and create the LaTeX source code. Here is an example in Python. + +``` +#!/usr/bin/env python +import csv +with open('data.csv', 'rb') as csvfile: + coeff = csv.reader(csvfile, delimiter=',') + coeff.next() + for row in coeff: + print(""\\addplot[mark=none] {"" + row[1] + + "" + x * ("" + row[2] + + "" + x * ("" + row[3] + + "" + x * ("" + row[4] + + "" + x * "" + row[5] + "")))};"") + +``` + +To make it easier to load the coefficients I converted your data into a proper csv file. + +``` +d,a0,a1,a2,a3,a4 +0,0.31632,0.038794,-0.637117,0.457322,-0.0940009 +0.002,0.316319,0.0387949,-0.637115,0.457321,-0.0940008 + +``` + +If you redirect the output to a file like this + +``` +python createPlots.py > plots.tex + +``` + +you can then load it later within your main tex file using `\input{}`. + +``` +\documentclass{standalone} +\usepackage{pgfplots, pgfplotstable} +\pgfplotsset{compat=1.12} +\begin{document} + +\begin{tikzpicture} + \begin{axis}[domain=0:2] + \input{plots.tex} + \end{axis} +\end{tikzpicture} +\end{document} + +``` + +--- + +**EDIT:** + +You can of course also run your script from within LaTeX (needs `--shell-escape`). + +``` +\documentclass{standalone} +\usepackage{pgfplots, pgfplotstable} +\pgfplotsset{compat=1.12} +\begin{document} + +\begin{tikzpicture} + \begin{axis}[domain=0:2] + \immediate\write18{python createPlots.py > plots.tex} + \input{plots.tex} + \end{axis} +\end{tikzpicture} +\end{document} + +``` + +--- + +**EDIT 2:** + +So here is a LuaTeX solution. It expects also the properly formatted csv file. + +``` +\documentclass{standalone} +\usepackage{pgfplots, pgfplotstable} +\pgfplotsset{compat=1.12} +\usepackage{luacode} +\begin{document} + +\begin{tikzpicture} + \begin{axis}[domain=0:2] +\begin{luacode} +firstLineSkipped = false +for line in io.lines(""data.csv"") do + if firstLineSkipped then + tex.print(""\\addplot[mark=none] {"" .. line:gsub('.-,','', 1):gsub("","", "" + x*("", 4) .. "")))};""); + else + firstLineSkipped = true + end +end +\end{luacode} + \end{axis} +\end{tikzpicture} +\end{document} + +```" +84358,"As I understand it, copyright applies to creative expression and not for examples rules of games. Does this also apply to the ISO standards ([example, costs CHF 158](https://www.iso.org/standard/30669.html))? For example, could one re-write the standards in one's own words and sell them in competition with ISO? Or is there something that would prevent this, perhaps something like [Copyright in compilation](https://en.wikipedia.org/wiki/Copyright_in_compilation)?",2022/09/15,"['https://law.stackexchange.com/questions/84358', 'https://law.stackexchange.com', 'https://law.stackexchange.com/users/41938/']","Expression vs Idea +------------------ + +> +> As I understand it, copyright applies to creative expression and not for examples rules of games. +> +> +> + +That is not correct as stated. Game rule, or more exactly the fixed expression of a set of game rule (what one finds in the package of a commercial game, or in a book such as *Hoyle's Rules of Games*, can be and usually are protected by copyright. What is **not** protected is the **ideas** expressed in a set of rules. These are sometimes called ""game mechanics"". For example it is a rule of bridge that 13 cards are dealt to each of 4 players. That is a fact, and so is not protected by copyright. But the exact wording of the official *Laws of Duplicate Bridge* is protected. + +### ""creativity"" vs ""originality"" + +Many things that might not be considered very creative are protected. US Copyright law calls not for creativity, but for an **original work**. The concepts of ""creativity"" and ""originality"" have a significant overlap, but are not at all the same. + +For example, a person might watch a baseball game and write down play-by-play account of it. That might not be very creative, but it would still be protected by copyright. But the event of the game are facts, and not protected. Someone else might describe the same game in different words, covering the same facts, and that would not be copyright infringement. + +Another example. A person writes a scientific paper describing in detail a series of chemical experiments and the results obtained. That is not very creative (although the design of the experiments might be). It would, however, be protected by copyright. But the facts and ideas would not be protected. Another person could desacribe the same experiments in different words, and that would not be an infringement of copyright. + +### Merger Doctrine + +In extreme cases, such as a basic recipe, there is no expression temperate from the facts. In such a case the [""merger doctrine""](https://en.wikipedia.org/wiki/Idea%E2%80%93expression_distinction#Merger_doctrine) applies, and there is no copyright protection at all. + +Standards +--------- + +Standards, such as ISO standards, are normally protected by copyright. But the ideas expressed in them are not. And since +standards are highly factual, the protection afforded to them is particularly narrow. But when one is testing compliance with a standard, the exact words of the standard may be important. A compliance officer is not likely to accept a paraphrase as a valid substitute. + +### Standards in Laws + +The actual text of laws (and regulations), however (Federal, state, or local) is never protected by copyright. All are in the public domain. So when a law incorporated and reprints a standard, as is often done with fire and building codes, anyone may freely reproduce the codes as set down as part of law, even through the code has been copyrighted and indeed registered, as long as the source is the text of an enacted law or regulation.","“In your own words” would be fine. Trouble might come from another source. If you make people believe that the contents of your document is equivalent to a standard, but it isn’t, that could be a problem. And of course you need to be careful that your document is not a derivative work." +725790,"I can extract all information related with any outlook account from windows registry on windows machine. Like Incoming and outgoing server, username , encrypted password and account type(POP or IMAP). All information which I can collect from windows registry is in hex. + +**I want to extract same information for account which I have configured in thunderbird**. + +Is there any way to do this in windows?",2014/03/04,"['https://superuser.com/questions/725790', 'https://superuser.com', 'https://superuser.com/users/297714/']","Information about Thunderbird account is stored in plain text file at user profile + +``` +%appdata%\thunderbird\profiles\%yourprofile%\prefs.js + +``` + +Passwords are stored under `key3.db` and `signons.sqlite` at same location, but those are somewhat encrytped.","Nirsoft's [MailPassView](http://www.nirsoft.net/utils/mailpv.html) will extract account details from most common mail clients, including port numbers. Like all Nirsoft stuff it's a very useful little tool, although many anti-virus applications will detect it as 'Hack Tool' or 'Potentially Unwanted Program', for obvious reasons." +14472,"I am confused by all the excitement surrounding the EU cookie directive; why is it such a painful thing? + +As far as I can see cookies that are required for your site to function are allowed such as shopping carts and site logins. Am I missing something here? + +The original HTTP specification was designed to work in a stateless way so to my mind this is a stepping stone in the right direction towards stateless RESTful websites. Why should state be added to the process when it is not needed. + +There is plenty of mileage left in Digest Auth etc so why is everyone worried? + +An obvious answer might be that Google Analytics needs to set cookies to be able to track traffic. There is a somewhat unsatisfactory answer to this point: + +So have I missed something that I should be panicking about? What has you worried about it?",2011/05/27,"['https://webmasters.stackexchange.com/questions/14472', 'https://webmasters.stackexchange.com', 'https://webmasters.stackexchange.com/users/7473/']","The ""excitement"" relates to confusion about how the new directive (PDF: [2009/136/EC](http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=OJ%3aL:2009:337:0011:0036%3aEn%3aPDF)) should be interpreted and implemented, and whether or not it's fair to European webmasters: + +### Do the laws apply to third party cookies? + +The UK data protection body in charge of enforcing the laws in Britain says in their guidelines that they're seeking clarification ([see my answer here](https://webmasters.stackexchange.com/questions/14473/google-analytics-and-the-eu-cookie-directive-who-will-fall-foul-of-the-law-goog/14478#14478)), but until then, we don't know whether we'll have to ask permission to use third-party cookies from Google Analytics, for example. + +### Might the laws cripple EU websites? + +If it turns out that the new laws require European webmasters to ask each visitor's permission to use third-party cookies, this will affect a lot of websites and render analytics, affiliate systems, usability testing, and even video embedding from third-parties (many of which use cookies) unusable or far less effective. It will also require many site owners who otherwise wouldn't have had to issue a request to store cookies to suddenly do so, drop the services, or seek cookie-less alternatives. + +### Does the directive apply to services hosted outside of the EU? + +Related to the above, if I run a business from the UK but run a blog on a hosted service outside the EU that makes use of 'unnecessary' cookies, must I rebuild my theme to request permission to use them? If so, will the service be prepared to provide this functionality? If not, do I have to migrate my blog elsewhere? These questions are yet to be answered. + +### How best to obtain permission? + +The new directive exists to ensure that people without technical knowledge have the same control over their privacy as more technical users. It does this by turning an opt-out system (""here's a cookie, you can always vomit it up if you don't want it"") into an opt-in system (""would you like a cookie? here's what's in it...""). + +The new laws are great for consumers, welcomed by privacy groups, more closely aligned with opt-in email and permission marketing conduct, and in line with the sentiment expressed by movements like [Do Not Track,](http://blog.sidstamm.com/2011/01/opting-out-of-behavioral-ads.html) which hope to block information harvesting techniques employed by behavioural ad networks. + +The trouble is that opt-in systems carry more interface overhead than opt-out ones, because a request for permission has to be made to every user. Article 66 of the directive says: + +> +> ""The methods of pro­viding information and offering the right to refuse should +> be as user-friendly as possible."" +> +> +> + +Unfortunately, they leave the actual method as an exercise for the reader. This is probably a good thing, because having the method dictated might make implementing the law even more painful. That said, it still raises a lot of questions about the best way to gain consent. + +The ICO has stepped in to offer a list of six methods to request cookies ([see page 6](http://www.ico.gov.uk/news/current_topics/%7E/media/documents/library/Privacy_and_electronic/Practical_application/advice_on_the_new_cookies_regulations.ashx)). They admit that no solution is ideal: + +1. **Pop ups** (ugly - see [this discussion](https://ux.stackexchange.com/q/7318/5124) - and often ignored by users) +2. **New terms and conditions** (users must explicitly agree to them before using the site) +3. **Settings-led consent** (good for visual customisation, not so good for analytics) +4. **Feature-led consent** (still have to make users aware that cookies are in use) +5. **Functional uses** (they suggest a permanent 'permissions' area with notifications) +6. **Via third parties** (but they don't know how the laws apply yet) + +Since there's no 'one solution fits all' approach to request permission to store cookies, each site owner has to come up with their own way of doing it. Because no real thought has been given to standardising the request format or presenting a common look and feel, we're likely to see a hodge-podge of different pop ups and implementations. + +### Shouldn't browsers be handling this? + +The ideal scenario might be to delegate all of this to the browser, but controls for cookies aren't mature enough and, even if browser updates brought granular cookie support, we'd still have to accommodate older browsers, which makes some kind of in-page request inevitable. + +### Does it present a commercial disadvantage? + +The new privacy laws might make EU Web services less attractive than US ones. As Nick Halsted of TweetMeme says: + +> +> ""If you go to two websites with identical functionality and one of them asks you to sign a big scary box that says ‘I am tracking everything about you’, and the U.S. one doesn’t, which one are you going to sign up for?"" [[source](http://blogs.wsj.com/tech-europe/2011/05/09/confusion-surrounds-u-k-cookie-guidelines/)] +> +> +> + +Not only might the addition of a modal permissions bar result in decreased sign ups and engagement, but we can't even split-test alternative request methods, because tracking the results of a split test first requires us to ask the user for permission. + +What's more, if it turns out that EU businesses can't use Google Analytics et al without permission from each visitor (when US businesses can), isn't that a competitive disadvantage too? The US already has a thriving start-up community and funding ecosystem. Some would argue that privacy directives, while great for users, are a pain for businesses because they further stifle those competing with companies outside the EU. + +### Has it really been thought through? + +While the goal of empowering users with decisions over their own privacy is a noble one, the usability aspects haven't been thought through. The good news is that (in the UK, at least) we have until May 2012 to figure something out. + +In short, it's nothing to *worry* about, but there's a lot to *think* about. Once the ICO clarifies the case for third party cookies and other EU data protection officers have done the same, it's important that European webmasters pool resources to present a unified solution.","It appears to be painful for people who read the headlines and don't know that about those allowed exceptions. + +It is also painful if you have cookies for statistical purposes as they aren't allowed without consent: + +> +> The exception would not apply, for +> example, just because you have +> decided that your website is more +> attractive if you remember users’ +> preferences or if you decide to use a +> cookie to collect statistical +> information about the use of your +> website. +> +> +> + + + +It's also painful because although it's easy to put JavaScript on your site that does statistics tracking it's not easy unless you've seen that plugin." +14472,"I am confused by all the excitement surrounding the EU cookie directive; why is it such a painful thing? + +As far as I can see cookies that are required for your site to function are allowed such as shopping carts and site logins. Am I missing something here? + +The original HTTP specification was designed to work in a stateless way so to my mind this is a stepping stone in the right direction towards stateless RESTful websites. Why should state be added to the process when it is not needed. + +There is plenty of mileage left in Digest Auth etc so why is everyone worried? + +An obvious answer might be that Google Analytics needs to set cookies to be able to track traffic. There is a somewhat unsatisfactory answer to this point: + +So have I missed something that I should be panicking about? What has you worried about it?",2011/05/27,"['https://webmasters.stackexchange.com/questions/14472', 'https://webmasters.stackexchange.com', 'https://webmasters.stackexchange.com/users/7473/']","The ""excitement"" relates to confusion about how the new directive (PDF: [2009/136/EC](http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=OJ%3aL:2009:337:0011:0036%3aEn%3aPDF)) should be interpreted and implemented, and whether or not it's fair to European webmasters: + +### Do the laws apply to third party cookies? + +The UK data protection body in charge of enforcing the laws in Britain says in their guidelines that they're seeking clarification ([see my answer here](https://webmasters.stackexchange.com/questions/14473/google-analytics-and-the-eu-cookie-directive-who-will-fall-foul-of-the-law-goog/14478#14478)), but until then, we don't know whether we'll have to ask permission to use third-party cookies from Google Analytics, for example. + +### Might the laws cripple EU websites? + +If it turns out that the new laws require European webmasters to ask each visitor's permission to use third-party cookies, this will affect a lot of websites and render analytics, affiliate systems, usability testing, and even video embedding from third-parties (many of which use cookies) unusable or far less effective. It will also require many site owners who otherwise wouldn't have had to issue a request to store cookies to suddenly do so, drop the services, or seek cookie-less alternatives. + +### Does the directive apply to services hosted outside of the EU? + +Related to the above, if I run a business from the UK but run a blog on a hosted service outside the EU that makes use of 'unnecessary' cookies, must I rebuild my theme to request permission to use them? If so, will the service be prepared to provide this functionality? If not, do I have to migrate my blog elsewhere? These questions are yet to be answered. + +### How best to obtain permission? + +The new directive exists to ensure that people without technical knowledge have the same control over their privacy as more technical users. It does this by turning an opt-out system (""here's a cookie, you can always vomit it up if you don't want it"") into an opt-in system (""would you like a cookie? here's what's in it...""). + +The new laws are great for consumers, welcomed by privacy groups, more closely aligned with opt-in email and permission marketing conduct, and in line with the sentiment expressed by movements like [Do Not Track,](http://blog.sidstamm.com/2011/01/opting-out-of-behavioral-ads.html) which hope to block information harvesting techniques employed by behavioural ad networks. + +The trouble is that opt-in systems carry more interface overhead than opt-out ones, because a request for permission has to be made to every user. Article 66 of the directive says: + +> +> ""The methods of pro­viding information and offering the right to refuse should +> be as user-friendly as possible."" +> +> +> + +Unfortunately, they leave the actual method as an exercise for the reader. This is probably a good thing, because having the method dictated might make implementing the law even more painful. That said, it still raises a lot of questions about the best way to gain consent. + +The ICO has stepped in to offer a list of six methods to request cookies ([see page 6](http://www.ico.gov.uk/news/current_topics/%7E/media/documents/library/Privacy_and_electronic/Practical_application/advice_on_the_new_cookies_regulations.ashx)). They admit that no solution is ideal: + +1. **Pop ups** (ugly - see [this discussion](https://ux.stackexchange.com/q/7318/5124) - and often ignored by users) +2. **New terms and conditions** (users must explicitly agree to them before using the site) +3. **Settings-led consent** (good for visual customisation, not so good for analytics) +4. **Feature-led consent** (still have to make users aware that cookies are in use) +5. **Functional uses** (they suggest a permanent 'permissions' area with notifications) +6. **Via third parties** (but they don't know how the laws apply yet) + +Since there's no 'one solution fits all' approach to request permission to store cookies, each site owner has to come up with their own way of doing it. Because no real thought has been given to standardising the request format or presenting a common look and feel, we're likely to see a hodge-podge of different pop ups and implementations. + +### Shouldn't browsers be handling this? + +The ideal scenario might be to delegate all of this to the browser, but controls for cookies aren't mature enough and, even if browser updates brought granular cookie support, we'd still have to accommodate older browsers, which makes some kind of in-page request inevitable. + +### Does it present a commercial disadvantage? + +The new privacy laws might make EU Web services less attractive than US ones. As Nick Halsted of TweetMeme says: + +> +> ""If you go to two websites with identical functionality and one of them asks you to sign a big scary box that says ‘I am tracking everything about you’, and the U.S. one doesn’t, which one are you going to sign up for?"" [[source](http://blogs.wsj.com/tech-europe/2011/05/09/confusion-surrounds-u-k-cookie-guidelines/)] +> +> +> + +Not only might the addition of a modal permissions bar result in decreased sign ups and engagement, but we can't even split-test alternative request methods, because tracking the results of a split test first requires us to ask the user for permission. + +What's more, if it turns out that EU businesses can't use Google Analytics et al without permission from each visitor (when US businesses can), isn't that a competitive disadvantage too? The US already has a thriving start-up community and funding ecosystem. Some would argue that privacy directives, while great for users, are a pain for businesses because they further stifle those competing with companies outside the EU. + +### Has it really been thought through? + +While the goal of empowering users with decisions over their own privacy is a noble one, the usability aspects haven't been thought through. The good news is that (in the UK, at least) we have until May 2012 to figure something out. + +In short, it's nothing to *worry* about, but there's a lot to *think* about. Once the ICO clarifies the case for third party cookies and other EU data protection officers have done the same, it's important that European webmasters pool resources to present a unified solution.","Most complaints I've seen fall outside of the exceptions you've mentioned and more into the realm of marketing/data. Some of the big issues I see are: + +1. Standard analytics (Google Analytics and others) +2. Additional testing (A/B testing etc for usability/conversion rate optimization) +3. Affiliate tracking. +4. Re-marketing there are many programs now that drop a cookie and generate dynamic ads based on user's activity. +5. Personalization - such as offering personalized product recommendations based on previously viewed products etc. + +Admittedly I'm US based so I haven't followed this as closely as others may have but I don't believe any of the above fall into the ""exceptions"" and all are widely used." +21041564,"Is there any way to do the following without either invoking garbage collection or increasing heap size to avoid eventual GC? + +``` +List someList = new ArrayList(); +someList.add(1l); +someList = new ArrayList(); //Will this cause GC of the old `someList`? + +``` + +So what I'm asking is if the original `ArrayList` will get deleted (and eventually GCd)? If so, how do I remedy this such that I can overwrite the original list without GCing?",2014/01/10,"['https://Stackoverflow.com/questions/21041564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2763361/']","Use [ArrayList.clear();](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#clear%28%29) instead of creating new ArrayList + +``` +someList.clear(); + +```","The older `ArrayList` will become eligible for garbage collection on line 3, provided there is no other reference pointing to it, as it seems is the case here. However, it isn't guaranteed to be GCed right away. + +If you want to avoid extra creation of the `ArrayList`, you can simply clear it by using `List#clear()` method: + +``` +someList.clear(); + +```" +21041564,"Is there any way to do the following without either invoking garbage collection or increasing heap size to avoid eventual GC? + +``` +List someList = new ArrayList(); +someList.add(1l); +someList = new ArrayList(); //Will this cause GC of the old `someList`? + +``` + +So what I'm asking is if the original `ArrayList` will get deleted (and eventually GCd)? If so, how do I remedy this such that I can overwrite the original list without GCing?",2014/01/10,"['https://Stackoverflow.com/questions/21041564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2763361/']","The older `ArrayList` will become eligible for garbage collection on line 3, provided there is no other reference pointing to it, as it seems is the case here. However, it isn't guaranteed to be GCed right away. + +If you want to avoid extra creation of the `ArrayList`, you can simply clear it by using `List#clear()` method: + +``` +someList.clear(); + +```","I assume by your question you want to keep a reference to the old list (and also its content, otherwise whats the point)? + +If so then just add a reference to it before reassigning: + +``` +List someList = new ArrayList(); +someList.add(1L); +List oldList = someList; +someList = new ArrayList(); + +```" +21041564,"Is there any way to do the following without either invoking garbage collection or increasing heap size to avoid eventual GC? + +``` +List someList = new ArrayList(); +someList.add(1l); +someList = new ArrayList(); //Will this cause GC of the old `someList`? + +``` + +So what I'm asking is if the original `ArrayList` will get deleted (and eventually GCd)? If so, how do I remedy this such that I can overwrite the original list without GCing?",2014/01/10,"['https://Stackoverflow.com/questions/21041564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2763361/']","Use [ArrayList.clear();](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#clear%28%29) instead of creating new ArrayList + +``` +someList.clear(); + +```","I assume by your question you want to keep a reference to the old list (and also its content, otherwise whats the point)? + +If so then just add a reference to it before reassigning: + +``` +List someList = new ArrayList(); +someList.add(1L); +List oldList = someList; +someList = new ArrayList(); + +```" +38645,"Just after 3:23 in [this TED Radio Hour segment](http://www.npr.org/2016/10/21/497837955/what-can-we-learn-from-one-of-the-world-s-most-toxic-accidents), featured guest Holly Morris makes the claim that ""the older you are, the less detrimental the effects of radiation is."" The context is in why explaining older people were allowed to return to their homes near Chernobyl following the nuclear accident. Is it true that the elderly are less sensitive to ionizing radiation than younger people, and that detrimental effects of ionizing radiation decrease with age? + +--- + +Note: The [original TED talk](https://www.ted.com/talks/holly_morris_why_stay_in_chernobyl_because_it_s_home/transcript?language=en) (2:11-2:34) indicates these people returned illegally, in defiance of authorities, while the later radio program claims the women ""were allowed back into the area,"" and this age explanation is given as to why they were allowed to return, contrasted with young people who were not allowed to return (radio 3:34).",2017/06/10,"['https://skeptics.stackexchange.com/questions/38645', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/27319/']","It seems plausible that such a ""pool"" did exist at Auschwitz in 1944. It probably served several purposes: A pool for swimming in by hard working prisoners, a fire reservoir tank and possible to fool the West at the same time who took aerial photos of the camp in order to see the living conditions of the prisoners. + +> +> Barbara Cherish, the daughter of Arthur Liebehenschel, wrote a book which was published in 2009, entitled ""My father, the Auschwitz commandant."" In her book, Barbara credits her father with building a swimming pool for the use of the prisoners. Liebehenschel was the Commandant of the Auschwitz main camp for five months, beginning on December 1, 1943. Liebehenschel is credited with other improvements at Auschwitz I, including the tearing down of the standing cells in Block 11. - [Swimming Pool at Auschwitz I](https://www.scrapbookpages.com/AuschwitzScrapbook/Tour/Auschwitz1/AuschwitzPool.html) +> +> +> + +[![Swimming pool at Auschwitz main camp, 1996](https://i.stack.imgur.com/HCqUM.jpg)](https://i.stack.imgur.com/HCqUM.jpg) + +> +> The photo [above] shows what the swimming pool looked like in 1996 before preservation work began. The high diving board is at the far end in the background of the photo. The diving board itself is now gone. - [Swimming Pool at Auschwitz I](https://www.scrapbookpages.com/AuschwitzScrapbook/Tour/Auschwitz1/AuschwitzPool.html) +> +> +>","> +> Is it a ""fire brigade reservoir"", which I assume has something to do with fire safety although I don't know exactly what this means or why they would need it? +> +> +> + +A fire brigade reservoir is a [supply of water](http://www.firerescuemagazine.com/articles/print/volume-9/issue-3/firefighting-operations/obtaining-water-without-a-hydrant.html) that can be pumped at a fire. They are often used in places where [fire hydrants are not available](http://www.bcfpd.org/index.php/faq/put-fires-no-fire-hydrants) or are insufficient to meet the demand. For example, where people get their water from a well rather than a municipal source. + +As a practical matter, almost any water can be used (although some may be easier to use). So if that was something that collected water, it could be a fire brigade reservoir. That is true even if it was also used as a swimming pool. + +My point being that it being a fire brigade reservoir would not prevent it from being a swimming pool. Or vice versa. They are not mutually exclusive uses. + +In regards to whether this particular water was actually a swimming pool, I have nothing to add to the [other answer](https://skeptics.stackexchange.com/a/38643/30596). + +Additional sources: + +* [Quora](https://www.quora.com/In-neighborhoods-lacking-fire-hydrants-what-do-fire-departments-use-as-water-sources-when-dealing-with-fires) +* [Facebook](https://www.facebook.com/notes/eastern-panhandle-working-fires/what-if-there-is-not-a-fire-hydrant-nearby-where-i-live/540193675999432/)" +38645,"Just after 3:23 in [this TED Radio Hour segment](http://www.npr.org/2016/10/21/497837955/what-can-we-learn-from-one-of-the-world-s-most-toxic-accidents), featured guest Holly Morris makes the claim that ""the older you are, the less detrimental the effects of radiation is."" The context is in why explaining older people were allowed to return to their homes near Chernobyl following the nuclear accident. Is it true that the elderly are less sensitive to ionizing radiation than younger people, and that detrimental effects of ionizing radiation decrease with age? + +--- + +Note: The [original TED talk](https://www.ted.com/talks/holly_morris_why_stay_in_chernobyl_because_it_s_home/transcript?language=en) (2:11-2:34) indicates these people returned illegally, in defiance of authorities, while the later radio program claims the women ""were allowed back into the area,"" and this age explanation is given as to why they were allowed to return, contrasted with young people who were not allowed to return (radio 3:34).",2017/06/10,"['https://skeptics.stackexchange.com/questions/38645', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/27319/']","It seems plausible that such a ""pool"" did exist at Auschwitz in 1944. It probably served several purposes: A pool for swimming in by hard working prisoners, a fire reservoir tank and possible to fool the West at the same time who took aerial photos of the camp in order to see the living conditions of the prisoners. + +> +> Barbara Cherish, the daughter of Arthur Liebehenschel, wrote a book which was published in 2009, entitled ""My father, the Auschwitz commandant."" In her book, Barbara credits her father with building a swimming pool for the use of the prisoners. Liebehenschel was the Commandant of the Auschwitz main camp for five months, beginning on December 1, 1943. Liebehenschel is credited with other improvements at Auschwitz I, including the tearing down of the standing cells in Block 11. - [Swimming Pool at Auschwitz I](https://www.scrapbookpages.com/AuschwitzScrapbook/Tour/Auschwitz1/AuschwitzPool.html) +> +> +> + +[![Swimming pool at Auschwitz main camp, 1996](https://i.stack.imgur.com/HCqUM.jpg)](https://i.stack.imgur.com/HCqUM.jpg) + +> +> The photo [above] shows what the swimming pool looked like in 1996 before preservation work began. The high diving board is at the far end in the background of the photo. The diving board itself is now gone. - [Swimming Pool at Auschwitz I](https://www.scrapbookpages.com/AuschwitzScrapbook/Tour/Auschwitz1/AuschwitzPool.html) +> +> +>","According to the [Third Reich in Ruins](http://www.thirdreichruins.com/auschwitz.htm), the below photo of the pool was obtained from [Auschwitz-Birkenau State Museum](http://www.auschwitz.org/). The site says: + +> +> This water tank was built as a reservoir for fire fighting purposes (there are several such fire fighting tanks around the Birkenau camp and the Auschwitz Erweiterungslager camp extension), but it was modified by the prisoner fire brigade into a swimming pool, complete with a diving board and starting blocks. Privileged Polish and other political prisoners (non-Jewish), in addition to the fire brigade, could use this pool. +> +> +> + +[![enter image description here](https://i.stack.imgur.com/W6gZ9.jpg)](https://i.stack.imgur.com/W6gZ9.jpg)" +38645,"Just after 3:23 in [this TED Radio Hour segment](http://www.npr.org/2016/10/21/497837955/what-can-we-learn-from-one-of-the-world-s-most-toxic-accidents), featured guest Holly Morris makes the claim that ""the older you are, the less detrimental the effects of radiation is."" The context is in why explaining older people were allowed to return to their homes near Chernobyl following the nuclear accident. Is it true that the elderly are less sensitive to ionizing radiation than younger people, and that detrimental effects of ionizing radiation decrease with age? + +--- + +Note: The [original TED talk](https://www.ted.com/talks/holly_morris_why_stay_in_chernobyl_because_it_s_home/transcript?language=en) (2:11-2:34) indicates these people returned illegally, in defiance of authorities, while the later radio program claims the women ""were allowed back into the area,"" and this age explanation is given as to why they were allowed to return, contrasted with young people who were not allowed to return (radio 3:34).",2017/06/10,"['https://skeptics.stackexchange.com/questions/38645', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/27319/']","According to the [Third Reich in Ruins](http://www.thirdreichruins.com/auschwitz.htm), the below photo of the pool was obtained from [Auschwitz-Birkenau State Museum](http://www.auschwitz.org/). The site says: + +> +> This water tank was built as a reservoir for fire fighting purposes (there are several such fire fighting tanks around the Birkenau camp and the Auschwitz Erweiterungslager camp extension), but it was modified by the prisoner fire brigade into a swimming pool, complete with a diving board and starting blocks. Privileged Polish and other political prisoners (non-Jewish), in addition to the fire brigade, could use this pool. +> +> +> + +[![enter image description here](https://i.stack.imgur.com/W6gZ9.jpg)](https://i.stack.imgur.com/W6gZ9.jpg)","> +> Is it a ""fire brigade reservoir"", which I assume has something to do with fire safety although I don't know exactly what this means or why they would need it? +> +> +> + +A fire brigade reservoir is a [supply of water](http://www.firerescuemagazine.com/articles/print/volume-9/issue-3/firefighting-operations/obtaining-water-without-a-hydrant.html) that can be pumped at a fire. They are often used in places where [fire hydrants are not available](http://www.bcfpd.org/index.php/faq/put-fires-no-fire-hydrants) or are insufficient to meet the demand. For example, where people get their water from a well rather than a municipal source. + +As a practical matter, almost any water can be used (although some may be easier to use). So if that was something that collected water, it could be a fire brigade reservoir. That is true even if it was also used as a swimming pool. + +My point being that it being a fire brigade reservoir would not prevent it from being a swimming pool. Or vice versa. They are not mutually exclusive uses. + +In regards to whether this particular water was actually a swimming pool, I have nothing to add to the [other answer](https://skeptics.stackexchange.com/a/38643/30596). + +Additional sources: + +* [Quora](https://www.quora.com/In-neighborhoods-lacking-fire-hydrants-what-do-fire-departments-use-as-water-sources-when-dealing-with-fires) +* [Facebook](https://www.facebook.com/notes/eastern-panhandle-working-fires/what-if-there-is-not-a-fire-hydrant-nearby-where-i-live/540193675999432/)" +3702998,"I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling. + +1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar) +2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use? + +I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user.",2010/09/13,"['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/']","I tried [android-CalendarView](http://developer.android.com/reference/android/widget/CalendarView.html), Caldroid and later switched to **[android-times-square](https://github.com/square/android-times-square)** which has this improvements: + +* Much faster switching to other months due to vertical scrolling (no pagination which responds slow in Caldroid) +* Indicators, highlighted dates (at least in [this fork](https://github.com/HannahMitt/android-times-square) for android) +* iOS version available with the same look and feel +* looks cleaner than the android version because months are clearly separated + +![enter image description here](https://i.stack.imgur.com/zloKv.png) + +Just like Caldroid it is a part of [a productive app](http://corner.squareup.com/2013/01/times-square.html).","it is possible but not easy. + + +and + +``` +private void InsertAppointment(String strTitle, String strDescription, String strEventLocation, long StartDateTime, long EndDateTime, boolean bAllDay, boolean bHasAlarm){ + int tAllday; + int tHasAlarm; + if (bAllDay = true){ + tAllday = 1; + } + else + tAllday = 0; + if (bHasAlarm = true){ + tHasAlarm = 1; + } + else + tHasAlarm = 0; + + ContentValues event = new ContentValues(); + // Calendar in which you want to add Evenet + event.put(""calendar_id"", CalId); //CalId + event.put(""title"", strTitle); + event.put(""description"", strDescription); + event.put(""eventLocation"", strEventLocation); + event.put(""dtstart"", StartDateTime); + event.put(""dtend"", EndDateTime ); + event.put(""allDay"", 0); + event.put(""hasAlarm"", 0); + Uri eventsUri = Uri.parse(""content://com.android.calendar/events""); + // event is added + getContentResolver().insert(eventsUri, event); + +} + +``` + +a quick search on + `content://com.android.calendar/calendars` +will help get you started. but I'm not finished mine yet I just can't get the data out yet. but it is possible" +3702998,"I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling. + +1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar) +2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use? + +I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user.",2010/09/13,"['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/']","AFAIK, there are no other way than implement your own calendar. So... what you would have to do is using a `GridLayout` with 7 columns and create a custom `BaseAdapter` to display data correctly.","it is possible but not easy. + + +and + +``` +private void InsertAppointment(String strTitle, String strDescription, String strEventLocation, long StartDateTime, long EndDateTime, boolean bAllDay, boolean bHasAlarm){ + int tAllday; + int tHasAlarm; + if (bAllDay = true){ + tAllday = 1; + } + else + tAllday = 0; + if (bHasAlarm = true){ + tHasAlarm = 1; + } + else + tHasAlarm = 0; + + ContentValues event = new ContentValues(); + // Calendar in which you want to add Evenet + event.put(""calendar_id"", CalId); //CalId + event.put(""title"", strTitle); + event.put(""description"", strDescription); + event.put(""eventLocation"", strEventLocation); + event.put(""dtstart"", StartDateTime); + event.put(""dtend"", EndDateTime ); + event.put(""allDay"", 0); + event.put(""hasAlarm"", 0); + Uri eventsUri = Uri.parse(""content://com.android.calendar/events""); + // event is added + getContentResolver().insert(eventsUri, event); + +} + +``` + +a quick search on + `content://com.android.calendar/calendars` +will help get you started. but I'm not finished mine yet I just can't get the data out yet. but it is possible" +3702998,"I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling. + +1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar) +2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use? + +I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user.",2010/09/13,"['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/']","Android now provides three ways to incorporate calendars in your app. + +1. [Calendar view](http://developer.android.com/reference/android/widget/CalendarView.html) for picking dates and such. +2. [Calendar provider](http://developer.android.com/guide/topics/providers/calendar-provider.html) can be accessed to add and remove events from the OS calendar. +3. [Calendar intents](http://developer.android.com/guide/topics/providers/calendar-provider.html#intents) allow you to provide a calendar without having to get extra permissions or deal with databases.","You can use MFCalendarView: + +set multiple events; + +``` +ArrayList eventDays = new ArrayList(); +eventDays.add(""2014-02-25""); +eventDays.add(Util.getCurrentDate()); + +mf.setEvents(eventDays); + +``` + +and handle with MFCalendarView's listener: + +``` +mf = (MFCalendarView) findViewById(R.id.mFCalendarView); +mf.setOnCalendarViewListener(new onMFCalendarViewListener() { + + @Override + public void onDisplayedMonthChanged(int month, int year, String monthStr) { + } + + @Override + public void onDateChanged(String date) { + } + }); + +``` + +It's very simple." +3702998,"I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling. + +1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar) +2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use? + +I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user.",2010/09/13,"['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/']","I tried [android-CalendarView](http://developer.android.com/reference/android/widget/CalendarView.html), Caldroid and later switched to **[android-times-square](https://github.com/square/android-times-square)** which has this improvements: + +* Much faster switching to other months due to vertical scrolling (no pagination which responds slow in Caldroid) +* Indicators, highlighted dates (at least in [this fork](https://github.com/HannahMitt/android-times-square) for android) +* iOS version available with the same look and feel +* looks cleaner than the android version because months are clearly separated + +![enter image description here](https://i.stack.imgur.com/zloKv.png) + +Just like Caldroid it is a part of [a productive app](http://corner.squareup.com/2013/01/times-square.html).","You can use the android calendar picker I have created, it is open source project and you can easily add it to your project. + +" +3702998,"I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling. + +1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar) +2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use? + +I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user.",2010/09/13,"['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/']","AFAIK, there are no other way than implement your own calendar. So... what you would have to do is using a `GridLayout` with 7 columns and create a custom `BaseAdapter` to display data correctly.","You can use the android calendar picker I have created, it is open source project and you can easily add it to your project. + +" +3702998,"I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling. + +1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar) +2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use? + +I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user.",2010/09/13,"['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/']","I wrote Caldroid library () that is simple to setup and have many features such as setup min/max date, disabled dates, select date range, swipe to change month, fully localized, support rotation properly etc. It's easy to customize the look and feel. Just to share if someone might find it useful :)","You can use MFCalendarView: + +set multiple events; + +``` +ArrayList eventDays = new ArrayList(); +eventDays.add(""2014-02-25""); +eventDays.add(Util.getCurrentDate()); + +mf.setEvents(eventDays); + +``` + +and handle with MFCalendarView's listener: + +``` +mf = (MFCalendarView) findViewById(R.id.mFCalendarView); +mf.setOnCalendarViewListener(new onMFCalendarViewListener() { + + @Override + public void onDisplayedMonthChanged(int month, int year, String monthStr) { + } + + @Override + public void onDateChanged(String date) { + } + }); + +``` + +It's very simple." +3702998,"I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling. + +1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar) +2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use? + +I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user.",2010/09/13,"['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/']","Android now provides three ways to incorporate calendars in your app. + +1. [Calendar view](http://developer.android.com/reference/android/widget/CalendarView.html) for picking dates and such. +2. [Calendar provider](http://developer.android.com/guide/topics/providers/calendar-provider.html) can be accessed to add and remove events from the OS calendar. +3. [Calendar intents](http://developer.android.com/guide/topics/providers/calendar-provider.html#intents) allow you to provide a calendar without having to get extra permissions or deal with databases.","You can use the android calendar picker I have created, it is open source project and you can easily add it to your project. + +" +3702998,"I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling. + +1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar) +2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use? + +I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user.",2010/09/13,"['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/']","AFAIK, there are no other way than implement your own calendar. So... what you would have to do is using a `GridLayout` with 7 columns and create a custom `BaseAdapter` to display data correctly.","You can use MFCalendarView: + +set multiple events; + +``` +ArrayList eventDays = new ArrayList(); +eventDays.add(""2014-02-25""); +eventDays.add(Util.getCurrentDate()); + +mf.setEvents(eventDays); + +``` + +and handle with MFCalendarView's listener: + +``` +mf = (MFCalendarView) findViewById(R.id.mFCalendarView); +mf.setOnCalendarViewListener(new onMFCalendarViewListener() { + + @Override + public void onDisplayedMonthChanged(int month, int year, String monthStr) { + } + + @Override + public void onDateChanged(String date) { + } + }); + +``` + +It's very simple." +3702998,"I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling. + +1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar) +2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use? + +I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user.",2010/09/13,"['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/']","This library seems really nice and with a more modern UI (Material Design) : + + + +You just have to import it with gradle: + +``` +compile 'com.prolificinteractive:material-calendarview:1.4.0' + +``` + +And add it in your layout: + +``` + + +``` + +[![enter image description here](https://i.stack.imgur.com/Fb4xc.gif)](https://i.stack.imgur.com/Fb4xc.gif)","You can use MFCalendarView: + +set multiple events; + +``` +ArrayList eventDays = new ArrayList(); +eventDays.add(""2014-02-25""); +eventDays.add(Util.getCurrentDate()); + +mf.setEvents(eventDays); + +``` + +and handle with MFCalendarView's listener: + +``` +mf = (MFCalendarView) findViewById(R.id.mFCalendarView); +mf.setOnCalendarViewListener(new onMFCalendarViewListener() { + + @Override + public void onDisplayedMonthChanged(int month, int year, String monthStr) { + } + + @Override + public void onDateChanged(String date) { + } + }); + +``` + +It's very simple." +3702998,"I'm pretty new to Android development and I'm looking for a means of including calendar in my Android application, but I'm striking out pretty bad when googling. + +1. Is there any way to use a default calendar kind of view in my application? (would be ideal since the UI would be familiar) +2. Failing at a built-in option, are there any good libraries out there with a calendar control that I could use? + +I'm not looking to sync and all of that (at least, at this point), just looking to have a calendar view that I can display information to the user.",2010/09/13,"['https://Stackoverflow.com/questions/3702998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446605/']","I wrote Caldroid library () that is simple to setup and have many features such as setup min/max date, disabled dates, select date range, swipe to change month, fully localized, support rotation properly etc. It's easy to customize the look and feel. Just to share if someone might find it useful :)","Android now provides three ways to incorporate calendars in your app. + +1. [Calendar view](http://developer.android.com/reference/android/widget/CalendarView.html) for picking dates and such. +2. [Calendar provider](http://developer.android.com/guide/topics/providers/calendar-provider.html) can be accessed to add and remove events from the OS calendar. +3. [Calendar intents](http://developer.android.com/guide/topics/providers/calendar-provider.html#intents) allow you to provide a calendar without having to get extra permissions or deal with databases." +30189605,"I've been playing around with flex box and I would like to center the ""Logo"" test in the upper left corner vertically in its blue container. + +You can see it here: + +``` +* { + margin: 0; + padding: 0; +} +.box { + color: white; + font-size: 80px; + text-align: center; + text-shadow: 4px 4px 3px black; +} + +/* COLORS & Style +===================================== */ + +.main-header { background: #e3e3e3; } +.main-footer { background: #e3e3e3; } +.main-content { background: #e3e3e3; } + +.main-wrapper { + box-shadow: 2px 2px 10px #333; +} + +.main-wrapper { + width: 80%; + margin: 0 auto; +} + +/* HEAD +===================================== */ + +.main-header { + width: 100%; + height: 100px; + border-bottom: 1px solid black; +} + +.main-nav { + list-style: none; + display: flex; + flex-flow: row wrap; + justify-content: flex-end; + align-items: flex-end; + height: 100%; + +} + +.main-nav li { + margin-left: 8px; + margin-right: 8px; +} + +#logo { + margin-right: auto; /* Align Logo to Left, Nav to the right*/ + margin-left: 0; + align-self: center; +} + +.main-nav li:last-child { + margin-right: 0; +} + +.main-nav li { + background-color: #3f8abf; + border-top-left-radius: 5px; + border-top-right-radius: 5px; + border-bottom: 4px solid firebrick; + +} +.main-nav a { + text-decoration: none; + color: white; + text-align: center; + font-weight: bold; + padding: 8px 15px; + display: block; + width: 100px; +} + +#logo { + border-top-left-radius: 0; + border-bottom-right-radius: 5px; + border-bottom: 0; + border-left: 4px solid firebrick; + padding: 0; + height: 100%; + +} + +#logo h1 { + padding: 0; + margin: 0; +} + +/* CONTENT +===================================== */ + +.main-content { + padding: 15px; +} +h3 { + margin-bottom: 15px; +} + +/* FOOTER +===================================== */ + +.main-footer { + border-top: 1px solid black; + text-align: center; + padding: 5px; +} + +``` + +I tried margin and padding auto but that doesnt seem to work, please help!",2015/05/12,"['https://Stackoverflow.com/questions/30189605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4400418/']","This approach uses a public enum and sets the style variable according to the users menu choice: + +``` +package chess; +//... +public class Screen extends JFrame + implements ActionListener { + + private JMenuItem random = new JMenuItem(""Random""); + private JMenuItem aggressive = new JMenuItem(""Aggressive""); + private JMenuItem human = new JMenuItem(""Human""); + + public enum PlayStyle {Random, Aggressive, Human}; + private PlayStyle style; + + public Screen(Board board) { + + //menuBar items + menu.add(random); + random.addActionListener(this); + menu.add(aggressive); + aggressive.addActionListener(this); + menu.add(human); + human.addActionListener(this); + //.... + //sets up board of buttons and adds actionListener to each. + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == random) { + style=PlayStyle.Random; + } + if (e.getSource() == aggressive) { + style=PlayStyle.Aggressive; + } + if (e.getSource() == human) { + style=PlayStyle.Human; + } + + //code for the board buttons - nothing to do with the menu. + //.... + } + public PlayStyle getStyle(){ + return style; + } + +} + +``` + +This is the class that contains the main method: + +``` +package chess; + +import chess.Screen.PlayStyle; + +public class Chess{ + + public static void main(String [ ] args){ + Screen s = new Screen(board); + + // this attempt will work + if (s.getStyle()==PlayStyle.Random) { + ... + } else if (s.getStyle()==PlayStyle.Aggressive){ + ... + +```","You are calling a method and it seems that you want to use something that comes back from that method but the method itself returns nothing, i.e. ""void"". I changed your Screen class so that the method returns something now. + +``` +public class Screen extends JFrame + implements ActionListener { + public Source actionPerformed(ActionEvent e) { + + .... + + if(e.getSource() == random){ + + } + if(e.getSource() == aggressive){ + + } + if(e.getSource() == human){ + + } + + return e.getSource() +} + +``` + +The main method will now be able to receive a result from the call and use it." +1328078,"In the ""Control Panel > Ease of Access Centre > Make the keyboard easier to use"" is an option to ""Underline keyboard shortcuts and access keys."" + +Is there a way of programmatically switching this on and off? +I'm using Visual Basic Scripts, but can use .NET.",2009/08/25,"['https://Stackoverflow.com/questions/1328078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1726/']","1. Run Registry Editor and go to HKEY\_CURRENT\_USER\Control Panel\Accessibility\Keyboard Preference +2. Now create or modify a String Value (REG\_SZ) called On and set its value to 1 + +Information is comming from: +","AFAIK, there's no way to toggle this option programmatically except for automating the approproate GUI actions (opening the Control Panel, switching the option on/off and applying the changes). In this case, I'd recommend using [AutoIt](http://www.autoitscript.com/autoit3/index.shtml) to automate the option switching." +1328078,"In the ""Control Panel > Ease of Access Centre > Make the keyboard easier to use"" is an option to ""Underline keyboard shortcuts and access keys."" + +Is there a way of programmatically switching this on and off? +I'm using Visual Basic Scripts, but can use .NET.",2009/08/25,"['https://Stackoverflow.com/questions/1328078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1726/']","AFAIK, there's no way to toggle this option programmatically except for automating the approproate GUI actions (opening the Control Panel, switching the option on/off and applying the changes). In this case, I'd recommend using [AutoIt](http://www.autoitscript.com/autoit3/index.shtml) to automate the option switching.","It turns out you CAN programatically change the “underline keyboard shortcuts” option in your own application. You need to send the WM\_UPDATEUISTATE message to your main form according to the documentation found at: + +Since you mentioned Visual Basic, here's how to do it: + +``` +Private Const WM_UPDATEUISTATE = &H128 +Private Const UIS_CLEAR = &H2 +Private Const UISF_HIDEACCEL = &H2 +Private Declare Function PostMessage Lib ""user32"" Alias ""PostMessageA"" (ByVal hWnd As +Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long + +``` + +Then in the ""Form\_Load"" event send the message and it will activate keyboard shortcuts underlining for all controls and menus present on that form: + +``` +Private Sub Form_Load() + PostMessage Me.hWnd, WM_UPDATEUISTATE, UIS_CLEAR + UISF_HIDEACCEL * 65536, 0 +End Sub + +```" +1328078,"In the ""Control Panel > Ease of Access Centre > Make the keyboard easier to use"" is an option to ""Underline keyboard shortcuts and access keys."" + +Is there a way of programmatically switching this on and off? +I'm using Visual Basic Scripts, but can use .NET.",2009/08/25,"['https://Stackoverflow.com/questions/1328078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1726/']","1. Run Registry Editor and go to HKEY\_CURRENT\_USER\Control Panel\Accessibility\Keyboard Preference +2. Now create or modify a String Value (REG\_SZ) called On and set its value to 1 + +Information is comming from: +","It turns out you CAN programatically change the “underline keyboard shortcuts” option in your own application. You need to send the WM\_UPDATEUISTATE message to your main form according to the documentation found at: + +Since you mentioned Visual Basic, here's how to do it: + +``` +Private Const WM_UPDATEUISTATE = &H128 +Private Const UIS_CLEAR = &H2 +Private Const UISF_HIDEACCEL = &H2 +Private Declare Function PostMessage Lib ""user32"" Alias ""PostMessageA"" (ByVal hWnd As +Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long + +``` + +Then in the ""Form\_Load"" event send the message and it will activate keyboard shortcuts underlining for all controls and menus present on that form: + +``` +Private Sub Form_Load() + PostMessage Me.hWnd, WM_UPDATEUISTATE, UIS_CLEAR + UISF_HIDEACCEL * 65536, 0 +End Sub + +```" +11500,"The problem I'm trying to solve here is very simple but the available data is very limited. That makes it a hard problem to solve. + +The available data are as follows: + +1. I have 100 patients and I need to rank order them in terms of how healthy they are. +2. I only have 5 measurements for each patient. Each of the five readings is coded as a numeric value, and the rule is that the bigger the reading the healthier is the patient. + +Should I have some sort of doctor's ""expert judgement based ranking"" I could use that as the target variable and fit some sort of an ordinal logistic regression model trying to predict doctor's assessment. However, I don't have that. The only thing I have is (1) and (2). + +How would you come up with a simple ""scoring"" algorithm which would combine those five measurements into a single score which would be good enough (not perfect) in rank ordering patients?",2011/06/02,"['https://stats.stackexchange.com/questions/11500', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/333/']","A simple approach would be to calculate the sum score or the mean. Another approach would not assume that all variables are of equal importance and we could calculate a weighted mean. + +Let's assume we have the following 10 patients and variables `v1` to `v5`. + +``` +> set.seed(1) +> df <- data.frame(v1 = sample(1:5, 10, replace = TRUE), ++ v2 = sample(1:5, 10, replace = TRUE), ++ v3 = sample(1:5, 10, replace = TRUE), ++ v4 = sample(1:5, 10, replace = TRUE), ++ v5 = sample(1:5, 10, replace = TRUE)) +> +> df + v1 v2 v3 v4 v5 +1 2 2 5 3 5 +2 2 1 2 3 4 +3 3 4 4 3 4 +4 5 2 1 1 3 +5 2 4 2 5 3 +6 5 3 2 4 4 +7 5 4 1 4 1 +8 4 5 2 1 3 +9 4 2 5 4 4 +10 1 4 2 3 4 + +``` + +*1. Sum score and ranks* + +``` +> df$sum <- rowSums(df) +> df$ranks <- abs(rank(df$sum) - (dim(df)[1] + 1)) +> df + v1 v2 v3 v4 v5 sum ranks +1 2 2 5 3 5 17 4.0 +2 2 1 2 3 4 12 9.5 +3 3 4 4 3 4 18 2.5 +4 5 2 1 1 3 12 9.5 +5 2 4 2 5 3 16 5.0 +6 5 3 2 4 4 18 2.5 +7 5 4 1 4 1 15 6.5 +8 4 5 2 1 3 15 6.5 +9 4 2 5 4 4 19 1.0 +10 1 4 2 3 4 14 8.0 + +``` + +*2. Mean score and ranks (note: `ranks` and `ranks2` are equal)* + +``` +> df$means <- apply(df[, 1:5], 1, mean) +> df$ranks2 <- abs(rank(df$mean) - (dim(df)[1] + 1)) +> df + v1 v2 v3 v4 v5 sum ranks means ranks2 +1 2 2 5 3 5 17 4.0 3.4 4.0 +2 2 1 2 3 4 12 9.5 2.4 9.5 +3 3 4 4 3 4 18 2.5 3.6 2.5 +4 5 2 1 1 3 12 9.5 2.4 9.5 +5 2 4 2 5 3 16 5.0 3.2 5.0 +6 5 3 2 4 4 18 2.5 3.6 2.5 +7 5 4 1 4 1 15 6.5 3.0 6.5 +8 4 5 2 1 3 15 6.5 3.0 6.5 +9 4 2 5 4 4 19 1.0 3.8 1.0 +10 1 4 2 3 4 14 8.0 2.8 8.0 + +``` + +*3. Weighted mean score (i.e. I assume that V3 and V4 are more important than v1, v2 or v5)* + +``` +> weights <- c(0.5, 0.5, 1, 1, 0.5) +> wmean <- function(x, w = weights){weighted.mean(x, w = w)} +> df$wmeans <- sapply(split(df[, 1:5], 1:10), wmean) +> df$ranks3 <- abs(rank(df$wmeans) - (dim(df)[1] + 1)) +> df + v1 v2 v3 v4 v5 sum ranks means ranks2 wmeans ranks3 +1 2 2 5 3 5 17 4.0 3.4 4.0 3.571429 2.5 +2 2 1 2 3 4 12 9.5 2.4 9.5 2.428571 9.0 +3 3 4 4 3 4 18 2.5 3.6 2.5 3.571429 2.5 +4 5 2 1 1 3 12 9.5 2.4 9.5 2.000000 10.0 +5 2 4 2 5 3 16 5.0 3.2 5.0 3.285714 5.0 +6 5 3 2 4 4 18 2.5 3.6 2.5 3.428571 4.0 +7 5 4 1 4 1 15 6.5 3.0 6.5 2.857143 6.0 +8 4 5 2 1 3 15 6.5 3.0 6.5 2.571429 8.0 +9 4 2 5 4 4 19 1.0 3.8 1.0 4.000000 1.0 +10 1 4 2 3 4 14 8.0 2.8 8.0 2.714286 7.0 + +```","I would just simply sum them up, weighting each factor if necessary." +11500,"The problem I'm trying to solve here is very simple but the available data is very limited. That makes it a hard problem to solve. + +The available data are as follows: + +1. I have 100 patients and I need to rank order them in terms of how healthy they are. +2. I only have 5 measurements for each patient. Each of the five readings is coded as a numeric value, and the rule is that the bigger the reading the healthier is the patient. + +Should I have some sort of doctor's ""expert judgement based ranking"" I could use that as the target variable and fit some sort of an ordinal logistic regression model trying to predict doctor's assessment. However, I don't have that. The only thing I have is (1) and (2). + +How would you come up with a simple ""scoring"" algorithm which would combine those five measurements into a single score which would be good enough (not perfect) in rank ordering patients?",2011/06/02,"['https://stats.stackexchange.com/questions/11500', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/333/']","*Any* function $f: \mathbb{R}^5 \to \mathbb{R}$ that is separately increasing in each of its arguments will work. For example, you can select positive parameters $\alpha\_i$ and any real parameters $\lambda\_i$ and rank the data $(x\_1, x\_2, x\_3, x\_4, x\_5)$ according to the values of + +$$\sum\_{i=1}^{5} \alpha\_i (x\_i^{\lambda\_i} - 1) / \lambda\_i \text{.}$$ + +Evidently some criterion is needed to select among such a rich set of distinctly different scores. In particular, the simple obvious solutions (frequently employed, unfortunately) of just summing the scores or first ""normalizing"" them in some fashion and then summing them will suffer from this lack of grounding in reality. To put it another way: *any* answer that does not derive its support from additional information is a pure fabrication. + +Because this problem is essentially the same as [Creating an index of quality from multiple variables to enable rank ordering](https://stats.stackexchange.com/questions/9358/creating-an-index-of-quality-from-multiple-variables-to-enable-rank-ordering), I refer you to the discussion there for more information.","I would just simply sum them up, weighting each factor if necessary." +11500,"The problem I'm trying to solve here is very simple but the available data is very limited. That makes it a hard problem to solve. + +The available data are as follows: + +1. I have 100 patients and I need to rank order them in terms of how healthy they are. +2. I only have 5 measurements for each patient. Each of the five readings is coded as a numeric value, and the rule is that the bigger the reading the healthier is the patient. + +Should I have some sort of doctor's ""expert judgement based ranking"" I could use that as the target variable and fit some sort of an ordinal logistic regression model trying to predict doctor's assessment. However, I don't have that. The only thing I have is (1) and (2). + +How would you come up with a simple ""scoring"" algorithm which would combine those five measurements into a single score which would be good enough (not perfect) in rank ordering patients?",2011/06/02,"['https://stats.stackexchange.com/questions/11500', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/333/']","I would just simply sum them up, weighting each factor if necessary.","How about generating a synthetic binary target variable first and then running a logistic regression model? + +The synthetic variable should be something like... ""If the observation is in the top decile on all of the input variable distributions flag it as 1 else 0"" + +Having generated the binary target variable... Run logistic regression to come up with probabilistic metric 0 to 1 assesing how far/close in the tails of multiple distributions observation is?" +11500,"The problem I'm trying to solve here is very simple but the available data is very limited. That makes it a hard problem to solve. + +The available data are as follows: + +1. I have 100 patients and I need to rank order them in terms of how healthy they are. +2. I only have 5 measurements for each patient. Each of the five readings is coded as a numeric value, and the rule is that the bigger the reading the healthier is the patient. + +Should I have some sort of doctor's ""expert judgement based ranking"" I could use that as the target variable and fit some sort of an ordinal logistic regression model trying to predict doctor's assessment. However, I don't have that. The only thing I have is (1) and (2). + +How would you come up with a simple ""scoring"" algorithm which would combine those five measurements into a single score which would be good enough (not perfect) in rank ordering patients?",2011/06/02,"['https://stats.stackexchange.com/questions/11500', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/333/']","A simple approach would be to calculate the sum score or the mean. Another approach would not assume that all variables are of equal importance and we could calculate a weighted mean. + +Let's assume we have the following 10 patients and variables `v1` to `v5`. + +``` +> set.seed(1) +> df <- data.frame(v1 = sample(1:5, 10, replace = TRUE), ++ v2 = sample(1:5, 10, replace = TRUE), ++ v3 = sample(1:5, 10, replace = TRUE), ++ v4 = sample(1:5, 10, replace = TRUE), ++ v5 = sample(1:5, 10, replace = TRUE)) +> +> df + v1 v2 v3 v4 v5 +1 2 2 5 3 5 +2 2 1 2 3 4 +3 3 4 4 3 4 +4 5 2 1 1 3 +5 2 4 2 5 3 +6 5 3 2 4 4 +7 5 4 1 4 1 +8 4 5 2 1 3 +9 4 2 5 4 4 +10 1 4 2 3 4 + +``` + +*1. Sum score and ranks* + +``` +> df$sum <- rowSums(df) +> df$ranks <- abs(rank(df$sum) - (dim(df)[1] + 1)) +> df + v1 v2 v3 v4 v5 sum ranks +1 2 2 5 3 5 17 4.0 +2 2 1 2 3 4 12 9.5 +3 3 4 4 3 4 18 2.5 +4 5 2 1 1 3 12 9.5 +5 2 4 2 5 3 16 5.0 +6 5 3 2 4 4 18 2.5 +7 5 4 1 4 1 15 6.5 +8 4 5 2 1 3 15 6.5 +9 4 2 5 4 4 19 1.0 +10 1 4 2 3 4 14 8.0 + +``` + +*2. Mean score and ranks (note: `ranks` and `ranks2` are equal)* + +``` +> df$means <- apply(df[, 1:5], 1, mean) +> df$ranks2 <- abs(rank(df$mean) - (dim(df)[1] + 1)) +> df + v1 v2 v3 v4 v5 sum ranks means ranks2 +1 2 2 5 3 5 17 4.0 3.4 4.0 +2 2 1 2 3 4 12 9.5 2.4 9.5 +3 3 4 4 3 4 18 2.5 3.6 2.5 +4 5 2 1 1 3 12 9.5 2.4 9.5 +5 2 4 2 5 3 16 5.0 3.2 5.0 +6 5 3 2 4 4 18 2.5 3.6 2.5 +7 5 4 1 4 1 15 6.5 3.0 6.5 +8 4 5 2 1 3 15 6.5 3.0 6.5 +9 4 2 5 4 4 19 1.0 3.8 1.0 +10 1 4 2 3 4 14 8.0 2.8 8.0 + +``` + +*3. Weighted mean score (i.e. I assume that V3 and V4 are more important than v1, v2 or v5)* + +``` +> weights <- c(0.5, 0.5, 1, 1, 0.5) +> wmean <- function(x, w = weights){weighted.mean(x, w = w)} +> df$wmeans <- sapply(split(df[, 1:5], 1:10), wmean) +> df$ranks3 <- abs(rank(df$wmeans) - (dim(df)[1] + 1)) +> df + v1 v2 v3 v4 v5 sum ranks means ranks2 wmeans ranks3 +1 2 2 5 3 5 17 4.0 3.4 4.0 3.571429 2.5 +2 2 1 2 3 4 12 9.5 2.4 9.5 2.428571 9.0 +3 3 4 4 3 4 18 2.5 3.6 2.5 3.571429 2.5 +4 5 2 1 1 3 12 9.5 2.4 9.5 2.000000 10.0 +5 2 4 2 5 3 16 5.0 3.2 5.0 3.285714 5.0 +6 5 3 2 4 4 18 2.5 3.6 2.5 3.428571 4.0 +7 5 4 1 4 1 15 6.5 3.0 6.5 2.857143 6.0 +8 4 5 2 1 3 15 6.5 3.0 6.5 2.571429 8.0 +9 4 2 5 4 4 19 1.0 3.8 1.0 4.000000 1.0 +10 1 4 2 3 4 14 8.0 2.8 8.0 2.714286 7.0 + +```","How about generating a synthetic binary target variable first and then running a logistic regression model? + +The synthetic variable should be something like... ""If the observation is in the top decile on all of the input variable distributions flag it as 1 else 0"" + +Having generated the binary target variable... Run logistic regression to come up with probabilistic metric 0 to 1 assesing how far/close in the tails of multiple distributions observation is?" +11500,"The problem I'm trying to solve here is very simple but the available data is very limited. That makes it a hard problem to solve. + +The available data are as follows: + +1. I have 100 patients and I need to rank order them in terms of how healthy they are. +2. I only have 5 measurements for each patient. Each of the five readings is coded as a numeric value, and the rule is that the bigger the reading the healthier is the patient. + +Should I have some sort of doctor's ""expert judgement based ranking"" I could use that as the target variable and fit some sort of an ordinal logistic regression model trying to predict doctor's assessment. However, I don't have that. The only thing I have is (1) and (2). + +How would you come up with a simple ""scoring"" algorithm which would combine those five measurements into a single score which would be good enough (not perfect) in rank ordering patients?",2011/06/02,"['https://stats.stackexchange.com/questions/11500', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/333/']","*Any* function $f: \mathbb{R}^5 \to \mathbb{R}$ that is separately increasing in each of its arguments will work. For example, you can select positive parameters $\alpha\_i$ and any real parameters $\lambda\_i$ and rank the data $(x\_1, x\_2, x\_3, x\_4, x\_5)$ according to the values of + +$$\sum\_{i=1}^{5} \alpha\_i (x\_i^{\lambda\_i} - 1) / \lambda\_i \text{.}$$ + +Evidently some criterion is needed to select among such a rich set of distinctly different scores. In particular, the simple obvious solutions (frequently employed, unfortunately) of just summing the scores or first ""normalizing"" them in some fashion and then summing them will suffer from this lack of grounding in reality. To put it another way: *any* answer that does not derive its support from additional information is a pure fabrication. + +Because this problem is essentially the same as [Creating an index of quality from multiple variables to enable rank ordering](https://stats.stackexchange.com/questions/9358/creating-an-index-of-quality-from-multiple-variables-to-enable-rank-ordering), I refer you to the discussion there for more information.","How about generating a synthetic binary target variable first and then running a logistic regression model? + +The synthetic variable should be something like... ""If the observation is in the top decile on all of the input variable distributions flag it as 1 else 0"" + +Having generated the binary target variable... Run logistic regression to come up with probabilistic metric 0 to 1 assesing how far/close in the tails of multiple distributions observation is?" +499446,"My algorithm textbook has a theorem that says + +'For every $r > 1$ and every $d > 0$, we have $n^d = O(r^n)$.' + +However, it does not provide proof. + +Of course I know exponential grows faster than polynomial in most cases, but is it true for all case? + +What if the polynomial function is something like $n^{100^{100}}$ and exponential is $2^n$? Will the latter outgrow the former at some point?",2013/09/20,"['https://math.stackexchange.com/questions/499446', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/95794/']","Yes, it is true for all cases. This can be seen by noting that + +$$\lim\_{n\to\infty} \frac{n^k}{e^n} = 0$$ + +for any $k$. This can be seen by an application of L'Hospital's rule a number of times, or by using induction as [here](https://math.stackexchange.com/questions/55468/how-to-prove-that-exponential-grows-faster-than-polynomial).",Hint: Yes. See Taylor expansion of exponential function. +499446,"My algorithm textbook has a theorem that says + +'For every $r > 1$ and every $d > 0$, we have $n^d = O(r^n)$.' + +However, it does not provide proof. + +Of course I know exponential grows faster than polynomial in most cases, but is it true for all case? + +What if the polynomial function is something like $n^{100^{100}}$ and exponential is $2^n$? Will the latter outgrow the former at some point?",2013/09/20,"['https://math.stackexchange.com/questions/499446', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/95794/']","Yes, it is true for all cases. This can be seen by noting that + +$$\lim\_{n\to\infty} \frac{n^k}{e^n} = 0$$ + +for any $k$. This can be seen by an application of L'Hospital's rule a number of times, or by using induction as [here](https://math.stackexchange.com/questions/55468/how-to-prove-that-exponential-grows-faster-than-polynomial).","Let $n = k^2$. + +Then $n^c = k^{2c}$ and $2^n = (2^k)^k$. + +Clearly $2^k \ge k+1 > k$ so all we need is $k > 2c$. + +In general if we want to find $n \in \mathbb{N}$ such that $r^n > n^c$ where $r > 1$, we can do essentially the same: + +Let $n = ak^2$ where $a > \log\_r(2)$. + +Then $r^n > (2^k)^k$ and $n^c = a^c k^{2c}$. + +It is then enough to choose $k$ such that $k > a$ and $k > 3c$, so that $n^c < k^{3c} < (2^k)^k < 2^n$." +499446,"My algorithm textbook has a theorem that says + +'For every $r > 1$ and every $d > 0$, we have $n^d = O(r^n)$.' + +However, it does not provide proof. + +Of course I know exponential grows faster than polynomial in most cases, but is it true for all case? + +What if the polynomial function is something like $n^{100^{100}}$ and exponential is $2^n$? Will the latter outgrow the former at some point?",2013/09/20,"['https://math.stackexchange.com/questions/499446', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/95794/']","Let $n = k^2$. + +Then $n^c = k^{2c}$ and $2^n = (2^k)^k$. + +Clearly $2^k \ge k+1 > k$ so all we need is $k > 2c$. + +In general if we want to find $n \in \mathbb{N}$ such that $r^n > n^c$ where $r > 1$, we can do essentially the same: + +Let $n = ak^2$ where $a > \log\_r(2)$. + +Then $r^n > (2^k)^k$ and $n^c = a^c k^{2c}$. + +It is then enough to choose $k$ such that $k > a$ and $k > 3c$, so that $n^c < k^{3c} < (2^k)^k < 2^n$.",Hint: Yes. See Taylor expansion of exponential function. +17809234,"I'm new to Java, in fact I know next to nothing. I've been interested in the type of data an android app is holding on me. So, I can see within an XML file this app has created strings which appear to to be encrypted using AES128-CBC. + +So I've decompiled their .apk file and looking through their source I can see a method they call to decode stuff (DecodeMe). Can I pass my encrypted strings through this using their method and it will decrypt it? + +Sorry, I'm not too clued up on this.",2013/07/23,"['https://Stackoverflow.com/questions/17809234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2359639/']","I have no experience with Android development at all, I can only comment from the Java side of things. + +If you have been able to decompile the program, you should be able to use the code as you like - so, assuming that DecodeMe really does what it's name implies, then yes it should decode the text. + +Add the decompiled code to a new project in your favourite Java IDE, create your own main(...) class/method and try calling the DecodeMe - it *shouldn't* take too much effort to set up and test. + +EDIT: Yes, you can use a decompiled method - you simply need to make sure all methods/classes it uses are also available.","That is a java method you just mined from the APK. + +> +> private void doNothing() {} +> +> +> + +Whoa, this is another. You can use it. +Sorry, just some fun. :) +Yes, you can actually use it, but check if it uses some class that is also defined in the application. You have to mine all custom classes, too." +57582787,"I would like to deploy my react app onto my personal website. I currently have it deployed onto to heroku and have that linked on my personal site. But I would like to eliminate heroku from the equation and have everything on my own site. Whenever I try to deploy it, I upload the build files into my file manager public\_html. But when I try to open it, all I get is a blank page. +I have my vanilla JS projects up just fine. + +My question is how do I deploy my react app, through cpanel, onto my existing site. + +I've read through some stack pages already and tried npm run build and posting the zip files as well as the normal files to my cpanel file manager. But it only gives me a blank page. +When I open up dev tools for the blank page I can see that it is the html file I want but and it has the links to my build files but it's just not running them for some reason. The console is giving me an error ""Failed to load resource: the server responded with a status of 404 ()"" +I've tried changing the homepage destination as well. + +I believe I'm just missing something really simple because I'm having a hard time finding any help on this one. I'm relatively new to react and deploying react apps so if someone could help me I would be very grateful. + +I don't know if I am uploading the files to my file manager in cpanel wrong or if I'm doing something wrong with npm run build. + +My git repo is here + + +Thank you.",2019/08/20,"['https://Stackoverflow.com/questions/57582787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11954181/']","To deploy your react app into your web site just follow these steps : + +1. Build your react app using : **npm run build** +2. Go to the app folder then to the build subfolder and you need to upload all contents to your server into the public\_html folder + +I have tested these steps using create-react-app this is the ordinary way to do it, if it doesn’t work then try to check the error from the browser console","It appears you need to change the `homepage` parameter in your configuration file and change few settings with your `router` + +See this as I think it can help " +71229648,"I have been using Keras/TF's [`CSVLogger`](https://keras.io/api/callbacks/csv_logger/) in order to save the training and validation accuracies. Then I was plotting those data to check the trajectory of training and validation accuracy or loss. + +Yesterday, I read [this link](https://www.tutorialspoint.com/deep_learning_with_keras/deep_learning_with_keras_evaluating_model_performance.htm). + +Here, they used `model.evaluate()` to plot the accuracy metric. + +What is the difference between these two approaches?",2022/02/22,"['https://Stackoverflow.com/questions/71229648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/159072/']","Here are the big key differences between the two: + +model.evaluate() gives a different loss on training data from the one in the training process, while CSVLogger tracks metrics on the validation set after every epoch in the process.","Log and plot the results +------------------------ + +* The `CSVLogger` will save the results **of the training** in a **CSV file**. +* The output of `fit`, normally called `history`, will have the same results ready in a variable, without needing a CSV file. + +Their data should be exactly the same. + +Evaluate +-------- + +The `evaluate` method is **not a log**. It's a method that you call **any time you want**, and will output a **single value** for each loss and metric you have in `compile` for the ""current"" model. + +This is not registered anywhere during training, and this should usually **not be called during training**, unless you create a custom training loop and manually call `evaluate` inside this loop every epoch (this is unnecessary and inconvenient for standard use). + +You can use `evaluate` with **any data you want**, including data that was neither in training nor validation data. + +The link you shared +------------------- + +Notice that what they plot is `history`, and `history` is the output of `fit`. It has nothing to do with `evaluate`. + +``` +plot.plot(history.history['acc']) +plot.plot(history.history['val_acc']) + +``` + +See in the previous page of the link: + +``` +history = model.fit(...) + +``` + +The link doesn't show exactly ""where"" they call evaluate, and they're probably doing it ""only once after training"", just to see the final results of the model (not a log of the training)" +23314041,"Actionscript to use Math.random what will this mean Right = 6 + Math.random() \* 2; + +I know Math.random is between 0-0.99... but will it come out (6 - 7)?",2014/04/26,"['https://Stackoverflow.com/questions/23314041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3281613/']","`Math.random()` returns a number greater or equal to 0 and less than 1.0, i.e. + +`0 <= Math.random() < 1.0` + +If we multiply this with `b` then we get a number greater or equal to 0 and less than b, i.e. + +`(0 * b) <= (Math.random() * b) < (1.0 * b)` + +or `0 <= (Math.random() * b) < b` + +If we add `a` with this then we get a number greater or equal to `a` and less than `a + b`, i.e. + +`(a + 0) <= (a + Math.random() * b) < (a + b)` + +or `a <= (a + Math.random() * b) < (a + b)` + +So, `6 + Math.random() * 2` returns a number greater or equal to 6 and less than 8. If you assign this to an integer then it will be either 6 or 7.","I prefer to write a function to set the scale and range for you. Like this: + +``` +public static function getRandomNumber(low:Number=0, high:Number=1):Number +{ + return Math.floor(Math.random() * (1+high-low)) + low; +} + +``` + +Now you can call it: + +``` +getRandomNumber(6, 7); //returns 6-7 inclusive + +```" +7589603,"I want to use a view script to render my zend form as it seems to be the best way to +control the layout/design of the form while still using the Zend\_Elements classes. + +From the view script, I render the element with `$this->element->getElement('elementName')` . + +I'm having problems with the names of the elements. This is actually a sub-form inside a sub-form inside a form. + +When I used the FormElements decorators , the fully qualified name of the elements was form[subForm][subForm][element] , which was good. +Wehn I moved to the viewScript decorators, it changed to subForm[subForm][element]. + +I understood that I need to use the PrepareElements decorator to fix this, but this caused the name to change form[subForm][form][subForm][subForm][elements] (it doubled the first two names in the start). + +Any ideas how I should handle this? + +Thanks. + +**UPDATE:** I tried to debug PrepareElements and I really don't understand what is doing. +It seems like it works ok in the first iteration, but then it adds again the form[subform] prefix when running on one of the middle subforms. + +When I'm not using the PrepareElements decorator, I'm just missing the ""form"" prefix in the names (i.e., instead of form[subForm][element], I get only subForm[element]). + +May be I can just fix this somehow? + +I tried to change the belongsTo but that only replaced the ""subForm"" prefix . + +It actually seems like what is missing is a belongsTo method on the subForm. + +Again, this is all because of the ViewScript decorator. It works fine with the FormElements decorators. + +**UPDATE 2:** Just to clarify, I wouldn't mind this name change, but it causes my fields to not populate when I call form->populate . + +**Edit:** I think that I've narrowed the problem to this: when I get my values back in setDefaults, they are ordered like this: + +``` +array( +\""formElements1-name\"" => value1... \""subFormName\"" => array( +\""parentFormName\"" => array( +\""subFormName\"" => subForm-values-array +) +) + +``` + +... +The main problem here is the `""parentFormName"" => ""subFormNAme""..` what does it repeat itself? I'm already in the main form. I'm guessing this is caused because I've set the `setElementsBelongTo(formName[subFormName])` , but if I wouldn't do that, then I would get my subform values completely separate from the form, + +i.e. + values array = array( + \""formName\"" => array( + formValues + ), \""subFormNAme\"" => array( + subFormValues + ) + +, while I exepct it to be + +``` +array( +formName => array( +subFormNAme => values-array +) +)... + +``` + +Is it even possible to make this work?",2011/09/28,"['https://Stackoverflow.com/questions/7589603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445114/']","Are you just trying to output your form using `form; ?>` from your view script? + +That works well for simple forms, but for my more complex forms I tend to render each element individually but don't need to use ViewScript decorator on each individual element to do this. Just try something like this from your view script: + +``` +
            +
            + Some Form Name + escape($this->form->getAction()) ?>"" + method=""escape($this->form->getMethod()) ?>"" + enctype=""multipart/form-data""> + + form->id; // render the id element here ?> + +
            + form->name; // render the user name field here ?> +
            +
            + form->description; // render the description element here ?> +
            +
            + +
            + form->address1; // render the address ?> +
            +
            + form->address2; // render address2 ?> +
            +
            + +
            + form->zip; // render zip code ?> +
            +
            + form->city; // render city ?> +
            +
            + form->state; // render state ?> +
            +
            + +
            + form->country; // render country ?> +
            +
            + + form->submit; ?> + + +
            +
            + +``` + +That is how I do most of my forms because I want to have some elements take up half the width and others the full width. + +Surprisingly, the reference guide doesn't tell you that you can do this. I seem to remember a page about it in the past but cannot find it now. When I got started with Zend Framework, I thought the only way I could get my form to output exactly how I wanted was to create complex decorators, but that is not the case. + +Matthew Weier O'Phinney has a great blog post on [rendering Zend\_Form decorators individually](http://weierophinney.net/matthew/archives/215-Rendering-Zend_Form-decorators-individually.html) which explains what I did above. I hope they add this to the first page of Zend Form because that was discouraging to me at first. The fact is, 90% of my forms render elements individually instead of just echo'ing the form itself. + +Note: To stop ZF from enclosing my form elements in the dt and dd tags, I apply this decorator to all of my standard form elements. I have a base form class that I extend all of my forms from so I don't have to repeat this everywhere. This is the decorator for the element so I can use tags to enclose my elements. + +``` +public $elementDecorators = array( + 'ViewHelper', + 'Errors', + array('Description', array('tag' => 'p', 'class' => 'description')), + array('HtmlTag', array('tag' => 'div', 'class' => 'form-div')), + array('Label', array('class' => 'form-label', 'requiredSuffix' => '*')) +); + +``` + +For my submit buttons I use + +``` +public $buttonDecorators = array( + 'ViewHelper', + array('HtmlTag', array('tag' => 'div', 'class' => 'form-button')) +); + +```","The solution would be to use the `belongsTo()` form element property. + +Example : + +``` +new Zend_Form_Element_Text('', array('belongsTo' => '')) + +``` + +In this way, the render() method will use a form element name like + +``` +name=""[]"" + +```" +7589603,"I want to use a view script to render my zend form as it seems to be the best way to +control the layout/design of the form while still using the Zend\_Elements classes. + +From the view script, I render the element with `$this->element->getElement('elementName')` . + +I'm having problems with the names of the elements. This is actually a sub-form inside a sub-form inside a form. + +When I used the FormElements decorators , the fully qualified name of the elements was form[subForm][subForm][element] , which was good. +Wehn I moved to the viewScript decorators, it changed to subForm[subForm][element]. + +I understood that I need to use the PrepareElements decorator to fix this, but this caused the name to change form[subForm][form][subForm][subForm][elements] (it doubled the first two names in the start). + +Any ideas how I should handle this? + +Thanks. + +**UPDATE:** I tried to debug PrepareElements and I really don't understand what is doing. +It seems like it works ok in the first iteration, but then it adds again the form[subform] prefix when running on one of the middle subforms. + +When I'm not using the PrepareElements decorator, I'm just missing the ""form"" prefix in the names (i.e., instead of form[subForm][element], I get only subForm[element]). + +May be I can just fix this somehow? + +I tried to change the belongsTo but that only replaced the ""subForm"" prefix . + +It actually seems like what is missing is a belongsTo method on the subForm. + +Again, this is all because of the ViewScript decorator. It works fine with the FormElements decorators. + +**UPDATE 2:** Just to clarify, I wouldn't mind this name change, but it causes my fields to not populate when I call form->populate . + +**Edit:** I think that I've narrowed the problem to this: when I get my values back in setDefaults, they are ordered like this: + +``` +array( +\""formElements1-name\"" => value1... \""subFormName\"" => array( +\""parentFormName\"" => array( +\""subFormName\"" => subForm-values-array +) +) + +``` + +... +The main problem here is the `""parentFormName"" => ""subFormNAme""..` what does it repeat itself? I'm already in the main form. I'm guessing this is caused because I've set the `setElementsBelongTo(formName[subFormName])` , but if I wouldn't do that, then I would get my subform values completely separate from the form, + +i.e. + values array = array( + \""formName\"" => array( + formValues + ), \""subFormNAme\"" => array( + subFormValues + ) + +, while I exepct it to be + +``` +array( +formName => array( +subFormNAme => values-array +) +)... + +``` + +Is it even possible to make this work?",2011/09/28,"['https://Stackoverflow.com/questions/7589603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445114/']","Are you just trying to output your form using `form; ?>` from your view script? + +That works well for simple forms, but for my more complex forms I tend to render each element individually but don't need to use ViewScript decorator on each individual element to do this. Just try something like this from your view script: + +``` +
            +
            + Some Form Name +
            escape($this->form->getAction()) ?>"" + method=""escape($this->form->getMethod()) ?>"" + enctype=""multipart/form-data""> + + form->id; // render the id element here ?> + +
            + form->name; // render the user name field here ?> +
            +
            + form->description; // render the description element here ?> +
            +
            + +
            + form->address1; // render the address ?> +
            +
            + form->address2; // render address2 ?> +
            +
            + +
            + form->zip; // render zip code ?> +
            +
            + form->city; // render city ?> +
            +
            + form->state; // render state ?> +
            +
            + +
            + form->country; // render country ?> +
            +
            + + form->submit; ?> + +
            +
            +
            + +``` + +That is how I do most of my forms because I want to have some elements take up half the width and others the full width. + +Surprisingly, the reference guide doesn't tell you that you can do this. I seem to remember a page about it in the past but cannot find it now. When I got started with Zend Framework, I thought the only way I could get my form to output exactly how I wanted was to create complex decorators, but that is not the case. + +Matthew Weier O'Phinney has a great blog post on [rendering Zend\_Form decorators individually](http://weierophinney.net/matthew/archives/215-Rendering-Zend_Form-decorators-individually.html) which explains what I did above. I hope they add this to the first page of Zend Form because that was discouraging to me at first. The fact is, 90% of my forms render elements individually instead of just echo'ing the form itself. + +Note: To stop ZF from enclosing my form elements in the dt and dd tags, I apply this decorator to all of my standard form elements. I have a base form class that I extend all of my forms from so I don't have to repeat this everywhere. This is the decorator for the element so I can use tags to enclose my elements. + +``` +public $elementDecorators = array( + 'ViewHelper', + 'Errors', + array('Description', array('tag' => 'p', 'class' => 'description')), + array('HtmlTag', array('tag' => 'div', 'class' => 'form-div')), + array('Label', array('class' => 'form-label', 'requiredSuffix' => '*')) +); + +``` + +For my submit buttons I use + +``` +public $buttonDecorators = array( + 'ViewHelper', + array('HtmlTag', array('tag' => 'div', 'class' => 'form-button')) +); + +```","I had the same problem and i solved it with a decorator + +1 : Create a generic subform with elements + +2 : Using a specific decorator with PrepareElements + +3 : Change form to an array with setIsArray(true) + +Example : + +Form + +``` +$i = 4; +for($i = 0; $i < $nbReclam ; $i++) +{ + $rowForm = new Zend_Form_SubForm($i); + $name= new Zend_Form_Element_Textarea('name'); + $rowForm->addElement($name); + $this->addSubForm($rowForm, $i); +} + +$this->setDecorators(array( + 'PrepareElements', + array('ViewScript', array('viewScript' => 'myDecorator.phtml')), + )); + +$this->setIsArray(true); + +``` + +Decorator + +``` + + + + + + + + + element->getSubForms() as $subForm) : ?> + + + getElements() as $row) : ?> + + + + + +
            Name
            + +``` + +Enjoy + +Sorry for my english, i am french" +7589603,"I want to use a view script to render my zend form as it seems to be the best way to +control the layout/design of the form while still using the Zend\_Elements classes. + +From the view script, I render the element with `$this->element->getElement('elementName')` . + +I'm having problems with the names of the elements. This is actually a sub-form inside a sub-form inside a form. + +When I used the FormElements decorators , the fully qualified name of the elements was form[subForm][subForm][element] , which was good. +Wehn I moved to the viewScript decorators, it changed to subForm[subForm][element]. + +I understood that I need to use the PrepareElements decorator to fix this, but this caused the name to change form[subForm][form][subForm][subForm][elements] (it doubled the first two names in the start). + +Any ideas how I should handle this? + +Thanks. + +**UPDATE:** I tried to debug PrepareElements and I really don't understand what is doing. +It seems like it works ok in the first iteration, but then it adds again the form[subform] prefix when running on one of the middle subforms. + +When I'm not using the PrepareElements decorator, I'm just missing the ""form"" prefix in the names (i.e., instead of form[subForm][element], I get only subForm[element]). + +May be I can just fix this somehow? + +I tried to change the belongsTo but that only replaced the ""subForm"" prefix . + +It actually seems like what is missing is a belongsTo method on the subForm. + +Again, this is all because of the ViewScript decorator. It works fine with the FormElements decorators. + +**UPDATE 2:** Just to clarify, I wouldn't mind this name change, but it causes my fields to not populate when I call form->populate . + +**Edit:** I think that I've narrowed the problem to this: when I get my values back in setDefaults, they are ordered like this: + +``` +array( +\""formElements1-name\"" => value1... \""subFormName\"" => array( +\""parentFormName\"" => array( +\""subFormName\"" => subForm-values-array +) +) + +``` + +... +The main problem here is the `""parentFormName"" => ""subFormNAme""..` what does it repeat itself? I'm already in the main form. I'm guessing this is caused because I've set the `setElementsBelongTo(formName[subFormName])` , but if I wouldn't do that, then I would get my subform values completely separate from the form, + +i.e. + values array = array( + \""formName\"" => array( + formValues + ), \""subFormNAme\"" => array( + subFormValues + ) + +, while I exepct it to be + +``` +array( +formName => array( +subFormNAme => values-array +) +)... + +``` + +Is it even possible to make this work?",2011/09/28,"['https://Stackoverflow.com/questions/7589603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445114/']","The current solution is to use the PrepareElements decorator on the subforms with one change - remove the recursive call in the PrepareElements code. Also, no ""setElementsBelongTo"" is required. + +This seem to generate the correct names and ids.","The solution would be to use the `belongsTo()` form element property. + +Example : + +``` +new Zend_Form_Element_Text('', array('belongsTo' => '')) + +``` + +In this way, the render() method will use a form element name like + +``` +name=""[]"" + +```" +7589603,"I want to use a view script to render my zend form as it seems to be the best way to +control the layout/design of the form while still using the Zend\_Elements classes. + +From the view script, I render the element with `$this->element->getElement('elementName')` . + +I'm having problems with the names of the elements. This is actually a sub-form inside a sub-form inside a form. + +When I used the FormElements decorators , the fully qualified name of the elements was form[subForm][subForm][element] , which was good. +Wehn I moved to the viewScript decorators, it changed to subForm[subForm][element]. + +I understood that I need to use the PrepareElements decorator to fix this, but this caused the name to change form[subForm][form][subForm][subForm][elements] (it doubled the first two names in the start). + +Any ideas how I should handle this? + +Thanks. + +**UPDATE:** I tried to debug PrepareElements and I really don't understand what is doing. +It seems like it works ok in the first iteration, but then it adds again the form[subform] prefix when running on one of the middle subforms. + +When I'm not using the PrepareElements decorator, I'm just missing the ""form"" prefix in the names (i.e., instead of form[subForm][element], I get only subForm[element]). + +May be I can just fix this somehow? + +I tried to change the belongsTo but that only replaced the ""subForm"" prefix . + +It actually seems like what is missing is a belongsTo method on the subForm. + +Again, this is all because of the ViewScript decorator. It works fine with the FormElements decorators. + +**UPDATE 2:** Just to clarify, I wouldn't mind this name change, but it causes my fields to not populate when I call form->populate . + +**Edit:** I think that I've narrowed the problem to this: when I get my values back in setDefaults, they are ordered like this: + +``` +array( +\""formElements1-name\"" => value1... \""subFormName\"" => array( +\""parentFormName\"" => array( +\""subFormName\"" => subForm-values-array +) +) + +``` + +... +The main problem here is the `""parentFormName"" => ""subFormNAme""..` what does it repeat itself? I'm already in the main form. I'm guessing this is caused because I've set the `setElementsBelongTo(formName[subFormName])` , but if I wouldn't do that, then I would get my subform values completely separate from the form, + +i.e. + values array = array( + \""formName\"" => array( + formValues + ), \""subFormNAme\"" => array( + subFormValues + ) + +, while I exepct it to be + +``` +array( +formName => array( +subFormNAme => values-array +) +)... + +``` + +Is it even possible to make this work?",2011/09/28,"['https://Stackoverflow.com/questions/7589603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445114/']","The current solution is to use the PrepareElements decorator on the subforms with one change - remove the recursive call in the PrepareElements code. Also, no ""setElementsBelongTo"" is required. + +This seem to generate the correct names and ids.","I had the same problem and i solved it with a decorator + +1 : Create a generic subform with elements + +2 : Using a specific decorator with PrepareElements + +3 : Change form to an array with setIsArray(true) + +Example : + +Form + +``` +$i = 4; +for($i = 0; $i < $nbReclam ; $i++) +{ + $rowForm = new Zend_Form_SubForm($i); + $name= new Zend_Form_Element_Textarea('name'); + $rowForm->addElement($name); + $this->addSubForm($rowForm, $i); +} + +$this->setDecorators(array( + 'PrepareElements', + array('ViewScript', array('viewScript' => 'myDecorator.phtml')), + )); + +$this->setIsArray(true); + +``` + +Decorator + +``` + + + + + + + + + element->getSubForms() as $subForm) : ?> + + + getElements() as $row) : ?> + + + + + +
            Name
            + +``` + +Enjoy + +Sorry for my english, i am french" +63575174,"Unable to set card footer as expected output + +**Expected output:** + +[![enter image description here.....](https://i.stack.imgur.com/Feadm.png)](https://i.stack.imgur.com/Feadm.png) + +**My Code:** + +```html + + +
            +
            + +
            +
            +
            +
            +
            + Africa +
            +

            + Kenya +

            +
            +
            + +
            +``` + +**jsfiddle:** ",2020/08/25,"['https://Stackoverflow.com/questions/63575174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7136100/']","```css +.card-footer:last-child { + border-radius: 0!important; +} + +.card-footer { + padding: 0!important; + background-color: unset!important; + border-top: unset!important; +} + +.text-center { + color: #fff; +} + +.card-img-overlay { + display: flex; + flex-direction: column; + justify-content: flex-end; + height: 100%; +} +``` + +```html + + +
            +
            + +
            +
            +
            +
            + Africa +
            +

            + Kenya +

            +
            +
            +
            + +
            +```","``` +
            +
            +
            + +
            +
            +
            +
            + Africa +
            +

            + Kenya +

            +
            +
            +
            +
            + +``` + +I think you need to add another div surrounding the card. This div needs to have the class `row`" +63575174,"Unable to set card footer as expected output + +**Expected output:** + +[![enter image description here.....](https://i.stack.imgur.com/Feadm.png)](https://i.stack.imgur.com/Feadm.png) + +**My Code:** + +```html + + +
            +
            + +
            +
            +
            +
            +
            + Africa +
            +

            + Kenya +

            +
            +
            + +
            +``` + +**jsfiddle:** ",2020/08/25,"['https://Stackoverflow.com/questions/63575174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7136100/']","```css +.card-footer:last-child { + border-radius: 0!important; +} + +.card-footer { + padding: 0!important; + background-color: unset!important; + border-top: unset!important; +} + +.text-center { + color: #fff; +} + +.card-img-overlay { + display: flex; + flex-direction: column; + justify-content: flex-end; + height: 100%; +} +``` + +```html + + +
            +
            + +
            +
            +
            +
            + Africa +
            +

            + Kenya +

            +
            +
            +
            + +
            +```","```css +.img-wrapper{ + position: relative; + text-align: center; + color: white; +} +.card-footer{ + position: absolute; + top: 60%; + left: 50%; + transform: translate(-50%, -50%); + } + h3, h1{ + color: #fff + } +``` + +```html +
            +
            +
            + +
            +
            +
            +
            +
            +
            +

            + Africa +

            +

            + Kenya +

            +
            +
            + +
            +```" +63575174,"Unable to set card footer as expected output + +**Expected output:** + +[![enter image description here.....](https://i.stack.imgur.com/Feadm.png)](https://i.stack.imgur.com/Feadm.png) + +**My Code:** + +```html + + +
            +
            + +
            +
            +
            +
            +
            + Africa +
            +

            + Kenya +

            +
            +
            + +
            +``` + +**jsfiddle:** ",2020/08/25,"['https://Stackoverflow.com/questions/63575174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7136100/']","Try this: + +```css +.card-footer:last-child { + border-radius: 0!important; +} + +.card-footer { + padding: 0!important; + background-color: unset!important; + border-top: unset!important; +} + +.text-center { + color: #fff; +} + +.card-img-overlay { + display: flex; + flex-direction: column; + justify-content: flex-end; + height: 100%; +} +``` + +```html + + +
            +
            + +
            +
            +
            +
            + AFRICA +
            +

            + Kenya +

            +
            +
            +
            + +
            +```","``` +
            +
            +
            + +
            +
            +
            +
            + Africa +
            +

            + Kenya +

            +
            +
            +
            +
            + +``` + +I think you need to add another div surrounding the card. This div needs to have the class `row`" +63575174,"Unable to set card footer as expected output + +**Expected output:** + +[![enter image description here.....](https://i.stack.imgur.com/Feadm.png)](https://i.stack.imgur.com/Feadm.png) + +**My Code:** + +```html + + +
            +
            + +
            +
            +
            +
            +
            + Africa +
            +

            + Kenya +

            +
            +
            + +
            +``` + +**jsfiddle:** ",2020/08/25,"['https://Stackoverflow.com/questions/63575174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7136100/']","Try this: + +```css +.card-footer:last-child { + border-radius: 0!important; +} + +.card-footer { + padding: 0!important; + background-color: unset!important; + border-top: unset!important; +} + +.text-center { + color: #fff; +} + +.card-img-overlay { + display: flex; + flex-direction: column; + justify-content: flex-end; + height: 100%; +} +``` + +```html + + +
            +
            + +
            +
            +
            +
            + AFRICA +
            +

            + Kenya +

            +
            +
            +
            + +
            +```","```css +.img-wrapper{ + position: relative; + text-align: center; + color: white; +} +.card-footer{ + position: absolute; + top: 60%; + left: 50%; + transform: translate(-50%, -50%); + } + h3, h1{ + color: #fff + } +``` + +```html +
            +
            +
            + +
            +
            +
            +
            +
            +
            +

            + Africa +

            +

            + Kenya +

            +
            +
            + +
            +```" +6176627,I am getting problems when generating a multi-dimensional array with unknown size. How can I fix it?,2011/05/30,"['https://Stackoverflow.com/questions/6176627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/737369/']","To generate a multi-dimensional array with unknown size is called a jagged array. + +For example: + +``` +String[][] array = new String[5][]; + +``` + +Java uses arrays of arrays for multi-dimensional arrays. I think you have to specify the first size. Otherwise, use list of lists. + +``` +ArrayList> list = new ArrayList>(); + +```","Array is static. ArrayList is dynamic. + +Before creating an array you should be aware of the size of the array. To create a multidimensional array without knowing array size is not possible. + +Better you have to use a nested `ArrayList` or nested `Vector`: + +``` +ArrayList> list = new ArrayList>(); + +```" +26172820,"``` +some text here +some -- text--here +test text--here +
            test --test
            + + +``` + +For the above content, I want some help in writing code to replace all occurrence of double dash (`--`) with `—`. + +But, it should not replace the double dash for any attributes inside the html elements. For e.g., the double dash in the class name (`my--class-name--here`) and id name (`id=""some--id""`) should not replaced. +And, also it should not replace double dash in ``",2014/10/03,"['https://Stackoverflow.com/questions/26172820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227325/']","If you are wanting a one-liner to replace outside of `<` and `>`, you can use the following. + +``` +$html = preg_replace('~<[^>]*>(*SKIP)(*F)|--~', '—', $html); + +``` + +The idea is to skip any content that is located between an opening and closing bracket character. + +On the left side of the alternation operator we match the subpattern we do not want. Making it fail and forcing the regular expression engine to not retry the substring using backtracking control verbs. + +[`Working Demo`](https://eval.in/201333)","Use a negative lookahead to match `--` which was not inside any html tags. + +``` +--(?![^><]*>) + +``` + +Replace the matched `--` with `—`. + +[DEMO](http://regex101.com/r/lJ1fL0/2) + +``` +some -- text--here +test text--here +
            test --test
            + +EOT; +echo preg_replace('~--(?![^><]*>)~', '—', $string); +?> + +``` + +Output: + +``` +some text here +some — text—here +test text—here +
            test —test
            + + +```" +28595,"### Introduction + +When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well. + +### Task + +You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider: + +* Individual resistors +* Two resistors in series +* Two resistors in parallel + +The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value. + +The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance. + +### Formulas + +* The resistance of one resistor is `R1` +* The net resistance of two resistors in series is `R1 + R2` +* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)` +* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100. +* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement. + +### Scoring + +Score is measured in characters of code, per usual golf rules. Lowest score wins. + +### Example + +We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined): + +``` +680 | 2200 519.444 +1000 | 1000 500. +150 + 330 480. +220 + 330 550. +470 470 +680 | 1500 467.89 +680 | 3300 563.819 +100 + 470 570. +220 + 220 440. +100 + 330 430. +470 | 4700 427.273 +680 | 4700 594.052 +1000 | 1500 600. +470 | 3300 411.406 +680 | 1000 404.762 +150 + 470 620. +... +many more rows +... +2200 + 4700 6900. +3300 + 4700 8000. +4700 + 4700 9400. + +``` + +In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel. + +**Best of each language so far (1 June 2014):** + +1. J - 70 char +2. APL - 102 char +3. Mathematica - 122 char +4. Ruby - 154 char +5. Javascript - 156 char +6. Julia - 163 char +7. Perl - 185 char +8. Python - 270 char",2014/05/25,"['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/']","Javascript (E6) 156 ~~162 164 186~~ +=================================== + +**Last Edit** Assuming all resistor values > 0, you can use them for the loop condition + +``` +F=(t,s)=>{D=a=>Math.abs(a[1]/t-1);for(i=r=[];a=s[j=i++];r[l]=[a,a])for(;b=s[j--];)l=r.push([a+'+'+b,c=a+b],[a+'|'+b,a*b/c]);return r.sort((a,b)=>D(a)-D(b))} + +``` + +Usage : `F(510, [100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700])` + +**Ungolfed** + +``` +F = (t,s) => +{ + D = a => Math.abs(a[1]/t-1); + for (i=r=[]; a=s[j=i++]; r[l]=[a,a]) + for(; b=s[j--];) + l = r.push([a+'+'+b, c=a+b], [a+'|'+b, a*b/c]); + return r.sort((a,b) => D(a)-D(b)) +} + +```","Perl, 213 199 185 bytes +======================= + +**213 bytes:** + +``` +$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$""=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep s!(..\b(\d+)\b,?\b(\d+)?\b\))=\K(??{$2<$3})!$1!ee&&/\d$/,<{S,P}({@i},{@i})= S({@i})=>; + +``` + +**199 bytes:** + +``` +$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$""=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep/(..(\d+),?(\d+)?\))/&&$2>=$3&&($_.=eval$1),<{S,P}({@i},{@i})= S({@i})=>; + +``` + +**185 bytes:** + +``` +$t=pop;sub t{abs 1-$_[0]=~s!.*=!!r/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$""=',';$i=""{@ARGV}"";say for sort{t($a)<=>t$b}grep{my($x,$y)=/\d+/g;$_.='='.eval,$x>=$y}<{S,P}($i,$i) S($i)> + +``` + +Pass all available resistors as arguments. The target resistance should be the last: + +``` +$ perl -E 'code' R1 R2 R3 ... Rn target + +``` + +### How it works (old code) + +* Define subroutines `S` and `P` to compute the sum and parallel values of two resistors. +* Set [`$""`](http://perldoc.perl.org/perlvar.html) to "","" to interpolate `@ARGV` inside the [`glob`](http://perldoc.perl.org/functions/glob.html) operator +* `<{S,P}({@i},{@i})= S({@i})=>` generates a cartesian of all possibilities: + +S(100,100), S(100,150), S(100,220), ... P(100,100), P(100,150) ... S(100), S(150) ... +* Combine `s///ee` with `grep` to evaluate the equivalent resistances and filter out unwanted repeats (performed by `(??{$2<$3})` and `/\d$/` +* `sort` by fitness computed in subroutine `t` + +### Changes in new code + +* Avoid use of `s///ee`, use shorter regex with conditional checking and `eval` inside `grep` +* Replace repeats of `""{@i}"" with`$i` +* Introduce `$x`, `$y` instead of `$2`, `$3` +* Replace `split/=/,pop` with `$_[0]=~s!!!r` +* No need for trailing `;` +* `eval;` is equivalent to `eval $_;` +* Add `=` along with `eval`-ed answer instead of declaring it up front + +### Output: + +`P` represents resistors in parallel, `S` represents resistors in series. + +``` +P(2200,680)=519.444444444444 +P(1000,1000)=500 +S(330,150)=480 +S(330,220)=550 +S(470)=470 +P(1500,680)=467.889908256881 +P(3300,680)=563.819095477387 +S(470,100)=570 +S(220,220)=440 +S(330,100)=430 +P(4700,470)=427.272727272727 +P(4700,680)=594.052044609665 +P(1500,1000)=600 +P(3300,470)=411.405835543767 +P(1000,680)=404.761904761905 +S(470,150)=620 +P(2200,470)=387.265917602996 +S(220,150)=370 +S(330,330)=660 +P(1500,470)=357.868020304569 +S(680)=680 +P(680,680)=340 +P(2200,1000)=687.5 +S(330)=330 +S(470,220)=690 +S(220,100)=320 +P(1000,470)=319.727891156463 +P(4700,330)=308.349900596421 +S(150,150)=300 +P(3300,330)=300 +P(2200,330)=286.95652173913 +P(680,470)=277.913043478261 +P(1500,330)=270.491803278689 +P(1500,1500)=750 +P(3300,1000)=767.441860465116 +S(150,100)=250 +P(1000,330)=248.12030075188 +S(680,100)=780 +P(470,470)=235 +P(680,330)=222.178217821782 +S(470,330)=800 +S(220)=220 +P(4700,220)=210.162601626016 +P(3300,220)=206.25 +S(100,100)=200 +P(2200,220)=200 +P(4700,1000)=824.561403508772 +P(470,330)=193.875 +P(1500,220)=191.860465116279 +S(680,150)=830 +P(1000,220)=180.327868852459 +P(680,220)=166.222222222222 +P(330,330)=165 +S(150)=150 +P(470,220)=149.855072463768 +P(4700,150)=145.360824742268 +P(3300,150)=143.478260869565 +P(2200,150)=140.425531914894 +P(1500,150)=136.363636363636 +P(330,220)=132 +P(1000,150)=130.434782608696 +P(2200,1500)=891.891891891892 +P(680,150)=122.89156626506 +S(680,220)=900 +P(470,150)=113.709677419355 +P(220,220)=110 +P(330,150)=103.125 +S(100)=100 +P(4700,100)=97.9166666666667 +P(3300,100)=97.0588235294118 +P(2200,100)=95.6521739130435 +P(1500,100)=93.75 +P(1000,100)=90.9090909090909 +P(220,150)=89.1891891891892 +P(680,100)=87.1794871794872 +P(470,100)=82.4561403508772 +S(470,470)=940 +P(330,100)=76.7441860465116 +P(150,150)=75 +P(220,100)=68.75 +P(150,100)=60 +P(100,100)=50 +S(1000)=1000 +S(680,330)=1010 +P(3300,1500)=1031.25 +S(1000,100)=1100 +P(2200,2200)=1100 +P(4700,1500)=1137.09677419355 +S(680,470)=1150 +S(1000,150)=1150 +S(1000,220)=1220 +P(3300,2200)=1320 +S(1000,330)=1330 +S(680,680)=1360 +S(1000,470)=1470 +P(4700,2200)=1498.55072463768 +S(1500)=1500 +S(1500,100)=1600 +S(1500,150)=1650 +P(3300,3300)=1650 +S(1000,680)=1680 +S(1500,220)=1720 +S(1500,330)=1830 +P(4700,3300)=1938.75 +S(1500,470)=1970 +S(1000,1000)=2000 +S(1500,680)=2180 +S(2200)=2200 +S(2200,100)=2300 +S(2200,150)=2350 +P(4700,4700)=2350 +S(2200,220)=2420 +S(1500,1000)=2500 +S(2200,330)=2530 +S(2200,470)=2670 +S(2200,680)=2880 +S(1500,1500)=3000 +S(2200,1000)=3200 +S(3300)=3300 +S(3300,100)=3400 +S(3300,150)=3450 +S(3300,220)=3520 +S(3300,330)=3630 +S(2200,1500)=3700 +S(3300,470)=3770 +S(3300,680)=3980 +S(3300,1000)=4300 +S(2200,2200)=4400 +S(4700)=4700 +S(3300,1500)=4800 +S(4700,100)=4800 +S(4700,150)=4850 +S(4700,220)=4920 +S(4700,330)=5030 +S(4700,470)=5170 +S(4700,680)=5380 +S(3300,2200)=5500 +S(4700,1000)=5700 +S(4700,1500)=6200 +S(3300,3300)=6600 +S(4700,2200)=6900 +S(4700,3300)=8000 +S(4700,4700)=9400 + +```" +28595,"### Introduction + +When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well. + +### Task + +You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider: + +* Individual resistors +* Two resistors in series +* Two resistors in parallel + +The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value. + +The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance. + +### Formulas + +* The resistance of one resistor is `R1` +* The net resistance of two resistors in series is `R1 + R2` +* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)` +* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100. +* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement. + +### Scoring + +Score is measured in characters of code, per usual golf rules. Lowest score wins. + +### Example + +We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined): + +``` +680 | 2200 519.444 +1000 | 1000 500. +150 + 330 480. +220 + 330 550. +470 470 +680 | 1500 467.89 +680 | 3300 563.819 +100 + 470 570. +220 + 220 440. +100 + 330 430. +470 | 4700 427.273 +680 | 4700 594.052 +1000 | 1500 600. +470 | 3300 411.406 +680 | 1000 404.762 +150 + 470 620. +... +many more rows +... +2200 + 4700 6900. +3300 + 4700 8000. +4700 + 4700 9400. + +``` + +In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel. + +**Best of each language so far (1 June 2014):** + +1. J - 70 char +2. APL - 102 char +3. Mathematica - 122 char +4. Ruby - 154 char +5. Javascript - 156 char +6. Julia - 163 char +7. Perl - 185 char +8. Python - 270 char",2014/05/25,"['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/']","Mathematica, ~~151~~ 122 characters +----------------------------------- + +Expects the target resistance to be stored in `r` and the list of available resistors in `l`. + +``` +SortBy[Join[{#,#}&/@l,Join@@(#@@@Union[Sort/@N@l~Tuples~{2}]&/@{{""+"",##,#+#2}&,{""|"",##,#*#2/(#+#2)}&})],Abs[#[[-1]]/r-1]&] + +``` + +Less golf: + +``` +SortBy[Join[{#, #} & /@ l, + Join @@ (# @@@ + Union[Sort /@ N@l~Tuples~{2}] & /@ {{""+"", ##, # + #2} &, {""|"", ##, + #*#2/(# + #2)} &})], Abs[#[[-1]]/r - 1] &] + +``` + +The output format differs from the suggested one but configurations are easily determinable. The output is a list of configurations. Each configuration is of one of the following forms: + +``` +{R1, Total} +{""+"", R1, R2, Total} +{""|"", R1, R2, Total} + +``` + +So the first three elements of the output read + +``` +{{""|"", 680., 2200., 519.444}, {""|"", 1000., 1000., 500.}, {""+"", 150., 330., 480.}, ...} + +``` + +If you're fine with rational numbers, I could save two characters from omitting `N@`. That is, the first element (for instance) would be returned as `4675/9` instead of `519.444`.","Javascript (E6) 156 ~~162 164 186~~ +=================================== + +**Last Edit** Assuming all resistor values > 0, you can use them for the loop condition + +``` +F=(t,s)=>{D=a=>Math.abs(a[1]/t-1);for(i=r=[];a=s[j=i++];r[l]=[a,a])for(;b=s[j--];)l=r.push([a+'+'+b,c=a+b],[a+'|'+b,a*b/c]);return r.sort((a,b)=>D(a)-D(b))} + +``` + +Usage : `F(510, [100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700])` + +**Ungolfed** + +``` +F = (t,s) => +{ + D = a => Math.abs(a[1]/t-1); + for (i=r=[]; a=s[j=i++]; r[l]=[a,a]) + for(; b=s[j--];) + l = r.push([a+'+'+b, c=a+b], [a+'|'+b, a*b/c]); + return r.sort((a,b) => D(a)-D(b)) +} + +```" +28595,"### Introduction + +When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well. + +### Task + +You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider: + +* Individual resistors +* Two resistors in series +* Two resistors in parallel + +The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value. + +The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance. + +### Formulas + +* The resistance of one resistor is `R1` +* The net resistance of two resistors in series is `R1 + R2` +* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)` +* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100. +* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement. + +### Scoring + +Score is measured in characters of code, per usual golf rules. Lowest score wins. + +### Example + +We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined): + +``` +680 | 2200 519.444 +1000 | 1000 500. +150 + 330 480. +220 + 330 550. +470 470 +680 | 1500 467.89 +680 | 3300 563.819 +100 + 470 570. +220 + 220 440. +100 + 330 430. +470 | 4700 427.273 +680 | 4700 594.052 +1000 | 1500 600. +470 | 3300 411.406 +680 | 1000 404.762 +150 + 470 620. +... +many more rows +... +2200 + 4700 6900. +3300 + 4700 8000. +4700 + 4700 9400. + +``` + +In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel. + +**Best of each language so far (1 June 2014):** + +1. J - 70 char +2. APL - 102 char +3. Mathematica - 122 char +4. Ruby - 154 char +5. Javascript - 156 char +6. Julia - 163 char +7. Perl - 185 char +8. Python - 270 char",2014/05/25,"['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/']","APL (102) +========= + +``` +{V←{⊃¨⍺{⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵}⍺⍺/¨Z/⍨≤/¨Z←,∘.,⍨⍵}⋄K[⍋|¯1+⍺÷⍨0 4↓K←↑('|'{÷+/÷⍺⍵}V⍵),('+'+V⍵),{⍵,' =',⍵}¨⍵;]} + +``` + +This takes the target resistance as the left argument and a list of available resistors as the right argument. + +Explanation: + +* `V←{`...`}`: `V` is a function that: + + `Z/⍨≤/¨Z←,∘.,⍨⍵`: finds every unique combination of two values in `⍵`, + - `Z←,∘.,⍨⍵`: join each value in `⍵` with each value in `⍵`, store in `Z`, + - `Z/⍨≤/¨Z`: select from `Z` those combinations where the first value is less than or equal to the second value + + `⍺{`...`}⍺⍺/¨`: and then applies following function, bound with the left function (`⍺⍺`) on the right and the left argument (`⍺`) on the left, to each pair: + - `⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵`, the left argument, followed by the left bound argument, followed by the right argument, followed by `=`, followed by the right function (`⍵⍵`) applied to both arguments. (This is the formatting function, `X [configuration] Y [equals] (X [fn] Y)`.) + + `⊃¨`: and then unbox each element. +* `{⍵,' =',⍵}¨⍵`: for each element in `⍵`, make the configurations for the individual resistors. (`⍵`, nothing, nothing, `=`, `⍵`). +* `('+'+V⍵)`: use the `V` function to make all serial configurations (character is `'+'` and function is `+`). +* `'|'{÷+/÷⍺⍵}V⍵`: use the `V` function to make all parallel configurations (character is `'|'` and function is `{÷+/÷⍺⍵}`, inverse of sum of inverse of arguments). +* `K←↑`: make this into a matrix and store it in `K`. +* `0 4↓K`: drop the 4 first columns from `K`, leaving only the resistance values. +* `|¯1+⍺÷⍨`: calculate the distance between `⍺` and each configuration. +* `K[⍋`...`;]`: sort `K` by the distances.","Perl, 213 199 185 bytes +======================= + +**213 bytes:** + +``` +$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$""=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep s!(..\b(\d+)\b,?\b(\d+)?\b\))=\K(??{$2<$3})!$1!ee&&/\d$/,<{S,P}({@i},{@i})= S({@i})=>; + +``` + +**199 bytes:** + +``` +$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$""=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep/(..(\d+),?(\d+)?\))/&&$2>=$3&&($_.=eval$1),<{S,P}({@i},{@i})= S({@i})=>; + +``` + +**185 bytes:** + +``` +$t=pop;sub t{abs 1-$_[0]=~s!.*=!!r/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$""=',';$i=""{@ARGV}"";say for sort{t($a)<=>t$b}grep{my($x,$y)=/\d+/g;$_.='='.eval,$x>=$y}<{S,P}($i,$i) S($i)> + +``` + +Pass all available resistors as arguments. The target resistance should be the last: + +``` +$ perl -E 'code' R1 R2 R3 ... Rn target + +``` + +### How it works (old code) + +* Define subroutines `S` and `P` to compute the sum and parallel values of two resistors. +* Set [`$""`](http://perldoc.perl.org/perlvar.html) to "","" to interpolate `@ARGV` inside the [`glob`](http://perldoc.perl.org/functions/glob.html) operator +* `<{S,P}({@i},{@i})= S({@i})=>` generates a cartesian of all possibilities: + +S(100,100), S(100,150), S(100,220), ... P(100,100), P(100,150) ... S(100), S(150) ... +* Combine `s///ee` with `grep` to evaluate the equivalent resistances and filter out unwanted repeats (performed by `(??{$2<$3})` and `/\d$/` +* `sort` by fitness computed in subroutine `t` + +### Changes in new code + +* Avoid use of `s///ee`, use shorter regex with conditional checking and `eval` inside `grep` +* Replace repeats of `""{@i}"" with`$i` +* Introduce `$x`, `$y` instead of `$2`, `$3` +* Replace `split/=/,pop` with `$_[0]=~s!!!r` +* No need for trailing `;` +* `eval;` is equivalent to `eval $_;` +* Add `=` along with `eval`-ed answer instead of declaring it up front + +### Output: + +`P` represents resistors in parallel, `S` represents resistors in series. + +``` +P(2200,680)=519.444444444444 +P(1000,1000)=500 +S(330,150)=480 +S(330,220)=550 +S(470)=470 +P(1500,680)=467.889908256881 +P(3300,680)=563.819095477387 +S(470,100)=570 +S(220,220)=440 +S(330,100)=430 +P(4700,470)=427.272727272727 +P(4700,680)=594.052044609665 +P(1500,1000)=600 +P(3300,470)=411.405835543767 +P(1000,680)=404.761904761905 +S(470,150)=620 +P(2200,470)=387.265917602996 +S(220,150)=370 +S(330,330)=660 +P(1500,470)=357.868020304569 +S(680)=680 +P(680,680)=340 +P(2200,1000)=687.5 +S(330)=330 +S(470,220)=690 +S(220,100)=320 +P(1000,470)=319.727891156463 +P(4700,330)=308.349900596421 +S(150,150)=300 +P(3300,330)=300 +P(2200,330)=286.95652173913 +P(680,470)=277.913043478261 +P(1500,330)=270.491803278689 +P(1500,1500)=750 +P(3300,1000)=767.441860465116 +S(150,100)=250 +P(1000,330)=248.12030075188 +S(680,100)=780 +P(470,470)=235 +P(680,330)=222.178217821782 +S(470,330)=800 +S(220)=220 +P(4700,220)=210.162601626016 +P(3300,220)=206.25 +S(100,100)=200 +P(2200,220)=200 +P(4700,1000)=824.561403508772 +P(470,330)=193.875 +P(1500,220)=191.860465116279 +S(680,150)=830 +P(1000,220)=180.327868852459 +P(680,220)=166.222222222222 +P(330,330)=165 +S(150)=150 +P(470,220)=149.855072463768 +P(4700,150)=145.360824742268 +P(3300,150)=143.478260869565 +P(2200,150)=140.425531914894 +P(1500,150)=136.363636363636 +P(330,220)=132 +P(1000,150)=130.434782608696 +P(2200,1500)=891.891891891892 +P(680,150)=122.89156626506 +S(680,220)=900 +P(470,150)=113.709677419355 +P(220,220)=110 +P(330,150)=103.125 +S(100)=100 +P(4700,100)=97.9166666666667 +P(3300,100)=97.0588235294118 +P(2200,100)=95.6521739130435 +P(1500,100)=93.75 +P(1000,100)=90.9090909090909 +P(220,150)=89.1891891891892 +P(680,100)=87.1794871794872 +P(470,100)=82.4561403508772 +S(470,470)=940 +P(330,100)=76.7441860465116 +P(150,150)=75 +P(220,100)=68.75 +P(150,100)=60 +P(100,100)=50 +S(1000)=1000 +S(680,330)=1010 +P(3300,1500)=1031.25 +S(1000,100)=1100 +P(2200,2200)=1100 +P(4700,1500)=1137.09677419355 +S(680,470)=1150 +S(1000,150)=1150 +S(1000,220)=1220 +P(3300,2200)=1320 +S(1000,330)=1330 +S(680,680)=1360 +S(1000,470)=1470 +P(4700,2200)=1498.55072463768 +S(1500)=1500 +S(1500,100)=1600 +S(1500,150)=1650 +P(3300,3300)=1650 +S(1000,680)=1680 +S(1500,220)=1720 +S(1500,330)=1830 +P(4700,3300)=1938.75 +S(1500,470)=1970 +S(1000,1000)=2000 +S(1500,680)=2180 +S(2200)=2200 +S(2200,100)=2300 +S(2200,150)=2350 +P(4700,4700)=2350 +S(2200,220)=2420 +S(1500,1000)=2500 +S(2200,330)=2530 +S(2200,470)=2670 +S(2200,680)=2880 +S(1500,1500)=3000 +S(2200,1000)=3200 +S(3300)=3300 +S(3300,100)=3400 +S(3300,150)=3450 +S(3300,220)=3520 +S(3300,330)=3630 +S(2200,1500)=3700 +S(3300,470)=3770 +S(3300,680)=3980 +S(3300,1000)=4300 +S(2200,2200)=4400 +S(4700)=4700 +S(3300,1500)=4800 +S(4700,100)=4800 +S(4700,150)=4850 +S(4700,220)=4920 +S(4700,330)=5030 +S(4700,470)=5170 +S(4700,680)=5380 +S(3300,2200)=5500 +S(4700,1000)=5700 +S(4700,1500)=6200 +S(3300,3300)=6600 +S(4700,2200)=6900 +S(4700,3300)=8000 +S(4700,4700)=9400 + +```" +28595,"### Introduction + +When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well. + +### Task + +You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider: + +* Individual resistors +* Two resistors in series +* Two resistors in parallel + +The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value. + +The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance. + +### Formulas + +* The resistance of one resistor is `R1` +* The net resistance of two resistors in series is `R1 + R2` +* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)` +* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100. +* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement. + +### Scoring + +Score is measured in characters of code, per usual golf rules. Lowest score wins. + +### Example + +We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined): + +``` +680 | 2200 519.444 +1000 | 1000 500. +150 + 330 480. +220 + 330 550. +470 470 +680 | 1500 467.89 +680 | 3300 563.819 +100 + 470 570. +220 + 220 440. +100 + 330 430. +470 | 4700 427.273 +680 | 4700 594.052 +1000 | 1500 600. +470 | 3300 411.406 +680 | 1000 404.762 +150 + 470 620. +... +many more rows +... +2200 + 4700 6900. +3300 + 4700 8000. +4700 + 4700 9400. + +``` + +In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel. + +**Best of each language so far (1 June 2014):** + +1. J - 70 char +2. APL - 102 char +3. Mathematica - 122 char +4. Ruby - 154 char +5. Javascript - 156 char +6. Julia - 163 char +7. Perl - 185 char +8. Python - 270 char",2014/05/25,"['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/']","APL (102) +========= + +``` +{V←{⊃¨⍺{⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵}⍺⍺/¨Z/⍨≤/¨Z←,∘.,⍨⍵}⋄K[⍋|¯1+⍺÷⍨0 4↓K←↑('|'{÷+/÷⍺⍵}V⍵),('+'+V⍵),{⍵,' =',⍵}¨⍵;]} + +``` + +This takes the target resistance as the left argument and a list of available resistors as the right argument. + +Explanation: + +* `V←{`...`}`: `V` is a function that: + + `Z/⍨≤/¨Z←,∘.,⍨⍵`: finds every unique combination of two values in `⍵`, + - `Z←,∘.,⍨⍵`: join each value in `⍵` with each value in `⍵`, store in `Z`, + - `Z/⍨≤/¨Z`: select from `Z` those combinations where the first value is less than or equal to the second value + + `⍺{`...`}⍺⍺/¨`: and then applies following function, bound with the left function (`⍺⍺`) on the right and the left argument (`⍺`) on the left, to each pair: + - `⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵`, the left argument, followed by the left bound argument, followed by the right argument, followed by `=`, followed by the right function (`⍵⍵`) applied to both arguments. (This is the formatting function, `X [configuration] Y [equals] (X [fn] Y)`.) + + `⊃¨`: and then unbox each element. +* `{⍵,' =',⍵}¨⍵`: for each element in `⍵`, make the configurations for the individual resistors. (`⍵`, nothing, nothing, `=`, `⍵`). +* `('+'+V⍵)`: use the `V` function to make all serial configurations (character is `'+'` and function is `+`). +* `'|'{÷+/÷⍺⍵}V⍵`: use the `V` function to make all parallel configurations (character is `'|'` and function is `{÷+/÷⍺⍵}`, inverse of sum of inverse of arguments). +* `K←↑`: make this into a matrix and store it in `K`. +* `0 4↓K`: drop the 4 first columns from `K`, leaving only the resistance values. +* `|¯1+⍺÷⍨`: calculate the distance between `⍺` and each configuration. +* `K[⍋`...`;]`: sort `K` by the distances.","Ruby 2.1, ~~156~~ 154 bytes +=========================== + +``` +s=->(a,z){c={};a.map{|e|a.map{|f|c[e]=e;c[e+f]=""#{e}+#{f}"";c[1/(1.0/f+1.0/e)]=""#{e}|#{f}""}};c.sort_by{|k,|(k/z.to_f-1).abs}.map{|e|puts""#{e[1]}=#{e[0]}""}} + +``` + +Ungolfed: +--------- + +``` +s =->(a,z) { + c={} + a.map{|e| + a.map{|f| + c[e]=e + c[e+f]=""#{e}+#{f}"" + c[1/(1.0/f+1.0/e)]=""#{e}|#{f}"" + } + } + c.sort_by{|k,| + (k/z.to_f-1).abs + }.map{|e| + puts ""#{e[1]}=#{e[0]}"" + } +} + +``` + +What it does: +------------- + +* For each value `e` in `a`; + + Iterate through `a`, computing single, series, and parallel values as keys to printed values in hash `c`; +* Determine distance from `z` for each key in `c`; and, +* For each value `e[1]` for each key `e[0]` in `c`, print `e[1]=e[0]`. + +Sample usage: +------------- + +`s[[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700], 510]` + +Sample output: +-------------- + +``` +2200|680=519.4444444444445 +1000|1000=500.0 +330+150=480 +330+220=550 +470=470 +1500|680=467.88990825688074 +3300|680=563.8190954773869 +. +. +. +4700+1500=6200 +3300+3300=6600 +4700+2200=6900 +4700+3300=8000 +4700+4700=9400 + +```" +28595,"### Introduction + +When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well. + +### Task + +You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider: + +* Individual resistors +* Two resistors in series +* Two resistors in parallel + +The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value. + +The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance. + +### Formulas + +* The resistance of one resistor is `R1` +* The net resistance of two resistors in series is `R1 + R2` +* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)` +* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100. +* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement. + +### Scoring + +Score is measured in characters of code, per usual golf rules. Lowest score wins. + +### Example + +We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined): + +``` +680 | 2200 519.444 +1000 | 1000 500. +150 + 330 480. +220 + 330 550. +470 470 +680 | 1500 467.89 +680 | 3300 563.819 +100 + 470 570. +220 + 220 440. +100 + 330 430. +470 | 4700 427.273 +680 | 4700 594.052 +1000 | 1500 600. +470 | 3300 411.406 +680 | 1000 404.762 +150 + 470 620. +... +many more rows +... +2200 + 4700 6900. +3300 + 4700 8000. +4700 + 4700 9400. + +``` + +In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel. + +**Best of each language so far (1 June 2014):** + +1. J - 70 char +2. APL - 102 char +3. Mathematica - 122 char +4. Ruby - 154 char +5. Javascript - 156 char +6. Julia - 163 char +7. Perl - 185 char +8. Python - 270 char",2014/05/25,"['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/']","Python 3 - ~~250~~ ~~247~~ 270 bytes +==================================== + +``` +from itertools import* +import sys +r=sys.argv[1:] +t=int(r.pop()) +p=set(map(tuple,map(sorted,product(r,r)))) +a=[('+'.join(b),sum(map(int,b)))for b in p]+[('|'.join(b),1/sum(map(lambda n:1/int(n),b)))for b in p] +for s in sorted(a,key=lambda b:abs(float(b[1])/t-1)):print(s) + +``` + +Run like this: + +``` +python resistors.py 100 150 220 330 470 680 1000 1500 2200 3300 4700 510 + +``` + +(that is, a space-delimited list of resistors, with the target value at the end) + +Output: + +``` +('2200|680', 519.4444444444445) +('1000|1000', 500.0) +('150+330', 480) +('220+330', 550) +('1500|680', 467.88990825688074) +('3300|680', 563.8190954773869) + +[snip] + +('2200+4700', 6900) +('3300+4700', 8000) +('4700+4700', 9400) + +``` + +~~I would say that outputting, say, `680|2200` and `2200|680` separately is still pretty clear. If this is unacceptable, I can change it, but it'll cost me bytes.~~ Wasn't acceptable. Cost me bytes. Now I sort the tuples before chucking them into the set, otherwise the solution is identical.","Perl, 213 199 185 bytes +======================= + +**213 bytes:** + +``` +$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$""=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep s!(..\b(\d+)\b,?\b(\d+)?\b\))=\K(??{$2<$3})!$1!ee&&/\d$/,<{S,P}({@i},{@i})= S({@i})=>; + +``` + +**199 bytes:** + +``` +$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$""=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep/(..(\d+),?(\d+)?\))/&&$2>=$3&&($_.=eval$1),<{S,P}({@i},{@i})= S({@i})=>; + +``` + +**185 bytes:** + +``` +$t=pop;sub t{abs 1-$_[0]=~s!.*=!!r/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$""=',';$i=""{@ARGV}"";say for sort{t($a)<=>t$b}grep{my($x,$y)=/\d+/g;$_.='='.eval,$x>=$y}<{S,P}($i,$i) S($i)> + +``` + +Pass all available resistors as arguments. The target resistance should be the last: + +``` +$ perl -E 'code' R1 R2 R3 ... Rn target + +``` + +### How it works (old code) + +* Define subroutines `S` and `P` to compute the sum and parallel values of two resistors. +* Set [`$""`](http://perldoc.perl.org/perlvar.html) to "","" to interpolate `@ARGV` inside the [`glob`](http://perldoc.perl.org/functions/glob.html) operator +* `<{S,P}({@i},{@i})= S({@i})=>` generates a cartesian of all possibilities: + +S(100,100), S(100,150), S(100,220), ... P(100,100), P(100,150) ... S(100), S(150) ... +* Combine `s///ee` with `grep` to evaluate the equivalent resistances and filter out unwanted repeats (performed by `(??{$2<$3})` and `/\d$/` +* `sort` by fitness computed in subroutine `t` + +### Changes in new code + +* Avoid use of `s///ee`, use shorter regex with conditional checking and `eval` inside `grep` +* Replace repeats of `""{@i}"" with`$i` +* Introduce `$x`, `$y` instead of `$2`, `$3` +* Replace `split/=/,pop` with `$_[0]=~s!!!r` +* No need for trailing `;` +* `eval;` is equivalent to `eval $_;` +* Add `=` along with `eval`-ed answer instead of declaring it up front + +### Output: + +`P` represents resistors in parallel, `S` represents resistors in series. + +``` +P(2200,680)=519.444444444444 +P(1000,1000)=500 +S(330,150)=480 +S(330,220)=550 +S(470)=470 +P(1500,680)=467.889908256881 +P(3300,680)=563.819095477387 +S(470,100)=570 +S(220,220)=440 +S(330,100)=430 +P(4700,470)=427.272727272727 +P(4700,680)=594.052044609665 +P(1500,1000)=600 +P(3300,470)=411.405835543767 +P(1000,680)=404.761904761905 +S(470,150)=620 +P(2200,470)=387.265917602996 +S(220,150)=370 +S(330,330)=660 +P(1500,470)=357.868020304569 +S(680)=680 +P(680,680)=340 +P(2200,1000)=687.5 +S(330)=330 +S(470,220)=690 +S(220,100)=320 +P(1000,470)=319.727891156463 +P(4700,330)=308.349900596421 +S(150,150)=300 +P(3300,330)=300 +P(2200,330)=286.95652173913 +P(680,470)=277.913043478261 +P(1500,330)=270.491803278689 +P(1500,1500)=750 +P(3300,1000)=767.441860465116 +S(150,100)=250 +P(1000,330)=248.12030075188 +S(680,100)=780 +P(470,470)=235 +P(680,330)=222.178217821782 +S(470,330)=800 +S(220)=220 +P(4700,220)=210.162601626016 +P(3300,220)=206.25 +S(100,100)=200 +P(2200,220)=200 +P(4700,1000)=824.561403508772 +P(470,330)=193.875 +P(1500,220)=191.860465116279 +S(680,150)=830 +P(1000,220)=180.327868852459 +P(680,220)=166.222222222222 +P(330,330)=165 +S(150)=150 +P(470,220)=149.855072463768 +P(4700,150)=145.360824742268 +P(3300,150)=143.478260869565 +P(2200,150)=140.425531914894 +P(1500,150)=136.363636363636 +P(330,220)=132 +P(1000,150)=130.434782608696 +P(2200,1500)=891.891891891892 +P(680,150)=122.89156626506 +S(680,220)=900 +P(470,150)=113.709677419355 +P(220,220)=110 +P(330,150)=103.125 +S(100)=100 +P(4700,100)=97.9166666666667 +P(3300,100)=97.0588235294118 +P(2200,100)=95.6521739130435 +P(1500,100)=93.75 +P(1000,100)=90.9090909090909 +P(220,150)=89.1891891891892 +P(680,100)=87.1794871794872 +P(470,100)=82.4561403508772 +S(470,470)=940 +P(330,100)=76.7441860465116 +P(150,150)=75 +P(220,100)=68.75 +P(150,100)=60 +P(100,100)=50 +S(1000)=1000 +S(680,330)=1010 +P(3300,1500)=1031.25 +S(1000,100)=1100 +P(2200,2200)=1100 +P(4700,1500)=1137.09677419355 +S(680,470)=1150 +S(1000,150)=1150 +S(1000,220)=1220 +P(3300,2200)=1320 +S(1000,330)=1330 +S(680,680)=1360 +S(1000,470)=1470 +P(4700,2200)=1498.55072463768 +S(1500)=1500 +S(1500,100)=1600 +S(1500,150)=1650 +P(3300,3300)=1650 +S(1000,680)=1680 +S(1500,220)=1720 +S(1500,330)=1830 +P(4700,3300)=1938.75 +S(1500,470)=1970 +S(1000,1000)=2000 +S(1500,680)=2180 +S(2200)=2200 +S(2200,100)=2300 +S(2200,150)=2350 +P(4700,4700)=2350 +S(2200,220)=2420 +S(1500,1000)=2500 +S(2200,330)=2530 +S(2200,470)=2670 +S(2200,680)=2880 +S(1500,1500)=3000 +S(2200,1000)=3200 +S(3300)=3300 +S(3300,100)=3400 +S(3300,150)=3450 +S(3300,220)=3520 +S(3300,330)=3630 +S(2200,1500)=3700 +S(3300,470)=3770 +S(3300,680)=3980 +S(3300,1000)=4300 +S(2200,2200)=4400 +S(4700)=4700 +S(3300,1500)=4800 +S(4700,100)=4800 +S(4700,150)=4850 +S(4700,220)=4920 +S(4700,330)=5030 +S(4700,470)=5170 +S(4700,680)=5380 +S(3300,2200)=5500 +S(4700,1000)=5700 +S(4700,1500)=6200 +S(3300,3300)=6600 +S(4700,2200)=6900 +S(4700,3300)=8000 +S(4700,4700)=9400 + +```" +28595,"### Introduction + +When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well. + +### Task + +You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider: + +* Individual resistors +* Two resistors in series +* Two resistors in parallel + +The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value. + +The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance. + +### Formulas + +* The resistance of one resistor is `R1` +* The net resistance of two resistors in series is `R1 + R2` +* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)` +* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100. +* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement. + +### Scoring + +Score is measured in characters of code, per usual golf rules. Lowest score wins. + +### Example + +We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined): + +``` +680 | 2200 519.444 +1000 | 1000 500. +150 + 330 480. +220 + 330 550. +470 470 +680 | 1500 467.89 +680 | 3300 563.819 +100 + 470 570. +220 + 220 440. +100 + 330 430. +470 | 4700 427.273 +680 | 4700 594.052 +1000 | 1500 600. +470 | 3300 411.406 +680 | 1000 404.762 +150 + 470 620. +... +many more rows +... +2200 + 4700 6900. +3300 + 4700 8000. +4700 + 4700 9400. + +``` + +In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel. + +**Best of each language so far (1 June 2014):** + +1. J - 70 char +2. APL - 102 char +3. Mathematica - 122 char +4. Ruby - 154 char +5. Javascript - 156 char +6. Julia - 163 char +7. Perl - 185 char +8. Python - 270 char",2014/05/25,"['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/']","Julia - ~~179~~ 163 bytes +========================= + +``` +f(t,s)=(\ =repmat;m=endof(s);A=A[v=(A=s\m).>=(B=sort(A))];B=B[v];F=[s,C=A+B,A.*B./C];n=sum(v);print([[s P=["" ""]\m P;A [+]\n B;A [|]\n B] F][sortperm(abs(F-t)),:])) + +``` + +This works the same as the old version, but the argument in the print statement has been organised slightly differently to reduce the number of square brackets necessary. Saves 4 bytes. Absorbing the spaces vector creation into the print argument saves an extra 2 bytes. It has also switched from using ""find"" to get the relevant indices to using the logical form. Saves 6 bytes. Absorbing the calculation of the index vector into the adjustment of A saved another 2 bytes. Finally, replacing endof(v) with sum(v) saved 2 more bytes. Total saving: 16 bytes. + +Old version: + +``` +f(t,s)=(\ =repmat;m=endof(s);A=s\m;v=find(A.>=(B=sort(A)));A=A[v];B=B[v];F=[s,C=A+B,A.*B./C];n=endof(v);P=["" ""]\m;print([[s,A,A] [P,[+]\n,[|]\n] [P,B,B] F][sortperm(abs(F-t)),:])) + +``` + +Within the function, here's what it's doing: + +``` +\ =repmat # Overloads \ operator to save lots of characters +m=endof(s) # Length of input s (""Stock"") +A=s\m # Equivalent to repmat(s,m) (see first command) +B=sort(A) # Same as A but sorted - rather than cycling through + # the resistors m times, it repeats each one m times +v=find(A.>=B) # Identify which pairs for A,B have A>=B +A=A[v];B=B[v] # Remove pairs where A f(170,[100,220,300]) +300 | 300 150 +100 + 100 200 +300 | 220 126.92307692307692 +220 220 +220 | 220 110 +100 100 +300 | 100 75 +220 | 100 68.75 +100 | 100 50 +300 300 +220 + 100 320 +300 + 100 400 +220 + 220 440 +300 + 220 520 +300 + 300 600 + +```","Perl, 213 199 185 bytes +======================= + +**213 bytes:** + +``` +$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$""=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep s!(..\b(\d+)\b,?\b(\d+)?\b\))=\K(??{$2<$3})!$1!ee&&/\d$/,<{S,P}({@i},{@i})= S({@i})=>; + +``` + +**199 bytes:** + +``` +$t=pop;sub t{abs 1-(split/=/,pop)[1]/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$""=',';@i=@ARGV;say for sort{t($a)<=>t($b)}grep/(..(\d+),?(\d+)?\))/&&$2>=$3&&($_.=eval$1),<{S,P}({@i},{@i})= S({@i})=>; + +``` + +**185 bytes:** + +``` +$t=pop;sub t{abs 1-$_[0]=~s!.*=!!r/$t}sub S{$_[0]+$_[1]}sub P{$_[0]*$_[1]/&S}$""=',';$i=""{@ARGV}"";say for sort{t($a)<=>t$b}grep{my($x,$y)=/\d+/g;$_.='='.eval,$x>=$y}<{S,P}($i,$i) S($i)> + +``` + +Pass all available resistors as arguments. The target resistance should be the last: + +``` +$ perl -E 'code' R1 R2 R3 ... Rn target + +``` + +### How it works (old code) + +* Define subroutines `S` and `P` to compute the sum and parallel values of two resistors. +* Set [`$""`](http://perldoc.perl.org/perlvar.html) to "","" to interpolate `@ARGV` inside the [`glob`](http://perldoc.perl.org/functions/glob.html) operator +* `<{S,P}({@i},{@i})= S({@i})=>` generates a cartesian of all possibilities: + +S(100,100), S(100,150), S(100,220), ... P(100,100), P(100,150) ... S(100), S(150) ... +* Combine `s///ee` with `grep` to evaluate the equivalent resistances and filter out unwanted repeats (performed by `(??{$2<$3})` and `/\d$/` +* `sort` by fitness computed in subroutine `t` + +### Changes in new code + +* Avoid use of `s///ee`, use shorter regex with conditional checking and `eval` inside `grep` +* Replace repeats of `""{@i}"" with`$i` +* Introduce `$x`, `$y` instead of `$2`, `$3` +* Replace `split/=/,pop` with `$_[0]=~s!!!r` +* No need for trailing `;` +* `eval;` is equivalent to `eval $_;` +* Add `=` along with `eval`-ed answer instead of declaring it up front + +### Output: + +`P` represents resistors in parallel, `S` represents resistors in series. + +``` +P(2200,680)=519.444444444444 +P(1000,1000)=500 +S(330,150)=480 +S(330,220)=550 +S(470)=470 +P(1500,680)=467.889908256881 +P(3300,680)=563.819095477387 +S(470,100)=570 +S(220,220)=440 +S(330,100)=430 +P(4700,470)=427.272727272727 +P(4700,680)=594.052044609665 +P(1500,1000)=600 +P(3300,470)=411.405835543767 +P(1000,680)=404.761904761905 +S(470,150)=620 +P(2200,470)=387.265917602996 +S(220,150)=370 +S(330,330)=660 +P(1500,470)=357.868020304569 +S(680)=680 +P(680,680)=340 +P(2200,1000)=687.5 +S(330)=330 +S(470,220)=690 +S(220,100)=320 +P(1000,470)=319.727891156463 +P(4700,330)=308.349900596421 +S(150,150)=300 +P(3300,330)=300 +P(2200,330)=286.95652173913 +P(680,470)=277.913043478261 +P(1500,330)=270.491803278689 +P(1500,1500)=750 +P(3300,1000)=767.441860465116 +S(150,100)=250 +P(1000,330)=248.12030075188 +S(680,100)=780 +P(470,470)=235 +P(680,330)=222.178217821782 +S(470,330)=800 +S(220)=220 +P(4700,220)=210.162601626016 +P(3300,220)=206.25 +S(100,100)=200 +P(2200,220)=200 +P(4700,1000)=824.561403508772 +P(470,330)=193.875 +P(1500,220)=191.860465116279 +S(680,150)=830 +P(1000,220)=180.327868852459 +P(680,220)=166.222222222222 +P(330,330)=165 +S(150)=150 +P(470,220)=149.855072463768 +P(4700,150)=145.360824742268 +P(3300,150)=143.478260869565 +P(2200,150)=140.425531914894 +P(1500,150)=136.363636363636 +P(330,220)=132 +P(1000,150)=130.434782608696 +P(2200,1500)=891.891891891892 +P(680,150)=122.89156626506 +S(680,220)=900 +P(470,150)=113.709677419355 +P(220,220)=110 +P(330,150)=103.125 +S(100)=100 +P(4700,100)=97.9166666666667 +P(3300,100)=97.0588235294118 +P(2200,100)=95.6521739130435 +P(1500,100)=93.75 +P(1000,100)=90.9090909090909 +P(220,150)=89.1891891891892 +P(680,100)=87.1794871794872 +P(470,100)=82.4561403508772 +S(470,470)=940 +P(330,100)=76.7441860465116 +P(150,150)=75 +P(220,100)=68.75 +P(150,100)=60 +P(100,100)=50 +S(1000)=1000 +S(680,330)=1010 +P(3300,1500)=1031.25 +S(1000,100)=1100 +P(2200,2200)=1100 +P(4700,1500)=1137.09677419355 +S(680,470)=1150 +S(1000,150)=1150 +S(1000,220)=1220 +P(3300,2200)=1320 +S(1000,330)=1330 +S(680,680)=1360 +S(1000,470)=1470 +P(4700,2200)=1498.55072463768 +S(1500)=1500 +S(1500,100)=1600 +S(1500,150)=1650 +P(3300,3300)=1650 +S(1000,680)=1680 +S(1500,220)=1720 +S(1500,330)=1830 +P(4700,3300)=1938.75 +S(1500,470)=1970 +S(1000,1000)=2000 +S(1500,680)=2180 +S(2200)=2200 +S(2200,100)=2300 +S(2200,150)=2350 +P(4700,4700)=2350 +S(2200,220)=2420 +S(1500,1000)=2500 +S(2200,330)=2530 +S(2200,470)=2670 +S(2200,680)=2880 +S(1500,1500)=3000 +S(2200,1000)=3200 +S(3300)=3300 +S(3300,100)=3400 +S(3300,150)=3450 +S(3300,220)=3520 +S(3300,330)=3630 +S(2200,1500)=3700 +S(3300,470)=3770 +S(3300,680)=3980 +S(3300,1000)=4300 +S(2200,2200)=4400 +S(4700)=4700 +S(3300,1500)=4800 +S(4700,100)=4800 +S(4700,150)=4850 +S(4700,220)=4920 +S(4700,330)=5030 +S(4700,470)=5170 +S(4700,680)=5380 +S(3300,2200)=5500 +S(4700,1000)=5700 +S(4700,1500)=6200 +S(3300,3300)=6600 +S(4700,2200)=6900 +S(4700,3300)=8000 +S(4700,4700)=9400 + +```" +28595,"### Introduction + +When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well. + +### Task + +You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider: + +* Individual resistors +* Two resistors in series +* Two resistors in parallel + +The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value. + +The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance. + +### Formulas + +* The resistance of one resistor is `R1` +* The net resistance of two resistors in series is `R1 + R2` +* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)` +* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100. +* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement. + +### Scoring + +Score is measured in characters of code, per usual golf rules. Lowest score wins. + +### Example + +We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined): + +``` +680 | 2200 519.444 +1000 | 1000 500. +150 + 330 480. +220 + 330 550. +470 470 +680 | 1500 467.89 +680 | 3300 563.819 +100 + 470 570. +220 + 220 440. +100 + 330 430. +470 | 4700 427.273 +680 | 4700 594.052 +1000 | 1500 600. +470 | 3300 411.406 +680 | 1000 404.762 +150 + 470 620. +... +many more rows +... +2200 + 4700 6900. +3300 + 4700 8000. +4700 + 4700 9400. + +``` + +In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel. + +**Best of each language so far (1 June 2014):** + +1. J - 70 char +2. APL - 102 char +3. Mathematica - 122 char +4. Ruby - 154 char +5. Javascript - 156 char +6. Julia - 163 char +7. Perl - 185 char +8. Python - 270 char",2014/05/25,"['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/']","Javascript (E6) 156 ~~162 164 186~~ +=================================== + +**Last Edit** Assuming all resistor values > 0, you can use them for the loop condition + +``` +F=(t,s)=>{D=a=>Math.abs(a[1]/t-1);for(i=r=[];a=s[j=i++];r[l]=[a,a])for(;b=s[j--];)l=r.push([a+'+'+b,c=a+b],[a+'|'+b,a*b/c]);return r.sort((a,b)=>D(a)-D(b))} + +``` + +Usage : `F(510, [100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700])` + +**Ungolfed** + +``` +F = (t,s) => +{ + D = a => Math.abs(a[1]/t-1); + for (i=r=[]; a=s[j=i++]; r[l]=[a,a]) + for(; b=s[j--];) + l = r.push([a+'+'+b, c=a+b], [a+'|'+b, a*b/c]); + return r.sort((a,b) => D(a)-D(b)) +} + +```","Javascript, 248 bytes +===================== + +```js +function r(T,L){R=[],O="""";for(i in L){R.push([a=L[i],a]);for(j=i;j=(B=sort(A))];B=B[v];F=[s,C=A+B,A.*B./C];n=sum(v);print([[s P=["" ""]\m P;A [+]\n B;A [|]\n B] F][sortperm(abs(F-t)),:])) + +``` + +This works the same as the old version, but the argument in the print statement has been organised slightly differently to reduce the number of square brackets necessary. Saves 4 bytes. Absorbing the spaces vector creation into the print argument saves an extra 2 bytes. It has also switched from using ""find"" to get the relevant indices to using the logical form. Saves 6 bytes. Absorbing the calculation of the index vector into the adjustment of A saved another 2 bytes. Finally, replacing endof(v) with sum(v) saved 2 more bytes. Total saving: 16 bytes. + +Old version: + +``` +f(t,s)=(\ =repmat;m=endof(s);A=s\m;v=find(A.>=(B=sort(A)));A=A[v];B=B[v];F=[s,C=A+B,A.*B./C];n=endof(v);P=["" ""]\m;print([[s,A,A] [P,[+]\n,[|]\n] [P,B,B] F][sortperm(abs(F-t)),:])) + +``` + +Within the function, here's what it's doing: + +``` +\ =repmat # Overloads \ operator to save lots of characters +m=endof(s) # Length of input s (""Stock"") +A=s\m # Equivalent to repmat(s,m) (see first command) +B=sort(A) # Same as A but sorted - rather than cycling through + # the resistors m times, it repeats each one m times +v=find(A.>=B) # Identify which pairs for A,B have A>=B +A=A[v];B=B[v] # Remove pairs where A f(170,[100,220,300]) +300 | 300 150 +100 + 100 200 +300 | 220 126.92307692307692 +220 220 +220 | 220 110 +100 100 +300 | 100 75 +220 | 100 68.75 +100 | 100 50 +300 300 +220 + 100 320 +300 + 100 400 +220 + 220 440 +300 + 220 520 +300 + 300 600 + +```" +28595,"### Introduction + +When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well. + +### Task + +You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider: + +* Individual resistors +* Two resistors in series +* Two resistors in parallel + +The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value. + +The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance. + +### Formulas + +* The resistance of one resistor is `R1` +* The net resistance of two resistors in series is `R1 + R2` +* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)` +* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100. +* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement. + +### Scoring + +Score is measured in characters of code, per usual golf rules. Lowest score wins. + +### Example + +We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined): + +``` +680 | 2200 519.444 +1000 | 1000 500. +150 + 330 480. +220 + 330 550. +470 470 +680 | 1500 467.89 +680 | 3300 563.819 +100 + 470 570. +220 + 220 440. +100 + 330 430. +470 | 4700 427.273 +680 | 4700 594.052 +1000 | 1500 600. +470 | 3300 411.406 +680 | 1000 404.762 +150 + 470 620. +... +many more rows +... +2200 + 4700 6900. +3300 + 4700 8000. +4700 + 4700 9400. + +``` + +In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel. + +**Best of each language so far (1 June 2014):** + +1. J - 70 char +2. APL - 102 char +3. Mathematica - 122 char +4. Ruby - 154 char +5. Javascript - 156 char +6. Julia - 163 char +7. Perl - 185 char +8. Python - 270 char",2014/05/25,"['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/']","APL (102) +========= + +``` +{V←{⊃¨⍺{⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵}⍺⍺/¨Z/⍨≤/¨Z←,∘.,⍨⍵}⋄K[⍋|¯1+⍺÷⍨0 4↓K←↑('|'{÷+/÷⍺⍵}V⍵),('+'+V⍵),{⍵,' =',⍵}¨⍵;]} + +``` + +This takes the target resistance as the left argument and a list of available resistors as the right argument. + +Explanation: + +* `V←{`...`}`: `V` is a function that: + + `Z/⍨≤/¨Z←,∘.,⍨⍵`: finds every unique combination of two values in `⍵`, + - `Z←,∘.,⍨⍵`: join each value in `⍵` with each value in `⍵`, store in `Z`, + - `Z/⍨≤/¨Z`: select from `Z` those combinations where the first value is less than or equal to the second value + + `⍺{`...`}⍺⍺/¨`: and then applies following function, bound with the left function (`⍺⍺`) on the right and the left argument (`⍺`) on the left, to each pair: + - `⍺,⍺⍺,⍵,'=',⍺⍵⍵⍵`, the left argument, followed by the left bound argument, followed by the right argument, followed by `=`, followed by the right function (`⍵⍵`) applied to both arguments. (This is the formatting function, `X [configuration] Y [equals] (X [fn] Y)`.) + + `⊃¨`: and then unbox each element. +* `{⍵,' =',⍵}¨⍵`: for each element in `⍵`, make the configurations for the individual resistors. (`⍵`, nothing, nothing, `=`, `⍵`). +* `('+'+V⍵)`: use the `V` function to make all serial configurations (character is `'+'` and function is `+`). +* `'|'{÷+/÷⍺⍵}V⍵`: use the `V` function to make all parallel configurations (character is `'|'` and function is `{÷+/÷⍺⍵}`, inverse of sum of inverse of arguments). +* `K←↑`: make this into a matrix and store it in `K`. +* `0 4↓K`: drop the 4 first columns from `K`, leaving only the resistance values. +* `|¯1+⍺÷⍨`: calculate the distance between `⍺` and each configuration. +* `K[⍋`...`;]`: sort `K` by the distances.","Python 3 - ~~250~~ ~~247~~ 270 bytes +==================================== + +``` +from itertools import* +import sys +r=sys.argv[1:] +t=int(r.pop()) +p=set(map(tuple,map(sorted,product(r,r)))) +a=[('+'.join(b),sum(map(int,b)))for b in p]+[('|'.join(b),1/sum(map(lambda n:1/int(n),b)))for b in p] +for s in sorted(a,key=lambda b:abs(float(b[1])/t-1)):print(s) + +``` + +Run like this: + +``` +python resistors.py 100 150 220 330 470 680 1000 1500 2200 3300 4700 510 + +``` + +(that is, a space-delimited list of resistors, with the target value at the end) + +Output: + +``` +('2200|680', 519.4444444444445) +('1000|1000', 500.0) +('150+330', 480) +('220+330', 550) +('1500|680', 467.88990825688074) +('3300|680', 563.8190954773869) + +[snip] + +('2200+4700', 6900) +('3300+4700', 8000) +('4700+4700', 9400) + +``` + +~~I would say that outputting, say, `680|2200` and `2200|680` separately is still pretty clear. If this is unacceptable, I can change it, but it'll cost me bytes.~~ Wasn't acceptable. Cost me bytes. Now I sort the tuples before chucking them into the set, otherwise the solution is identical." +28595,"### Introduction + +When building an electronics project, a schematic may call for a resistor of an unusual value (say, 510 ohms). You check your parts bin and find that you have no 510-ohm resistors. But you do have many common values above and below this value. By combining resistors in parallel and series, you should be able to approximate the 510-ohm resistor fairly well. + +### Task + +You must write a function or program which accepts a list of resistor values (resistors you stock) and a target value (which you aim to approximate). The program must consider: + +* Individual resistors +* Two resistors in series +* Two resistors in parallel + +The program should compute all possible combinations of 1 and 2 resistors from the stock list (including two copies of the same resistor value), compute their series and parallel resistance, then sort the configurations according to how well they approximate the target value. + +The output format should be one configuration per line, with a `+` denoting series and `|` denoting parallel, and some space or an = sign before the net resistance. + +### Formulas + +* The resistance of one resistor is `R1` +* The net resistance of two resistors in series is `R1 + R2` +* The net resistance of two resistors in parallel is `1 / (1/R1 + 1/R2)` +* The distance between an approximated resistance value and the target value can be calculated as pseudo-logarithmic distance, not linear distance: `dist = abs(Rapprox / Rtarget - 1)`. For example, 200 is closer to 350 than it is to 100. +* A better distance measure is true logarithmic distance `dist = abs(log(Rapprox/Rtarget))`, but since this was not specified in the original question, you are free to use either measurement. + +### Scoring + +Score is measured in characters of code, per usual golf rules. Lowest score wins. + +### Example + +We have the following resistors in stock `[100, 150, 220, 330, 470, 680, 1000, 1500, 2200, 3300, 4700]` and wish to target `510` ohms. The program should output 143 configurations, approximately as shown (you can change the format, but make sure the meaning is easily determined): + +``` +680 | 2200 519.444 +1000 | 1000 500. +150 + 330 480. +220 + 330 550. +470 470 +680 | 1500 467.89 +680 | 3300 563.819 +100 + 470 570. +220 + 220 440. +100 + 330 430. +470 | 4700 427.273 +680 | 4700 594.052 +1000 | 1500 600. +470 | 3300 411.406 +680 | 1000 404.762 +150 + 470 620. +... +many more rows +... +2200 + 4700 6900. +3300 + 4700 8000. +4700 + 4700 9400. + +``` + +In this example, the best approximation of 510 ohms is given by 680- and 2200-ohm resistors in parallel. + +**Best of each language so far (1 June 2014):** + +1. J - 70 char +2. APL - 102 char +3. Mathematica - 122 char +4. Ruby - 154 char +5. Javascript - 156 char +6. Julia - 163 char +7. Perl - 185 char +8. Python - 270 char",2014/05/25,"['https://codegolf.stackexchange.com/questions/28595', 'https://codegolf.stackexchange.com', 'https://codegolf.stackexchange.com/users/16615/']","J - 86 71 70 char +================= + +``` +((]/:[|@<:@%~2{::""1])(;a:,<)""0,[:,/(<,.+`|,.+/;+&.%/)""1@;@((<@,.{:)\)) + +``` + +I'm not going to bother to explain every little detail because a lot of the code is spent syncing up the results of different functions, but here's the gist of the golf: + +* `;@((<@,.{:)\)` makes every possible pair of resistors, to be connected either in parallel or in series. +* `[:,/(<,.+`|,.+/;+&.%/)""1@` then connects them, in parallel and in series, making a big list of possible connections. +* `(;a:,<)""0,` adds in the possibility of using only one resistor by itself to approximate. +* `(]/:[|@<:@%~2{::""1])` sorts the list of combinations of resistors by the pseudolog distance (`|@<:@%`) between the target and the resultant resistance from each combination. + +And this is how to use it: + +``` + rouv =: ((]/:[|@<:@%~2{::""1])(;a:,<)""0,[:,/(<,.+`|,.+/;+&.%/)""1@;@((<@,.{:)\)) + # 510 rouv 100 150 220 330 470 680 1000 1500 2200 3300 4700 NB. how many? +143 + 10 {. 510 rouv 100 150 220 330 470 680 1000 1500 2200 3300 4700 NB. view first 10 ++---------+-+-------+ +|680 2200 |||519.444| ++---------+-+-------+ +|1000 1000|||500 | ++---------+-+-------+ +|150 330 |+|480 | ++---------+-+-------+ +|220 330 |+|550 | ++---------+-+-------+ +|470 | |470 | ++---------+-+-------+ +|680 1500 |||467.89 | ++---------+-+-------+ +|680 3300 |||563.819| ++---------+-+-------+ +|100 470 |+|570 | ++---------+-+-------+ +|220 220 |+|440 | ++---------+-+-------+ +|100 330 |+|430 | ++---------+-+-------+ + +``` + +You don't have to only view the first 10 like I did above, but this is a function and the J REPL truncates very large return values, and the full output for this example has 287 lines. You can force it all to STDOUT with something like `tmoutput toCRLF , LF ,.~ "": blah rouv blah` on Windows—drop the `toCRLF` on Linux—but `rouv` is a function and internally, all the rows exist. + +Note: +----- + +The question seems to have been changed right under our noses, and now the log distance is defined as `abs(log(Rapprox/Rtarget))` instead of `abs(Rapprox/Rtarget-1)`. To correct this in my golf, we can change the `|@<:@%` to `|@^.@%`: `<:` is Decrement while `^.` is Logarithm.","Python 3 - ~~250~~ ~~247~~ 270 bytes +==================================== + +``` +from itertools import* +import sys +r=sys.argv[1:] +t=int(r.pop()) +p=set(map(tuple,map(sorted,product(r,r)))) +a=[('+'.join(b),sum(map(int,b)))for b in p]+[('|'.join(b),1/sum(map(lambda n:1/int(n),b)))for b in p] +for s in sorted(a,key=lambda b:abs(float(b[1])/t-1)):print(s) + +``` + +Run like this: + +``` +python resistors.py 100 150 220 330 470 680 1000 1500 2200 3300 4700 510 + +``` + +(that is, a space-delimited list of resistors, with the target value at the end) + +Output: + +``` +('2200|680', 519.4444444444445) +('1000|1000', 500.0) +('150+330', 480) +('220+330', 550) +('1500|680', 467.88990825688074) +('3300|680', 563.8190954773869) + +[snip] + +('2200+4700', 6900) +('3300+4700', 8000) +('4700+4700', 9400) + +``` + +~~I would say that outputting, say, `680|2200` and `2200|680` separately is still pretty clear. If this is unacceptable, I can change it, but it'll cost me bytes.~~ Wasn't acceptable. Cost me bytes. Now I sort the tuples before chucking them into the set, otherwise the solution is identical." +58913,"I have just bought a brand new MacBook Pro with 4 GB RAM, and was wondering which Windows 7 version 32 bit or 64 bit I should install with BootCamp, in order to do Visual Studio development? + +Is Visual Studio 32 bit? Any pointers to the correct install process would also be appreciated.",2009/10/22,"['https://superuser.com/questions/58913', 'https://superuser.com', 'https://superuser.com/users/-1/']","No brainer: 64bit. + +In addition to the ability to use more RAM and run 64bit apps, 64bit chips have other features the OS itself can use to get performance benefits that a 32bit OS won't know about. More registers, for example. + +So even if 32bit Visual Studio is the only app you run, you're still better off running 64bit windows. Not to mention it gives you the ability to build 64bit apps.","Visual Studio is a 32 bit application only, so if that is the major reason for installing windows, 64-bit will not give you any additional features, other than it will be able to handle all 4 GB of memory, whereas 32-bit will only give 3.2 GB or so. + +See this question for details about general 32-bit vs 64 bit systems: + +* [32-bit vs 64-bit systems](https://superuser.com/questions/56540/32-bit-vs-64-bit-systems)" +58913,"I have just bought a brand new MacBook Pro with 4 GB RAM, and was wondering which Windows 7 version 32 bit or 64 bit I should install with BootCamp, in order to do Visual Studio development? + +Is Visual Studio 32 bit? Any pointers to the correct install process would also be appreciated.",2009/10/22,"['https://superuser.com/questions/58913', 'https://superuser.com', 'https://superuser.com/users/-1/']","While Visual Studio is 32 bit application, depending on what type of applications you're planning to develop, you might find it beneficial to use the 64-bit version. IIRC you can run and debug both 32-bit and 64-bit executables in 64-bit Windows but not in 32-bit Windows (as the latter isn't able to run 64-bit apps).","Visual Studio is a 32 bit application only, so if that is the major reason for installing windows, 64-bit will not give you any additional features, other than it will be able to handle all 4 GB of memory, whereas 32-bit will only give 3.2 GB or so. + +See this question for details about general 32-bit vs 64 bit systems: + +* [32-bit vs 64-bit systems](https://superuser.com/questions/56540/32-bit-vs-64-bit-systems)" +58913,"I have just bought a brand new MacBook Pro with 4 GB RAM, and was wondering which Windows 7 version 32 bit or 64 bit I should install with BootCamp, in order to do Visual Studio development? + +Is Visual Studio 32 bit? Any pointers to the correct install process would also be appreciated.",2009/10/22,"['https://superuser.com/questions/58913', 'https://superuser.com', 'https://superuser.com/users/-1/']","No brainer: 64bit. + +In addition to the ability to use more RAM and run 64bit apps, 64bit chips have other features the OS itself can use to get performance benefits that a 32bit OS won't know about. More registers, for example. + +So even if 32bit Visual Studio is the only app you run, you're still better off running 64bit windows. Not to mention it gives you the ability to build 64bit apps.","While Visual Studio is 32 bit application, depending on what type of applications you're planning to develop, you might find it beneficial to use the 64-bit version. IIRC you can run and debug both 32-bit and 64-bit executables in 64-bit Windows but not in 32-bit Windows (as the latter isn't able to run 64-bit apps)." +6284893,"I am using [SDAC](http://www.devart.com/sdac/) components to query a SQL Server 2008 database. It has a `recordcount`property as all datasets do and it also has the `FetchAll` property (which I think it is called `packedrecords` on `clientdatasets`). Said that, I got a few questions: + +1 - If I set `FetchAll = True` the `recordcount` property returns ok. But in this case, when I have a large database and my query returns a lot of lines, sometimes the memory grows a lot (because it is fetching all data to get the `recordcount` of course). + +2 - If I set `FetchAll = False`, the `recordcount` returns -1 and the memory does not grow. But I really need the recordcount. And I also wanna create a generic function for this, so I dont have to change all my existent queries. + +What can I do to have the `recordcount` working and the memory usage of the application low in this case? + +Please, do not post that I dont need recordcount (or that I should use EOF and BOF) because I really do and this is not the question. + +I thought about using a query to determine the recordcount, but it has some problems since my query is going to be executed twice (1 for recordcount, 1 for data) + +**EDIT** + +@Johan pointed out a good solution, and it seems to work. Can anybody confirm this? I am using 1 `TMSCconnection` for every `TMSQuery` (because i am using threads), so I dont think this will be a problem, will it? + +``` + MSQuery1.FetchAll := False; + MSQuery1.FetchRows := 10; + MSQuery1.SQL.Text := 'select * from cidade'; + MSQuery1.Open; + ShowMessage(IntToStr(MSQuery1.RecordCount)); //returns 10 + MSQuery1.Close; + + MSQuery2.SQL.Text := 'SELECT @@rowcount AS num_of_rows'; + MSQuery2.Open; + ShowMessage(MSQuery2.FieldByName('num_of_rows').AsString); //returns 289 + +``` + +**EDIT 2\*** + +`MSQuery1` must be closed, or `MSQuery2` will not return the `num_of_rows`. Why is that? + +``` + MSQuery1.FetchAll := False; + MSQuery1.FetchRows := 10; + MSQuery1.SQL.Text := 'select * from cidade'; + MSQuery1.Open; + ShowMessage(IntToStr(MSQuery1.RecordCount)); //returns 10 + //MSQuery1.Close; <(context, listen: false); + provider.login(); + }), + icon: Image.asset(socialIcon)), + ); + } +} + +``` + +When I press button I am facing this issue: + +``` +ProviderNotFoundException (Error: Could not find the correct Provider above this SocialIconButton Widget. + +```",2022/11/11,"['https://Stackoverflow.com/questions/74401695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20477196/']","You're not using the username and the password you provided in your docker-compose file. Try this and then enter `my_password`: + +```bash +docker exec -it container_id psql -U my_user -d my_db --password + +``` + +Check [the official documentation](https://docs.postgresql.fr/15/app-psql.html) to find out about the PostgreSQL terminal.","I would also like to add, in your compose file you're not exposing any ports for the db container. So it will be unreachable via external sources (you, your app or anything that isn't ran within that container)." +74401695,"I want use Firebase Auth in Flutter project. And I am use `provider`. Everything is okey but I am facing one issue with `provider`. + +My IconButtonWidget: + +``` +class SocialIconButton extends StatelessWidget { + final String socialIcon; + const SocialIconButton({Key? key, required this.socialIcon}) + : super(key: key); + + @override + Widget build(BuildContext context) { + return Padding( + padding: EdgeInsets.symmetric(horizontal: context.dynamicWidth(20)), + child: IconButton( + onPressed: (() { + final provider = + Provider.of(context, listen: false); + provider.login(); + }), + icon: Image.asset(socialIcon)), + ); + } +} + +``` + +When I press button I am facing this issue: + +``` +ProviderNotFoundException (Error: Could not find the correct Provider above this SocialIconButton Widget. + +```",2022/11/11,"['https://Stackoverflow.com/questions/74401695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20477196/']","You're not using the username and the password you provided in your docker-compose file. Try this and then enter `my_password`: + +```bash +docker exec -it container_id psql -U my_user -d my_db --password + +``` + +Check [the official documentation](https://docs.postgresql.fr/15/app-psql.html) to find out about the PostgreSQL terminal.","I think you need to add `environment` to project container. + +``` + environment: + - DB_HOST=db + - DB_NAME=my_db + - DB_USER=youruser + - DB_PASS=yourpass + depends_on: + - db + +``` + +add this before `depends_on` + +And now see if it solves" +74401695,"I want use Firebase Auth in Flutter project. And I am use `provider`. Everything is okey but I am facing one issue with `provider`. + +My IconButtonWidget: + +``` +class SocialIconButton extends StatelessWidget { + final String socialIcon; + const SocialIconButton({Key? key, required this.socialIcon}) + : super(key: key); + + @override + Widget build(BuildContext context) { + return Padding( + padding: EdgeInsets.symmetric(horizontal: context.dynamicWidth(20)), + child: IconButton( + onPressed: (() { + final provider = + Provider.of(context, listen: false); + provider.login(); + }), + icon: Image.asset(socialIcon)), + ); + } +} + +``` + +When I press button I am facing this issue: + +``` +ProviderNotFoundException (Error: Could not find the correct Provider above this SocialIconButton Widget. + +```",2022/11/11,"['https://Stackoverflow.com/questions/74401695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20477196/']","You're not using the username and the password you provided in your docker-compose file. Try this and then enter `my_password`: + +```bash +docker exec -it container_id psql -U my_user -d my_db --password + +``` + +Check [the official documentation](https://docs.postgresql.fr/15/app-psql.html) to find out about the PostgreSQL terminal.","You should add ports to the docker-compose for the postgres image,as this would allow postgres to be accessible outside the container + +``` +- ports: + ""5432:5432"" + +``` + +You can checkout more here [docker-compose for postgres](https://geshan.com.np/blog/2021/12/docker-postgres/)" +10262114,"I need to script my app (not a game) and I have a problem, choosing a script lang for this. +Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used. +Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib). +Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app. +So, I'd like to know is there a scripting lang, which satisfies this conditions: + +* unicode strings +* I can import C++ functions and then call them from +script +* Can be embedded to app (no dll's) without any problems + +Reinventing the wheel is not a good idea, so I don't want to develop my own lang. +Or there is a way to write unicode strings in Lua's source? Like in C++ L""Unicode string""",2012/04/21,"['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/']","Lua strings are encoding-agnostic. So, yes, you can write unicode strings in Lua scripts. If you need pattern matching, then the standard Lua string library does not support unicode classes. But plain substring search works.","Have a look at JavaScript - the [V8 engine](https://developers.google.com/v8/embed) is pretty powerful and JavaScript does not come with a big stdlib. Besides that, you can easily embed it and from what I know it handles unicode fine." +10262114,"I need to script my app (not a game) and I have a problem, choosing a script lang for this. +Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used. +Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib). +Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app. +So, I'd like to know is there a scripting lang, which satisfies this conditions: + +* unicode strings +* I can import C++ functions and then call them from +script +* Can be embedded to app (no dll's) without any problems + +Reinventing the wheel is not a good idea, so I don't want to develop my own lang. +Or there is a way to write unicode strings in Lua's source? Like in C++ L""Unicode string""",2012/04/21,"['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/']","Have a look at JavaScript - the [V8 engine](https://developers.google.com/v8/embed) is pretty powerful and JavaScript does not come with a big stdlib. Besides that, you can easily embed it and from what I know it handles unicode fine.","Have a look at [`Io`](http://www.iolanguage.com). + +It's [unicode](http://www.iolanguage.com/scm/io/docs/IoGuide.html#Unicode) all the way down and [embeddable](http://www.iolanguage.com/scm/io/docs/IoGuide.html#Embedding). Also it seems to provide some [C++ binding library](https://stackoverflow.com/a/3153987/12195)." +10262114,"I need to script my app (not a game) and I have a problem, choosing a script lang for this. +Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used. +Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib). +Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app. +So, I'd like to know is there a scripting lang, which satisfies this conditions: + +* unicode strings +* I can import C++ functions and then call them from +script +* Can be embedded to app (no dll's) without any problems + +Reinventing the wheel is not a good idea, so I don't want to develop my own lang. +Or there is a way to write unicode strings in Lua's source? Like in C++ L""Unicode string""",2012/04/21,"['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/']","There isn't really such a thing as a ""unicode string"". Strings are a sequence of bytes that can contain anything. Knowing the encoding of the data in the string matters, though. + +I use Lua with [UTF-8 strings](http://en.wikipedia.org/wiki/UTF-8), which just works for all the operations I care about. I do not use any Unicode string library, though those are available for Lua ([ICU4Lua](http://luaforge.net/projects/icu-lua/), [slnunicode](http://luaforge.net/projects/sln/), etc.). + +Some notes about using UTF-8 strings in Lua: + +* String length (# operator) returns the string length in bytes, not characters or codepoints (non-ASCII characters may be sequences of multiple bytes). +* String splitting (e.g. string.sub) must not split up UTF-8 sequences. +* String matching works (string.find, string.match) fine with ASCII patterns. +* Substring searching (such as string.find in 'plain' mode) works with UTF-8 as the needle or the haystack. + +Counting codepoints in UTF-8 is quite straightforward, if slightly less efficient than other encodings. For example in Lua: + +``` +function utf8_length(str) + return select(2, string.gsub(str, ""[^\128-\193]"", """")); +end + +``` + +If you need more than this kind of thing, the unicode libraries I mentioned give you APIs for everything, including conversion between encodings. + +Personally I prefer this straightforward approach to any of the languages that force a certain flavour of unicode on you (such as Javascript) or try and be clever by having multiple encodings built into the language (such as Python). In my experience they only cause headaches and performance bottlenecks. + +In any case, I think every developer should have a good basic understanding of how unicode works, and the principle differences between different encodings so that they can make the best choice about how to handle unicode in their application. + +For example if all your existing strings in your application are in a wide-char encoding, it would be much less convenient to use Lua as you would have to add a conversion to every string in and out of Lua. This is entirely possible, but if your app might be CPU-bound (as in a game) then it would be a negative point performance-wise.","Have a look at JavaScript - the [V8 engine](https://developers.google.com/v8/embed) is pretty powerful and JavaScript does not come with a big stdlib. Besides that, you can easily embed it and from what I know it handles unicode fine." +10262114,"I need to script my app (not a game) and I have a problem, choosing a script lang for this. +Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used. +Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib). +Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app. +So, I'd like to know is there a scripting lang, which satisfies this conditions: + +* unicode strings +* I can import C++ functions and then call them from +script +* Can be embedded to app (no dll's) without any problems + +Reinventing the wheel is not a good idea, so I don't want to develop my own lang. +Or there is a way to write unicode strings in Lua's source? Like in C++ L""Unicode string""",2012/04/21,"['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/']","Have a look at JavaScript - the [V8 engine](https://developers.google.com/v8/embed) is pretty powerful and JavaScript does not come with a big stdlib. Besides that, you can easily embed it and from what I know it handles unicode fine.","Take look at [Jim Tcl](http://jim.tcl.tk). It's small, easily embeddable and extendable, supports UTF-8 strings, and it's pretty powerful" +10262114,"I need to script my app (not a game) and I have a problem, choosing a script lang for this. +Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used. +Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib). +Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app. +So, I'd like to know is there a scripting lang, which satisfies this conditions: + +* unicode strings +* I can import C++ functions and then call them from +script +* Can be embedded to app (no dll's) without any problems + +Reinventing the wheel is not a good idea, so I don't want to develop my own lang. +Or there is a way to write unicode strings in Lua's source? Like in C++ L""Unicode string""",2012/04/21,"['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/']","Lua strings are encoding-agnostic. So, yes, you can write unicode strings in Lua scripts. If you need pattern matching, then the standard Lua string library does not support unicode classes. But plain substring search works.","Have a look at [`Io`](http://www.iolanguage.com). + +It's [unicode](http://www.iolanguage.com/scm/io/docs/IoGuide.html#Unicode) all the way down and [embeddable](http://www.iolanguage.com/scm/io/docs/IoGuide.html#Embedding). Also it seems to provide some [C++ binding library](https://stackoverflow.com/a/3153987/12195)." +10262114,"I need to script my app (not a game) and I have a problem, choosing a script lang for this. +Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used. +Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib). +Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app. +So, I'd like to know is there a scripting lang, which satisfies this conditions: + +* unicode strings +* I can import C++ functions and then call them from +script +* Can be embedded to app (no dll's) without any problems + +Reinventing the wheel is not a good idea, so I don't want to develop my own lang. +Or there is a way to write unicode strings in Lua's source? Like in C++ L""Unicode string""",2012/04/21,"['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/']","There isn't really such a thing as a ""unicode string"". Strings are a sequence of bytes that can contain anything. Knowing the encoding of the data in the string matters, though. + +I use Lua with [UTF-8 strings](http://en.wikipedia.org/wiki/UTF-8), which just works for all the operations I care about. I do not use any Unicode string library, though those are available for Lua ([ICU4Lua](http://luaforge.net/projects/icu-lua/), [slnunicode](http://luaforge.net/projects/sln/), etc.). + +Some notes about using UTF-8 strings in Lua: + +* String length (# operator) returns the string length in bytes, not characters or codepoints (non-ASCII characters may be sequences of multiple bytes). +* String splitting (e.g. string.sub) must not split up UTF-8 sequences. +* String matching works (string.find, string.match) fine with ASCII patterns. +* Substring searching (such as string.find in 'plain' mode) works with UTF-8 as the needle or the haystack. + +Counting codepoints in UTF-8 is quite straightforward, if slightly less efficient than other encodings. For example in Lua: + +``` +function utf8_length(str) + return select(2, string.gsub(str, ""[^\128-\193]"", """")); +end + +``` + +If you need more than this kind of thing, the unicode libraries I mentioned give you APIs for everything, including conversion between encodings. + +Personally I prefer this straightforward approach to any of the languages that force a certain flavour of unicode on you (such as Javascript) or try and be clever by having multiple encodings built into the language (such as Python). In my experience they only cause headaches and performance bottlenecks. + +In any case, I think every developer should have a good basic understanding of how unicode works, and the principle differences between different encodings so that they can make the best choice about how to handle unicode in their application. + +For example if all your existing strings in your application are in a wide-char encoding, it would be much less convenient to use Lua as you would have to add a conversion to every string in and out of Lua. This is entirely possible, but if your app might be CPU-bound (as in a game) then it would be a negative point performance-wise.","Lua strings are encoding-agnostic. So, yes, you can write unicode strings in Lua scripts. If you need pattern matching, then the standard Lua string library does not support unicode classes. But plain substring search works." +10262114,"I need to script my app (not a game) and I have a problem, choosing a script lang for this. +Lua looks fine (actually, it is ideal for my task), but it has problems with unicode strings, which will be used. +Also, I thought about Python, but I don't like It's syntax, and it's Dll is too big for me ( about 2.5 Mib). +Python and other such langs have too much functions, battaries and modules which i do not need (e.g. I/O functions) - script just need to implement logic, all other will do my app. +So, I'd like to know is there a scripting lang, which satisfies this conditions: + +* unicode strings +* I can import C++ functions and then call them from +script +* Can be embedded to app (no dll's) without any problems + +Reinventing the wheel is not a good idea, so I don't want to develop my own lang. +Or there is a way to write unicode strings in Lua's source? Like in C++ L""Unicode string""",2012/04/21,"['https://Stackoverflow.com/questions/10262114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684275/']","Lua strings are encoding-agnostic. So, yes, you can write unicode strings in Lua scripts. If you need pattern matching, then the standard Lua string library does not support unicode classes. But plain substring search works.","Take look at [Jim Tcl](http://jim.tcl.tk). It's small, easily embeddable and extendable, supports UTF-8 strings, and it's pretty powerful"