qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
49,106 | I have a Hamilton Beach 6 qt Set 'N Forget Programmable slow cooker, and I keep having the same problem-- when I try to make beef stew, the beef comes out almost inedibly tough, and the veggies don't soften. I can't for the life of me figure out what's wrong!
My cooking method:
>
> Put in 1.5ish lbs stew beef-- the stuff that comes from the store
> already cut up into pieces.
>
>
> Add carrots and celery, chopped about 1/2 - 1 inch long.
>
>
> Add splash worsterchire sauce and cajun spices.
>
>
> Add enough water to fill the crock pot halfway (I did this because
> last time I didn't use as much and thought that might be the source of
> the problem-- but apparently not.)
>
>
> Set crock pot on low until it reaches 160\* (within about an hour and a half), and then leave on warm through the rest of the night (it maintained the temperature at 160\*),
> for a total of 11 hours.
>
>
>
I've read that acidic ingredients can prevent vegetables from getting soft, but that wouldn't explain the beef. Anyone have an idea what the problem might be?
And on that note... does anyone have any suggestions for what to do with a couple pounds of tough, cooked beef, hard carrots, and celery?
Thanks! | 2014/10/20 | [
"https://cooking.stackexchange.com/questions/49106",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/28794/"
] | I always leave my crocpot on low, not warm. The meat and potatoes are always tender. | Beef is generally a pretty hard meat to break down compared to other meats. Takes longer to chew, longer to digest, and requires more heat to make it tender during the cooking process. So while a crock pot is fine for most of the operation, you'll meet with the desired success if you'll instead braise your cut of beef in a covered pot (not a pan) on the stove top.
Make sure your pot is of the stainless steel variety, as you'll be going at it pretty aggressively with your metal spatula. And absolutely make sure it has a heavy bottom. Invariably they're a separate piece welded on to the lining of the pot. The bottom of the pot really needs to be able to hold and evenly distribute heat, which is simply not true for pots which by definition are bowl-shaped pieces of sheet metal. Remember, part of what the term "evenly distribute" means is that a balance is struck between the burner and the bottom of the pan. If that bottom is almost non-existent then there's no back-and-forth between the two. The heat just leaps straight from burner to food surface and makes it impossible to do much more than sauté or stir fry.
Add to the pot a thin layer of olive oil, thin meaning just a bit more than one sixteenth of an inch. Set the burner up in the range of medium high to high. (Not high, not medium high, but squarely in between those two.) Just before the oil reaches its smoke point drop in your piece of beef. Your goal is to sear the beef on that side, which will take about 80 seconds. (Do not apply additional pressure to the meat.) Even at that short of a time span it will want to stick to the bottom of the pan. You want to separate the two, but not at the expense of tearing the meat. (Otherwise there's no sense in searing it.) So flip your spatula over (underside facing the ceiling), slide it under an available lip, and then rock it from side to side while gradually pushing it further and further underneath the cut of beef. This means that the flat edge of the spatula retains contact with the bottom of the pot the whole time. Rocking, here, does not mean teetering.
Once the beef is loose, grab a pair of kitchen tongs and stand it up on one side (whichever side is most convenient). You're now going to sear that side. In fact, you're goal is to sear *each* side of the cut of meat. Generally that would be six sides: two broad, two narrow, and two ends. But trust me, this will make all the difference in outcome. The searing creates much more of a "closed system\*, by which the cut of meat is able to stew from the *inside out* rather, that is, than from the outside in. Stewing from the outside in is synonymous with boiling. Boiling beef draws all the moisture out and leaves behind a mass of tissue. So that's never what you want to do. You want to force the moisture to stay *in* the beef while it's cooking, at least as much as humanly possible. Searing makes that possible.
*Now* the meat needs to be braised. It's beef. It needs to be braised. You can accomplish this one of two ways. You can leave it in the pot you started with on your stove top. Or you can transfer it to your crock pot. If you do the latter though, it's imperative that you bring it's temperature way up first. Just add about a quarter cup of water (or beef stock) to it and bring that to a roiling boil. Yes, a quarter cup (not a misprint). Not only is this all you'll need, this is one of those situations where more is literally less. So if you're going to add Worcestershire sauce, make sure that's *part of* this quarter cup of liquid. Also, when you add the beef you'll want to make sure and include all of the oil (flavors) produced in the first step.
Now, if you're going with the standard stove top approach, while the heat's still up (as before) you just add that quarter cup of water and cover. You'll need a clear lid, because braising by definition entails just *barely* keeping things at a boil, in which case you'll be needing to *see* what's happening without *changing* what's happening. As steam rises and contacts the lid it eventually trickles back down and keeps the level the same. It's this equilibrium you're after. Meanwhile, as the meat slowly releases it's own juices, (emphasis on *slowly*), that added amount of liquid is sufficient to compensate for any incidental, low-level evaporation. Same thing with the crock pot. When you drop the meat in it'll temporarily stunt that roiling broil. Here's the time you should be cranking the dial down. Your goal, again, is to get it as low as possible without losing sight of slight movement in the water. And then your goal is to keep it that way.
There's no reason to expect this stage to take any less than a couple hours to accomplish, though closer to four is even better. Remember, the beef is being broken down. And I know from experience that patience at this stage reaps a huge dividend in tenderness. You won't have to cut the meat. Nor will anyone to whom you serve it. It'll simply pull right apart.
Now, the vegetables. Always add first the ones that take longest to cook. Remember, you're going to stay here with low temps (just enough to boil water). So *gauging* what you add (meaning when) can be a bit nuanced compared, that is, to just throwing everything in together into a high heat environment. I always go with celery first. Then carrots and onions. Then potatoes. (You may find it more practical to lightly oil your pieces of potato and then salt and pepper them *before* adding them to the stew.) And remember, this is the diametric opposite of stir fry. Once the braising process commences, at no point ever will you be doing any stirring. You just add what needs to be added, cover, and allow the process to bring itself to completion. The vegetables will release all of their water. You won't have to add any more. (If you do favor a particularly soupy stew, adding preheated beef stock should suffice, but no sooner than a half hour before serve time.)
With a half hour's prep work and searing, three hours braising, and a final hour to hour-and-a-half for the vegetables to slow cook, your stew should take about six hours to make. But this is not the kind of thing you can crank up like a machine and then come home to after a day at the office. A good stew has to be fussed over in a very present and very hands-on sort of way. A crock pot can work. But it's really just one more step in an already ample repertoire. |
49,106 | I have a Hamilton Beach 6 qt Set 'N Forget Programmable slow cooker, and I keep having the same problem-- when I try to make beef stew, the beef comes out almost inedibly tough, and the veggies don't soften. I can't for the life of me figure out what's wrong!
My cooking method:
>
> Put in 1.5ish lbs stew beef-- the stuff that comes from the store
> already cut up into pieces.
>
>
> Add carrots and celery, chopped about 1/2 - 1 inch long.
>
>
> Add splash worsterchire sauce and cajun spices.
>
>
> Add enough water to fill the crock pot halfway (I did this because
> last time I didn't use as much and thought that might be the source of
> the problem-- but apparently not.)
>
>
> Set crock pot on low until it reaches 160\* (within about an hour and a half), and then leave on warm through the rest of the night (it maintained the temperature at 160\*),
> for a total of 11 hours.
>
>
>
I've read that acidic ingredients can prevent vegetables from getting soft, but that wouldn't explain the beef. Anyone have an idea what the problem might be?
And on that note... does anyone have any suggestions for what to do with a couple pounds of tough, cooked beef, hard carrots, and celery?
Thanks! | 2014/10/20 | [
"https://cooking.stackexchange.com/questions/49106",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/28794/"
] | Start the pot on HIGH until it is all hot and bubbly to get it started, around 15 to 30 minutes while you are cleaning up the kitchen. Then turn to LOW to cook. The WARM setting it just to hold the meal until you are ready to serve the meal. WARM setting is designed to NOT COOK the meal. | Beef is generally a pretty hard meat to break down compared to other meats. Takes longer to chew, longer to digest, and requires more heat to make it tender during the cooking process. So while a crock pot is fine for most of the operation, you'll meet with the desired success if you'll instead braise your cut of beef in a covered pot (not a pan) on the stove top.
Make sure your pot is of the stainless steel variety, as you'll be going at it pretty aggressively with your metal spatula. And absolutely make sure it has a heavy bottom. Invariably they're a separate piece welded on to the lining of the pot. The bottom of the pot really needs to be able to hold and evenly distribute heat, which is simply not true for pots which by definition are bowl-shaped pieces of sheet metal. Remember, part of what the term "evenly distribute" means is that a balance is struck between the burner and the bottom of the pan. If that bottom is almost non-existent then there's no back-and-forth between the two. The heat just leaps straight from burner to food surface and makes it impossible to do much more than sauté or stir fry.
Add to the pot a thin layer of olive oil, thin meaning just a bit more than one sixteenth of an inch. Set the burner up in the range of medium high to high. (Not high, not medium high, but squarely in between those two.) Just before the oil reaches its smoke point drop in your piece of beef. Your goal is to sear the beef on that side, which will take about 80 seconds. (Do not apply additional pressure to the meat.) Even at that short of a time span it will want to stick to the bottom of the pan. You want to separate the two, but not at the expense of tearing the meat. (Otherwise there's no sense in searing it.) So flip your spatula over (underside facing the ceiling), slide it under an available lip, and then rock it from side to side while gradually pushing it further and further underneath the cut of beef. This means that the flat edge of the spatula retains contact with the bottom of the pot the whole time. Rocking, here, does not mean teetering.
Once the beef is loose, grab a pair of kitchen tongs and stand it up on one side (whichever side is most convenient). You're now going to sear that side. In fact, you're goal is to sear *each* side of the cut of meat. Generally that would be six sides: two broad, two narrow, and two ends. But trust me, this will make all the difference in outcome. The searing creates much more of a "closed system\*, by which the cut of meat is able to stew from the *inside out* rather, that is, than from the outside in. Stewing from the outside in is synonymous with boiling. Boiling beef draws all the moisture out and leaves behind a mass of tissue. So that's never what you want to do. You want to force the moisture to stay *in* the beef while it's cooking, at least as much as humanly possible. Searing makes that possible.
*Now* the meat needs to be braised. It's beef. It needs to be braised. You can accomplish this one of two ways. You can leave it in the pot you started with on your stove top. Or you can transfer it to your crock pot. If you do the latter though, it's imperative that you bring it's temperature way up first. Just add about a quarter cup of water (or beef stock) to it and bring that to a roiling boil. Yes, a quarter cup (not a misprint). Not only is this all you'll need, this is one of those situations where more is literally less. So if you're going to add Worcestershire sauce, make sure that's *part of* this quarter cup of liquid. Also, when you add the beef you'll want to make sure and include all of the oil (flavors) produced in the first step.
Now, if you're going with the standard stove top approach, while the heat's still up (as before) you just add that quarter cup of water and cover. You'll need a clear lid, because braising by definition entails just *barely* keeping things at a boil, in which case you'll be needing to *see* what's happening without *changing* what's happening. As steam rises and contacts the lid it eventually trickles back down and keeps the level the same. It's this equilibrium you're after. Meanwhile, as the meat slowly releases it's own juices, (emphasis on *slowly*), that added amount of liquid is sufficient to compensate for any incidental, low-level evaporation. Same thing with the crock pot. When you drop the meat in it'll temporarily stunt that roiling broil. Here's the time you should be cranking the dial down. Your goal, again, is to get it as low as possible without losing sight of slight movement in the water. And then your goal is to keep it that way.
There's no reason to expect this stage to take any less than a couple hours to accomplish, though closer to four is even better. Remember, the beef is being broken down. And I know from experience that patience at this stage reaps a huge dividend in tenderness. You won't have to cut the meat. Nor will anyone to whom you serve it. It'll simply pull right apart.
Now, the vegetables. Always add first the ones that take longest to cook. Remember, you're going to stay here with low temps (just enough to boil water). So *gauging* what you add (meaning when) can be a bit nuanced compared, that is, to just throwing everything in together into a high heat environment. I always go with celery first. Then carrots and onions. Then potatoes. (You may find it more practical to lightly oil your pieces of potato and then salt and pepper them *before* adding them to the stew.) And remember, this is the diametric opposite of stir fry. Once the braising process commences, at no point ever will you be doing any stirring. You just add what needs to be added, cover, and allow the process to bring itself to completion. The vegetables will release all of their water. You won't have to add any more. (If you do favor a particularly soupy stew, adding preheated beef stock should suffice, but no sooner than a half hour before serve time.)
With a half hour's prep work and searing, three hours braising, and a final hour to hour-and-a-half for the vegetables to slow cook, your stew should take about six hours to make. But this is not the kind of thing you can crank up like a machine and then come home to after a day at the office. A good stew has to be fussed over in a very present and very hands-on sort of way. A crock pot can work. But it's really just one more step in an already ample repertoire. |
30,946,625 | Im learning html & css and after few tutorials I decided to write webpage from nothing.
But I've got a problem. When I add *"display: inline"* in CSS **.nav**, it ignores all .**nav** css properties, including *"display: inline"*.
Here's code:
**HTML**
```
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet">
<title>Neni okurka, nebudou caciky</title>
</head>
<body>
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a></li>
<li><a href="#">Navigation 2</a></li>
<li><a href="#">Navigation 3</a></li>
<li><a href="#">Navigation 4</a></li>
<li><a href="#">Navigation 5</a></li>
</ul>
</div>
<div class="nav2">
<ul>
<li class="active"><a href="#">Navi 1</a></li>
<li><a href="#">Navi 2</a></li>
<li><a href="#">Navi 3</a></li>
<li><a href="#">Navi 4</a></li>
<li><a href="#">Navi 5</a></li>
</ul>
</div>
</body>
</html>
```
**CSS**
```
body {
background-image: url("background.png");
width: 1000px;
margin-left: auto;
margin-right: auto;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav {
display: inline;
width: 500px;
background: #fff;
}
``` | 2015/06/19 | [
"https://Stackoverflow.com/questions/30946625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5029670/"
] | The right usage is:
```
.nav li {
display: inline;
}
``` | You should put display: inline-block; |
30,946,625 | Im learning html & css and after few tutorials I decided to write webpage from nothing.
But I've got a problem. When I add *"display: inline"* in CSS **.nav**, it ignores all .**nav** css properties, including *"display: inline"*.
Here's code:
**HTML**
```
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet">
<title>Neni okurka, nebudou caciky</title>
</head>
<body>
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a></li>
<li><a href="#">Navigation 2</a></li>
<li><a href="#">Navigation 3</a></li>
<li><a href="#">Navigation 4</a></li>
<li><a href="#">Navigation 5</a></li>
</ul>
</div>
<div class="nav2">
<ul>
<li class="active"><a href="#">Navi 1</a></li>
<li><a href="#">Navi 2</a></li>
<li><a href="#">Navi 3</a></li>
<li><a href="#">Navi 4</a></li>
<li><a href="#">Navi 5</a></li>
</ul>
</div>
</body>
</html>
```
**CSS**
```
body {
background-image: url("background.png");
width: 1000px;
margin-left: auto;
margin-right: auto;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav {
display: inline;
width: 500px;
background: #fff;
}
``` | 2015/06/19 | [
"https://Stackoverflow.com/questions/30946625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5029670/"
] | You should put display: inline-block; | in orther to display betther ur nav thing u shuld not use .nav ul li `display:inline`
i know i say that was for answer ur question but this thing i will tell you will be betther
.nav ul li`float:left`
this will do the items in the li will float left and will do the same as the inline but isbetther to use that rather than the inline |
30,946,625 | Im learning html & css and after few tutorials I decided to write webpage from nothing.
But I've got a problem. When I add *"display: inline"* in CSS **.nav**, it ignores all .**nav** css properties, including *"display: inline"*.
Here's code:
**HTML**
```
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet">
<title>Neni okurka, nebudou caciky</title>
</head>
<body>
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a></li>
<li><a href="#">Navigation 2</a></li>
<li><a href="#">Navigation 3</a></li>
<li><a href="#">Navigation 4</a></li>
<li><a href="#">Navigation 5</a></li>
</ul>
</div>
<div class="nav2">
<ul>
<li class="active"><a href="#">Navi 1</a></li>
<li><a href="#">Navi 2</a></li>
<li><a href="#">Navi 3</a></li>
<li><a href="#">Navi 4</a></li>
<li><a href="#">Navi 5</a></li>
</ul>
</div>
</body>
</html>
```
**CSS**
```
body {
background-image: url("background.png");
width: 1000px;
margin-left: auto;
margin-right: auto;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav {
display: inline;
width: 500px;
background: #fff;
}
``` | 2015/06/19 | [
"https://Stackoverflow.com/questions/30946625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5029670/"
] | If you want `background(image)` you need to have it in the `container` as soon you give it `width` and `height` because `body` is the **"Base"** you can give it `margin: 0; padding: 0;` to reset it only and you can add `background` to it **but not** `height` and `width`. Inside `container`you have created you can play with the `height` and `width` as you like.
```css
html,
body {
margin: 0;
padding: 0;
background-color: cadetblue;
}
.container {
width: 1050px;
height: 100vh;
margin: 0 auto;
position: relative;
background-size: 100% 100%;
background: url("http://www.myfreetextures.com/wp-content/uploads/2013/07/free-grunge-texture-of-old-vintage-paper-background-image.jpg") no-repeat center;
}
.nav {
width: 1000px;
height: 50px;
margin: 0 auto;
background: beige;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav ul {
margin: 0;
padding: 0;
list-style-type: none;
}
.nav ul li {
margin-left: 12px;
}
.nav ul li a {
float: left;
font-size: 16px;
font-weight: lighter;
text-decoration: none;
font-family: sans-serif;
margin: 10px 0px 10px 0px;
padding: 8px 15px 8px 15px;
}
.nav ul li a:hover {
color: #fff;
border-radius: 3px;
background: cadetblue;
}
```
```html
<div class="container">
<div class="wrapper">
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a>
</li>
<li><a href="#">Navigation 2</a>
</li>
<li><a href="#">Navigation 3</a>
</li>
<li><a href="#">Navigation 4</a>
</li>
<li><a href="#">Navigation 5</a>
</li>
</ul>
<ul>
<li class="active"><a href="#">Navi 1</a>
</li>
<li><a href="#">Navi 2</a>
</li>
<li><a href="#">Navi 3</a>
</li>
<li><a href="#">Navi 4</a>
</li>
<li><a href="#">Navi 5</a>
</li>
</ul>
</div>
</div>
</div>
```
>
> this code without `display:inline;` or `display :inline-block;` which
> it works but it's another way to align nabbar in nice way compatible
> with all browsers too.
>
>
>
I hope you like it and it helps you, let me know if you have another question. | You should put display: inline-block; |
30,946,625 | Im learning html & css and after few tutorials I decided to write webpage from nothing.
But I've got a problem. When I add *"display: inline"* in CSS **.nav**, it ignores all .**nav** css properties, including *"display: inline"*.
Here's code:
**HTML**
```
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet">
<title>Neni okurka, nebudou caciky</title>
</head>
<body>
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a></li>
<li><a href="#">Navigation 2</a></li>
<li><a href="#">Navigation 3</a></li>
<li><a href="#">Navigation 4</a></li>
<li><a href="#">Navigation 5</a></li>
</ul>
</div>
<div class="nav2">
<ul>
<li class="active"><a href="#">Navi 1</a></li>
<li><a href="#">Navi 2</a></li>
<li><a href="#">Navi 3</a></li>
<li><a href="#">Navi 4</a></li>
<li><a href="#">Navi 5</a></li>
</ul>
</div>
</body>
</html>
```
**CSS**
```
body {
background-image: url("background.png");
width: 1000px;
margin-left: auto;
margin-right: auto;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav {
display: inline;
width: 500px;
background: #fff;
}
``` | 2015/06/19 | [
"https://Stackoverflow.com/questions/30946625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5029670/"
] | The right usage is:
```
.nav li {
display: inline;
}
``` | Man try to put .nav ul lit to refer to the li but I will not use that let me tell you now one sec
```
.nav ul li`display:inline`
``` |
30,946,625 | Im learning html & css and after few tutorials I decided to write webpage from nothing.
But I've got a problem. When I add *"display: inline"* in CSS **.nav**, it ignores all .**nav** css properties, including *"display: inline"*.
Here's code:
**HTML**
```
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet">
<title>Neni okurka, nebudou caciky</title>
</head>
<body>
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a></li>
<li><a href="#">Navigation 2</a></li>
<li><a href="#">Navigation 3</a></li>
<li><a href="#">Navigation 4</a></li>
<li><a href="#">Navigation 5</a></li>
</ul>
</div>
<div class="nav2">
<ul>
<li class="active"><a href="#">Navi 1</a></li>
<li><a href="#">Navi 2</a></li>
<li><a href="#">Navi 3</a></li>
<li><a href="#">Navi 4</a></li>
<li><a href="#">Navi 5</a></li>
</ul>
</div>
</body>
</html>
```
**CSS**
```
body {
background-image: url("background.png");
width: 1000px;
margin-left: auto;
margin-right: auto;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav {
display: inline;
width: 500px;
background: #fff;
}
``` | 2015/06/19 | [
"https://Stackoverflow.com/questions/30946625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5029670/"
] | Man try to put .nav ul lit to refer to the li but I will not use that let me tell you now one sec
```
.nav ul li`display:inline`
``` | in orther to display betther ur nav thing u shuld not use .nav ul li `display:inline`
i know i say that was for answer ur question but this thing i will tell you will be betther
.nav ul li`float:left`
this will do the items in the li will float left and will do the same as the inline but isbetther to use that rather than the inline |
30,946,625 | Im learning html & css and after few tutorials I decided to write webpage from nothing.
But I've got a problem. When I add *"display: inline"* in CSS **.nav**, it ignores all .**nav** css properties, including *"display: inline"*.
Here's code:
**HTML**
```
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet">
<title>Neni okurka, nebudou caciky</title>
</head>
<body>
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a></li>
<li><a href="#">Navigation 2</a></li>
<li><a href="#">Navigation 3</a></li>
<li><a href="#">Navigation 4</a></li>
<li><a href="#">Navigation 5</a></li>
</ul>
</div>
<div class="nav2">
<ul>
<li class="active"><a href="#">Navi 1</a></li>
<li><a href="#">Navi 2</a></li>
<li><a href="#">Navi 3</a></li>
<li><a href="#">Navi 4</a></li>
<li><a href="#">Navi 5</a></li>
</ul>
</div>
</body>
</html>
```
**CSS**
```
body {
background-image: url("background.png");
width: 1000px;
margin-left: auto;
margin-right: auto;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav {
display: inline;
width: 500px;
background: #fff;
}
``` | 2015/06/19 | [
"https://Stackoverflow.com/questions/30946625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5029670/"
] | If you want `background(image)` you need to have it in the `container` as soon you give it `width` and `height` because `body` is the **"Base"** you can give it `margin: 0; padding: 0;` to reset it only and you can add `background` to it **but not** `height` and `width`. Inside `container`you have created you can play with the `height` and `width` as you like.
```css
html,
body {
margin: 0;
padding: 0;
background-color: cadetblue;
}
.container {
width: 1050px;
height: 100vh;
margin: 0 auto;
position: relative;
background-size: 100% 100%;
background: url("http://www.myfreetextures.com/wp-content/uploads/2013/07/free-grunge-texture-of-old-vintage-paper-background-image.jpg") no-repeat center;
}
.nav {
width: 1000px;
height: 50px;
margin: 0 auto;
background: beige;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav ul {
margin: 0;
padding: 0;
list-style-type: none;
}
.nav ul li {
margin-left: 12px;
}
.nav ul li a {
float: left;
font-size: 16px;
font-weight: lighter;
text-decoration: none;
font-family: sans-serif;
margin: 10px 0px 10px 0px;
padding: 8px 15px 8px 15px;
}
.nav ul li a:hover {
color: #fff;
border-radius: 3px;
background: cadetblue;
}
```
```html
<div class="container">
<div class="wrapper">
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a>
</li>
<li><a href="#">Navigation 2</a>
</li>
<li><a href="#">Navigation 3</a>
</li>
<li><a href="#">Navigation 4</a>
</li>
<li><a href="#">Navigation 5</a>
</li>
</ul>
<ul>
<li class="active"><a href="#">Navi 1</a>
</li>
<li><a href="#">Navi 2</a>
</li>
<li><a href="#">Navi 3</a>
</li>
<li><a href="#">Navi 4</a>
</li>
<li><a href="#">Navi 5</a>
</li>
</ul>
</div>
</div>
</div>
```
>
> this code without `display:inline;` or `display :inline-block;` which
> it works but it's another way to align nabbar in nice way compatible
> with all browsers too.
>
>
>
I hope you like it and it helps you, let me know if you have another question. | Man try to put .nav ul lit to refer to the li but I will not use that let me tell you now one sec
```
.nav ul li`display:inline`
``` |
30,946,625 | Im learning html & css and after few tutorials I decided to write webpage from nothing.
But I've got a problem. When I add *"display: inline"* in CSS **.nav**, it ignores all .**nav** css properties, including *"display: inline"*.
Here's code:
**HTML**
```
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet">
<title>Neni okurka, nebudou caciky</title>
</head>
<body>
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a></li>
<li><a href="#">Navigation 2</a></li>
<li><a href="#">Navigation 3</a></li>
<li><a href="#">Navigation 4</a></li>
<li><a href="#">Navigation 5</a></li>
</ul>
</div>
<div class="nav2">
<ul>
<li class="active"><a href="#">Navi 1</a></li>
<li><a href="#">Navi 2</a></li>
<li><a href="#">Navi 3</a></li>
<li><a href="#">Navi 4</a></li>
<li><a href="#">Navi 5</a></li>
</ul>
</div>
</body>
</html>
```
**CSS**
```
body {
background-image: url("background.png");
width: 1000px;
margin-left: auto;
margin-right: auto;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav {
display: inline;
width: 500px;
background: #fff;
}
``` | 2015/06/19 | [
"https://Stackoverflow.com/questions/30946625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5029670/"
] | The right usage is:
```
.nav li {
display: inline;
}
``` | in orther to display betther ur nav thing u shuld not use .nav ul li `display:inline`
i know i say that was for answer ur question but this thing i will tell you will be betther
.nav ul li`float:left`
this will do the items in the li will float left and will do the same as the inline but isbetther to use that rather than the inline |
30,946,625 | Im learning html & css and after few tutorials I decided to write webpage from nothing.
But I've got a problem. When I add *"display: inline"* in CSS **.nav**, it ignores all .**nav** css properties, including *"display: inline"*.
Here's code:
**HTML**
```
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet">
<title>Neni okurka, nebudou caciky</title>
</head>
<body>
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a></li>
<li><a href="#">Navigation 2</a></li>
<li><a href="#">Navigation 3</a></li>
<li><a href="#">Navigation 4</a></li>
<li><a href="#">Navigation 5</a></li>
</ul>
</div>
<div class="nav2">
<ul>
<li class="active"><a href="#">Navi 1</a></li>
<li><a href="#">Navi 2</a></li>
<li><a href="#">Navi 3</a></li>
<li><a href="#">Navi 4</a></li>
<li><a href="#">Navi 5</a></li>
</ul>
</div>
</body>
</html>
```
**CSS**
```
body {
background-image: url("background.png");
width: 1000px;
margin-left: auto;
margin-right: auto;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav {
display: inline;
width: 500px;
background: #fff;
}
``` | 2015/06/19 | [
"https://Stackoverflow.com/questions/30946625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5029670/"
] | If you want `background(image)` you need to have it in the `container` as soon you give it `width` and `height` because `body` is the **"Base"** you can give it `margin: 0; padding: 0;` to reset it only and you can add `background` to it **but not** `height` and `width`. Inside `container`you have created you can play with the `height` and `width` as you like.
```css
html,
body {
margin: 0;
padding: 0;
background-color: cadetblue;
}
.container {
width: 1050px;
height: 100vh;
margin: 0 auto;
position: relative;
background-size: 100% 100%;
background: url("http://www.myfreetextures.com/wp-content/uploads/2013/07/free-grunge-texture-of-old-vintage-paper-background-image.jpg") no-repeat center;
}
.nav {
width: 1000px;
height: 50px;
margin: 0 auto;
background: beige;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav ul {
margin: 0;
padding: 0;
list-style-type: none;
}
.nav ul li {
margin-left: 12px;
}
.nav ul li a {
float: left;
font-size: 16px;
font-weight: lighter;
text-decoration: none;
font-family: sans-serif;
margin: 10px 0px 10px 0px;
padding: 8px 15px 8px 15px;
}
.nav ul li a:hover {
color: #fff;
border-radius: 3px;
background: cadetblue;
}
```
```html
<div class="container">
<div class="wrapper">
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a>
</li>
<li><a href="#">Navigation 2</a>
</li>
<li><a href="#">Navigation 3</a>
</li>
<li><a href="#">Navigation 4</a>
</li>
<li><a href="#">Navigation 5</a>
</li>
</ul>
<ul>
<li class="active"><a href="#">Navi 1</a>
</li>
<li><a href="#">Navi 2</a>
</li>
<li><a href="#">Navi 3</a>
</li>
<li><a href="#">Navi 4</a>
</li>
<li><a href="#">Navi 5</a>
</li>
</ul>
</div>
</div>
</div>
```
>
> this code without `display:inline;` or `display :inline-block;` which
> it works but it's another way to align nabbar in nice way compatible
> with all browsers too.
>
>
>
I hope you like it and it helps you, let me know if you have another question. | The right usage is:
```
.nav li {
display: inline;
}
``` |
30,946,625 | Im learning html & css and after few tutorials I decided to write webpage from nothing.
But I've got a problem. When I add *"display: inline"* in CSS **.nav**, it ignores all .**nav** css properties, including *"display: inline"*.
Here's code:
**HTML**
```
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet">
<title>Neni okurka, nebudou caciky</title>
</head>
<body>
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a></li>
<li><a href="#">Navigation 2</a></li>
<li><a href="#">Navigation 3</a></li>
<li><a href="#">Navigation 4</a></li>
<li><a href="#">Navigation 5</a></li>
</ul>
</div>
<div class="nav2">
<ul>
<li class="active"><a href="#">Navi 1</a></li>
<li><a href="#">Navi 2</a></li>
<li><a href="#">Navi 3</a></li>
<li><a href="#">Navi 4</a></li>
<li><a href="#">Navi 5</a></li>
</ul>
</div>
</body>
</html>
```
**CSS**
```
body {
background-image: url("background.png");
width: 1000px;
margin-left: auto;
margin-right: auto;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav {
display: inline;
width: 500px;
background: #fff;
}
``` | 2015/06/19 | [
"https://Stackoverflow.com/questions/30946625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5029670/"
] | If you want `background(image)` you need to have it in the `container` as soon you give it `width` and `height` because `body` is the **"Base"** you can give it `margin: 0; padding: 0;` to reset it only and you can add `background` to it **but not** `height` and `width`. Inside `container`you have created you can play with the `height` and `width` as you like.
```css
html,
body {
margin: 0;
padding: 0;
background-color: cadetblue;
}
.container {
width: 1050px;
height: 100vh;
margin: 0 auto;
position: relative;
background-size: 100% 100%;
background: url("http://www.myfreetextures.com/wp-content/uploads/2013/07/free-grunge-texture-of-old-vintage-paper-background-image.jpg") no-repeat center;
}
.nav {
width: 1000px;
height: 50px;
margin: 0 auto;
background: beige;
border: 25px solid rgba(0, 0, 0, 0.3);
}
.nav ul {
margin: 0;
padding: 0;
list-style-type: none;
}
.nav ul li {
margin-left: 12px;
}
.nav ul li a {
float: left;
font-size: 16px;
font-weight: lighter;
text-decoration: none;
font-family: sans-serif;
margin: 10px 0px 10px 0px;
padding: 8px 15px 8px 15px;
}
.nav ul li a:hover {
color: #fff;
border-radius: 3px;
background: cadetblue;
}
```
```html
<div class="container">
<div class="wrapper">
<div class="nav">
<ul>
<li class="active"><a href="#">Navigation 1</a>
</li>
<li><a href="#">Navigation 2</a>
</li>
<li><a href="#">Navigation 3</a>
</li>
<li><a href="#">Navigation 4</a>
</li>
<li><a href="#">Navigation 5</a>
</li>
</ul>
<ul>
<li class="active"><a href="#">Navi 1</a>
</li>
<li><a href="#">Navi 2</a>
</li>
<li><a href="#">Navi 3</a>
</li>
<li><a href="#">Navi 4</a>
</li>
<li><a href="#">Navi 5</a>
</li>
</ul>
</div>
</div>
</div>
```
>
> this code without `display:inline;` or `display :inline-block;` which
> it works but it's another way to align nabbar in nice way compatible
> with all browsers too.
>
>
>
I hope you like it and it helps you, let me know if you have another question. | in orther to display betther ur nav thing u shuld not use .nav ul li `display:inline`
i know i say that was for answer ur question but this thing i will tell you will be betther
.nav ul li`float:left`
this will do the items in the li will float left and will do the same as the inline but isbetther to use that rather than the inline |
61,593,505 | I know this goes against all DB normalization principals but I cannot change the design at this point.
I have a column that has values stored like this (SQL Server database):
```
5;26;31;49
```
There's another table that has translation for this values which looks like this:
```
Code Value
-------------------
5 Some Value 1
26 Some Value 2
31 Some Value 3
49 Some Value 4
```
I need to convert the semi-colon delimited codes into their corresponding values and present these values as part of just 1 row, so what I want to see as a result is:
```
Some Value 1; Some Value 2; Some Value 3; Some Value 4
```
Does anyone have a solution for this puzzle?
Thanks. | 2020/05/04 | [
"https://Stackoverflow.com/questions/61593505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1392848/"
] | this is the syntax.. use it as appropriate in you code:
```
mTextInputLayout.getEditText().setText("ur text");
```
and
```
mTextInputLayout.getEditText().getText()
``` | Example:
```
TextInputEditText inpedit_txt;
inpedit_txt = (TextInputEditText)findViewById(R.id.id_of_input_edit_text);
inpedit_txt.setText(String.valueOf("you Text"))
``` |
3,428,966 | is there any shortcut key to do this? | 2010/08/07 | [
"https://Stackoverflow.com/questions/3428966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] | `Ctrl` + `Shift` + `.` to zoom in and `Ctrl` + `Shift` + `,` to zoom out.
You can get download the shortcut posters [here](http://www.microsoft.com/downloads/details.aspx?FamilyID=92CED922-D505-457A-8C9C-84036160639F&displaylang=en) | In my install, I find that I have to head in through Tools -> Options -> Environment -> Keyboard and map "View.ZoomIn" and "View.ZoomOut" to get this working. This could be because ReSharper has modified my keyboard shortcuts, however. |
54,224,669 | I'm trying to extend the property decorator to my own needs, but I don't know how to access the attributes and methods in the extended property
```
class myproperty(property):
def __init__(self, tooltip, cls_name,
fget=None, fset=None, fdel=None, doc=None, **kwargs ):
super().__init__(fget=fget, fset=fset, fdel=fdel, doc=doc)
self._name = ''
self._value = ''
self._cls_name = None # name of GUI object to be used
self._datatype = None
self._tooltip = tooltip
self._cls_name = cls_name
self._kwargs = dict(**kwargs)
def __get__(self, *args, **kwargs):
return self._datatype(self._value)
def __set__(self, instance, value):
self._value = value
print(f'setting {value}')
def __call__(self, f):
self._value = f(self)
self._datatype= type(self._value )
self._name = f.__name__
return self
def get_membervalues(self):
return {'name': self._name, 'cls_name': self._cls_name, 'tooltip': self._tooltip}
```
I can use the property:
```
class myclass():
@myproperty(tooltip='help', cls_name='AnotherClass')
def data(self): return 4
```
And it seems to work internally
```
a = myclass()
print(a.data) # prints out 4, __get__() is called
a.data = "10" # __set__ is called correctly
print(a.data) # prints out 10 correctly
print(type(a.data)) # prints out "int" which is correct
a.get_memvervalues() # this does not work
```
How do I access the method "get\_memvervalues" or the attributes \_name, \_tooltip etc?
Ive tried with inspect and to cast it but have not yet succeeded.
Bonus question: When the def **call**(self, f) function is called I get the function pointer to 'data' in myclass. How do I extract the name of the class from that function pointer? | 2019/01/16 | [
"https://Stackoverflow.com/questions/54224669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7725690/"
] | You need a mask:
```
# Set a default value
data['rwasted'] = data['republican'] - data['votestowin']
# Find where it is different
mask = data['democrat'] >= data['republican']
# Set those rows to another value
data['rwasted'][mask] = data['republican']
```
No if-else statement needed, *no* for loop needed either. You have to think row- and column-wise with DataFrames, not cell-like. | `.all()` is a function that applies to an entire `Series`, not a single `row`. You are mixing concepts here. To do a row-by-row comparison (as you want to do):
```
myseries = []
for idx, row in data.iterrows():
if row['democrat'] >= row['republican']:
myseries.append(row['republican'])
else:
myseries.append(row['republican'] - row['votestowin'])
data['rwasted'] = pd.Series(myseries)
```
See @9769953's answer for a more concise way to apply it in the dataframe, but this is the analogue to your `iterrows` approach |
34,336,122 | I am creating a regex for controlling the attacks to my website.I am using regex to compare the parameters that it should not contain the word 'script' in it and also should not have special character curly braces `{ and }`.
So using the java pattern matcher adding the regex I am not able to reject this param value
```
indices.jsp--><script>alert(1)</script>
```
regex I am using
```
(?=^[\x26\x3c\x3e:a-zA-Z0-9_\s.\-\/@+* \^(),~%]+$)(?!script)|^$
``` | 2015/12/17 | [
"https://Stackoverflow.com/questions/34336122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1729522/"
] | Alternatively, you can think of the problem the other way.
Instead of focusing on ***what you don't want***, focus ***on what you want***.
### What are the valid values for the param?
* Find the response to this question
* Build a regex pattern that will match the valid values only.
Thus, any invalid value will be automatically rejected. | Instead of trying to prevent the input of harmful parameters, you should try to make sure that their output doesn't happen in an unpredictable way.
Since you can use URL encoding and other tricks to get `<script>` to the server, you should be making sure that everywhere you're displaying data that has been input by the user, the output has been properly escaped or encoded.
Instead of the output being `<script>`, it should be `<script>` which will display properly to the user, but the browser won't try to execute it. If you look at this page's source, you'll see that's the way it works.
Obviously you shouldn't attempt to do this by hand. Most view technologies have a simple way of automatically performing the escape (it can even be on by default). JSTL's `c:out` does this automatically, but if you're writing raw JSP you'll need to do the `<` -> `<` manually. |
17,717,623 | The content of `a.txt` : `ba.txt`
When I type `cat a.txt | xargs vi`, vi open the `ba.txt` and everything seems to be OK...
But when I exit the vi, I find my bash is abnormal..I can't see the instructions I type in. I typed `ls`. I can't see it, but when I press the enter, the result is displayed(in a strange way..)...(After typed `ls`,I typed `ll`. There are some Chinese characters,please ignore it ).. And the bash is like this:

Could anybody explain this? | 2013/07/18 | [
"https://Stackoverflow.com/questions/17717623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1291716/"
] | Your `bash` shell is not destroyed. It is just that your terminal is in some bad state -because you sent strange bytes to it- (a terminal has some state -and the terminal emulator and the kernel manage that state, which persists after the process having wrongly changed it. See e.g. the [stty(1)](http://man7.org/linux/man-pages/man1/stty.1.html) command, the [tty(4)](http://man7.org/linux/man-pages/man4/tty.4.html) man page about `/dev/tty`, and the [isatty(3)](http://man7.org/linux/man-pages/man3/isatty.3.html) function). Type (perhaps blindly) the `reset` command (or `stty sane`) to reset the terminal.
Most terminals respond to [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) (for ugly details, read about [termcap(5)](http://man7.org/linux/man-pages/man5/termcap.5.html) which is related to configuring these escape codes). A command sending arbitrary -or random- bytes may happen to send some escape sequences which might damage the behavior of your terminal.
However, your use of `vi` is probably wrong. For programmable edition, consider using [sed(1)](http://man7.org/linux/man-pages/man1/sed.1.html) or [ed(1)](http://linux.about.com/library/cmd/blcmdl1_ed.htm); or perhaps `emacs --batch` ....
If you just want to edit the file `ba.txt` named by the line inside `a.txt` you could just run:
```
vi $(cat a.txt)
```
or better yet, using the standard `EDITOR` variable (see [environ(7)](http://man7.org/linux/man-pages/man7/environ.7.html))
```
$EDITOR $(cat a.txt)
```
Read also the [Advanced Bash Scripting Guide](http://www.tldp.org/LDP/abs/html/). You might use backquotes, see [this answer](https://stackoverflow.com/a/17715005/841108), but I don't recommend using them.
---
For historical reasons, terminals emulate [tty](http://www.linusakesson.net/programming/tty/)-s (follow that link, it explains a lot), which were incredibly complex and arcane physical devices. You are probably too young to have seen them (outside of a museum). I worked on some, as a teenager, in the 1970s. It was incredibly fun and noisy - a sort of electromechanical communicating typewriter.
Jesus, I'm getting old, no one know today what a typewriter really is.... | If vi/vim is invoked from inside the pipeline, the `stdin` is connected to the previous pipeline's output, not the terminal. vi/vim is an interactive command, that needs to receive its input from the terminal (tty).
**Bottomline:** You can't pipe to xargs vim, since vim expects input to come from an **interactive terminal**.
If you closely at your terminal you will note vi/vim writing this:
>
> Vim: Warning: Input is not from a terminal
>
>
>
**PS:** You can use:
```
cat file | xargs vim -Nu NONE
```
To avoid this and make vi/vim non-interactive. |
17,717,623 | The content of `a.txt` : `ba.txt`
When I type `cat a.txt | xargs vi`, vi open the `ba.txt` and everything seems to be OK...
But when I exit the vi, I find my bash is abnormal..I can't see the instructions I type in. I typed `ls`. I can't see it, but when I press the enter, the result is displayed(in a strange way..)...(After typed `ls`,I typed `ll`. There are some Chinese characters,please ignore it ).. And the bash is like this:

Could anybody explain this? | 2013/07/18 | [
"https://Stackoverflow.com/questions/17717623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1291716/"
] | Your `bash` shell is not destroyed. It is just that your terminal is in some bad state -because you sent strange bytes to it- (a terminal has some state -and the terminal emulator and the kernel manage that state, which persists after the process having wrongly changed it. See e.g. the [stty(1)](http://man7.org/linux/man-pages/man1/stty.1.html) command, the [tty(4)](http://man7.org/linux/man-pages/man4/tty.4.html) man page about `/dev/tty`, and the [isatty(3)](http://man7.org/linux/man-pages/man3/isatty.3.html) function). Type (perhaps blindly) the `reset` command (or `stty sane`) to reset the terminal.
Most terminals respond to [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) (for ugly details, read about [termcap(5)](http://man7.org/linux/man-pages/man5/termcap.5.html) which is related to configuring these escape codes). A command sending arbitrary -or random- bytes may happen to send some escape sequences which might damage the behavior of your terminal.
However, your use of `vi` is probably wrong. For programmable edition, consider using [sed(1)](http://man7.org/linux/man-pages/man1/sed.1.html) or [ed(1)](http://linux.about.com/library/cmd/blcmdl1_ed.htm); or perhaps `emacs --batch` ....
If you just want to edit the file `ba.txt` named by the line inside `a.txt` you could just run:
```
vi $(cat a.txt)
```
or better yet, using the standard `EDITOR` variable (see [environ(7)](http://man7.org/linux/man-pages/man7/environ.7.html))
```
$EDITOR $(cat a.txt)
```
Read also the [Advanced Bash Scripting Guide](http://www.tldp.org/LDP/abs/html/). You might use backquotes, see [this answer](https://stackoverflow.com/a/17715005/841108), but I don't recommend using them.
---
For historical reasons, terminals emulate [tty](http://www.linusakesson.net/programming/tty/)-s (follow that link, it explains a lot), which were incredibly complex and arcane physical devices. You are probably too young to have seen them (outside of a museum). I worked on some, as a teenager, in the 1970s. It was incredibly fun and noisy - a sort of electromechanical communicating typewriter.
Jesus, I'm getting old, no one know today what a typewriter really is.... | I think Basile's answer explained well for the reason of why your terminal gets screwed up. also he gave a solution `stty sane`.
When I want to open files as result of `find, grep -l ...(in your case, the cat too)` I do:
```
vim $(find . ...)
```
you could try:
```
vim $(cat a.txt)
```
Zhu Ni Hao Yun. :) |
17,717,623 | The content of `a.txt` : `ba.txt`
When I type `cat a.txt | xargs vi`, vi open the `ba.txt` and everything seems to be OK...
But when I exit the vi, I find my bash is abnormal..I can't see the instructions I type in. I typed `ls`. I can't see it, but when I press the enter, the result is displayed(in a strange way..)...(After typed `ls`,I typed `ll`. There are some Chinese characters,please ignore it ).. And the bash is like this:

Could anybody explain this? | 2013/07/18 | [
"https://Stackoverflow.com/questions/17717623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1291716/"
] | If vi/vim is invoked from inside the pipeline, the `stdin` is connected to the previous pipeline's output, not the terminal. vi/vim is an interactive command, that needs to receive its input from the terminal (tty).
**Bottomline:** You can't pipe to xargs vim, since vim expects input to come from an **interactive terminal**.
If you closely at your terminal you will note vi/vim writing this:
>
> Vim: Warning: Input is not from a terminal
>
>
>
**PS:** You can use:
```
cat file | xargs vim -Nu NONE
```
To avoid this and make vi/vim non-interactive. | I think Basile's answer explained well for the reason of why your terminal gets screwed up. also he gave a solution `stty sane`.
When I want to open files as result of `find, grep -l ...(in your case, the cat too)` I do:
```
vim $(find . ...)
```
you could try:
```
vim $(cat a.txt)
```
Zhu Ni Hao Yun. :) |
270,383 | I have my KVM guests on a standard br0 bridge setup:
```
auto br0
iface br0 inet static
address 192.168.1.117
netmask 255.255.255.0
network 192.168.1.1
broadcast 192.168.1.225
gateway 192.168.1.1
bridge_ports eth0
bridge_stp off
bridge_fd 0
auto eth1
iface eth1 inet static
address 10.0.0.117
netmask 255.255.255.0
gateway 10.0.0.1
broadcast 10.0.0.225
```
eth1 is reserved for other traffic but a guest could simply change it's ip to connect to it.
What I am trying to achieve is dropping *all* traffic towards the host / outside / other guest as soon as a guest attempts to change *either* it's ip address or mac address (in an attempt to join the other network / spoof another guest)
I tried many interfaces (eth0, br0, tap0, tap+) but I cannot seem to get my rule right:
```
iptables -A INPUT -m physdev --physdev-in tap+ --physdev-out tap+ -s 192.168.1.205 -m mac ! --mac-source 52:54:5a:8d:77:8e -j DROP
```
IP forwarding is enabled- there are no other rules in iptables.
Am I missing something- or even should I consider try to achieve this another way? | 2011/05/17 | [
"https://serverfault.com/questions/270383",
"https://serverfault.com",
"https://serverfault.com/users/46688/"
] | I tried to make a template for the simple set of iptables rules for your problem, try this out:
```
iptables -t filter -A FORWARD -m physdev --physdev-in $LINK_FOR_THE_VM --physdev-is-bridged -j ${VMID}-out
iptables -t filter -A ${VMID}-out -m mac ! --mac-source $MAC_ADDR_FOR_THE_VIRTUAL_NIC -j DROP
iptables -t filter -A ${VMID}-out -s 0.0.0.0/32 -d 255.255.255.255/32 -p udp -m udp --sport 68 --dport 67 -j ACCEPT
iptables -t filter -A ${VMID}-out ! -s $PERMITTED_IP_ADDR_FOR_THE_VM -j DROP
iptables -t filter -A ${VMID}-out -j RETURN
```
Here is an example:
```
iptables -t filter -A FORWARD -m physdev --physdev-in vm10 --physdev-is-bridged -j 10-out
iptables -t filter -A 10-out -m mac ! --mac-source 52:54:5a:8d:77:8e -j DROP
iptables -t filter -A 10-out -s 0.0.0.0/32 -d 255.255.255.255/32 -p udp -m udp --sport 68 --dport 67 -j ACCEPT
iptables -t filter -A 10-out ! -s 192.168.1.205 -j DROP
iptables -t filter -A 10-out -j RETURN
``` | As far as I can see you just can't do some of the things you need to do with iptables. You need filtering at the bridge level. You should probably take a look at [ebtables](http://ebtables.sourceforge.net/) - it's like iptables for bridges.
Manual: <http://ebtables.sourceforge.net/misc/ebtables-man.html> |
51,605,831 | I'm trying to save my data where I get the data from JSON and I want to save it for login activity. In login activity I want it to check if the data exist so it no need to login anymore. So I using `SharedPreferences` to save the data but I don't know it saved or not because I can't track it if the app terminated. But it suddenly intent itself before I put some data on it.
This is my code where I get the data from JSON and save it to `sharedpreferences`.
```
String jsonData = response.body().string();
JSONObject object = new JSONObject(jsonData);
token = object.getString("access_token");
Log.d("isi token", "" + token);
if (response.code() == 200) {
runOnUiThread(new Runnable() {
@Override
public void run() {
new userData().execute();
SharedPreferences sharedPreferences = getSharedPreferences("userToken", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("token", token);
editor.commit();
Intent intent = new Intent(LoginActivity.this, JudulActivity.class);
startActivity(intent);
}
});
}
```
and this is my data where I retrieve the data from `sharedpreferences` and want to make the logic to login if the token null so it will not intent. but it intent before I call the JSON.
```
Log.d("token", "" + token2);
SharedPreferences sharedPreferences = getSharedPreferences("userToken", Context.MODE_PRIVATE);
token2 = sharedPreferences.getString("token", "");
Log.d("token2", "" + token2);
if (token2 == null) {
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
nameS = username.getText().toString();
passS = password.getText().toString();
if (nameS.isEmpty()) username.setError("Username belum diisi");
else if (passS.isEmpty()) password.setError("Password belum diisi");
else {
new login().execute();
}
}
});
} else {
Intent intent = new Intent(LoginActivity.this, JudulActivity.class);
startActivity(intent);
}
```
The Log.d in the token is null but in token2 nothings happen, please help how to make it right. | 2018/07/31 | [
"https://Stackoverflow.com/questions/51605831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9823690/"
] | ```
token2 = sharedPreferences.getString("token", "");
```
it will get default value `""` so it not be null for that you have to try this
```
if(TextUtils.isEmpty(token2)){
// your code
}
``` | **Write to shared preferences**
To write to a shared preferences file, create a SharedPreferences.Editor by calling edit() on your SharedPreferences.
Pass the keys and values you want to write with methods such as `putInt()` and putString(). Then call `apply()` or `commit()` to save the changes. For example:
```
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score_key), newHighScore);
editor.commit();
```
**Read from shared preferences**
To retrieve values from a shared preferences file, call methods such as `getInt()` and `getString()`, providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:
```
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.integer.saved_high_score_default_key);
int highScore = sharedPref.getInt(getString(R.string.saved_high_score_key), defaultValue);
``` |
7,043,761 | We have a Grails (1.3.7) application deployed to 2 web servers that are sitting behind a load balancer. The problem we're seeing is that when we modify the RequestMaps the springSecurityService.clearCachedRequestmaps() only gets called on whatever server the user has a session to at that time. So that cache isn't getting reset on the other server.
This causes issues when logging in with a connection to the other server and not having the correct permissions because of bad request map cache. What is the right thing to do here?
One thought is to have a quartz job running that clears the cache every, say, 5 minutes. But I'm not sure that is optimal. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7043761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261159/"
] | Fundamentally, you want a `CompositeEditor` to handle cases where objects are dynamically added or removed from the Editor hierarchy. The `ListEditor` and `OptionalFieldEditor` adaptors implement `CompositeEditor`.
If the information required for the different types of questions is fundamentally orthogonal, then multiple `OptionalFieldEditor` could be used with different fields, one for each question type. This will work when you have only a few question types, but won't really scale well in the future.
A different approach, that will scale better would be to use a custom implementation of a `CompositeEditor + LeafValueEditor` that handles a polymorphic `QuestionData` type hierarchy. The type drop-down UI element would become an implementation detail of the `CompositeEditor`. When a question type is selected, the editor will call `EditorChain.attach()` with an instance of a `QuestionData` subtype and the type-specific sub-Editor. The newly-created `QuestionData` instance should be retained to implement `LeafValueEditor.getValue()`. The implementation of `CompositeEditor.setValue()` just creates the type-specific sub-Editor and calls `EditorChain.attach()`.
FWIW, `OptionalFieldEditor` can be used with `ListEditor` or any other editor type. | Regarding your question why subtype specific data isn't displayed or flushed:
My scenario is a little bit different but I made the following observation:
GWT editor databinding does not work as one would expect with abstract editors in the editor hierarchy. The subEditor declared in your QuestionDataEditor is of type QuestionBaseDataEditor and this is fully abstract type (an interface). When looking for fields/sub editors to populate with data/flush GWT takes all the fields declared in this type. Since QuestionBaseDataEditor has no sub editors declared nothing is displayed/flushed. From debugging I found out that is happens due to GWT using a generated EditorDelegate for that abstract type rather than the EditorDelegate for the concrete subtype present at that moment.
In my case all the concrete sub editors had the same types of leaf value editors (I had two different concrete editors one to display and one to edit the same bean type) so I could do something like this to work around this limitation:
```
interface MyAbstractEditor1 extends Editor<MyBean>
{
LeafValueEditor<String> description();
}
// or as an alternative
abstract class MyAbstractEditor2 implements Editor<MyBean>
{
@UiField protected LeafValueEditor<String> name;
}
class MyConcreteEditor extends MyAbstractEditor2 implements MyAbstractEditor1
{
@UiField TextBox description;
public LeafValueEditor<String> description()
{
return description;
}
// super.name is bound to a TextBox using UiBinder :)
}
```
Now GWT finds the subeditors in the abstract base class and in both cases I get the corresponding fields name and description populated and flushed.
Unfortunately this approach is not suitable when the concrete subeditors have different values in your bean structure to edit :(
I think this is a bug of the editors framework GWT code generation, that can only be solved by the GWT development team. |
7,043,761 | We have a Grails (1.3.7) application deployed to 2 web servers that are sitting behind a load balancer. The problem we're seeing is that when we modify the RequestMaps the springSecurityService.clearCachedRequestmaps() only gets called on whatever server the user has a session to at that time. So that cache isn't getting reset on the other server.
This causes issues when logging in with a connection to the other server and not having the correct permissions because of bad request map cache. What is the right thing to do here?
One thought is to have a quartz job running that clears the cache every, say, 5 minutes. But I'm not sure that is optimal. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7043761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261159/"
] | Fundamentally, you want a `CompositeEditor` to handle cases where objects are dynamically added or removed from the Editor hierarchy. The `ListEditor` and `OptionalFieldEditor` adaptors implement `CompositeEditor`.
If the information required for the different types of questions is fundamentally orthogonal, then multiple `OptionalFieldEditor` could be used with different fields, one for each question type. This will work when you have only a few question types, but won't really scale well in the future.
A different approach, that will scale better would be to use a custom implementation of a `CompositeEditor + LeafValueEditor` that handles a polymorphic `QuestionData` type hierarchy. The type drop-down UI element would become an implementation detail of the `CompositeEditor`. When a question type is selected, the editor will call `EditorChain.attach()` with an instance of a `QuestionData` subtype and the type-specific sub-Editor. The newly-created `QuestionData` instance should be retained to implement `LeafValueEditor.getValue()`. The implementation of `CompositeEditor.setValue()` just creates the type-specific sub-Editor and calls `EditorChain.attach()`.
FWIW, `OptionalFieldEditor` can be used with `ListEditor` or any other editor type. | We implemented similar approach (see accepted answer) and it works for us like this.
Since driver is initially unaware of simple editor paths that might be used by sub-editors, every sub-editor has own driver:
```
public interface CreatesEditorDriver<T> {
RequestFactoryEditorDriver<T, ? extends Editor<T>> createDriver();
}
public interface RequestFactoryEditor<T> extends CreatesEditorDriver<T>, Editor<T> {
}
```
Then we use the following editor adapter that would allow any sub-editor that implements RequestFactoryEditor to be used. This is our workaround to support polimorphism in editors:
```
public static class DynamicEditor<T>
implements LeafValueEditor<T>, CompositeEditor<T, T, RequestFactoryEditor<T>>, HasRequestContext<T> {
private RequestFactoryEditorDriver<T, ? extends Editor<T>> subdriver;
private RequestFactoryEditor<T> subeditor;
private T value;
private EditorDelegate<T> delegate;
private RequestContext ctx;
public static <T> DynamicEditor<T> of(RequestFactoryEditor<T> subeditor) {
return new DynamicEditor<T>(subeditor);
}
protected DynamicEditor(RequestFactoryEditor<T> subeditor) {
this.subeditor = subeditor;
}
@Override
public void setValue(T value) {
this.value = value;
subdriver = null;
if (null != value) {
RequestFactoryEditorDriver<T, ? extends Editor<T>> newSubdriver = subeditor.createDriver();
if (null != ctx) {
newSubdriver.edit(value, ctx);
} else {
newSubdriver.display(value);
}
subdriver = newSubdriver;
}
}
@Override
public T getValue() {
return value;
}
@Override
public void flush() {
if (null != subdriver) {
subdriver.flush();
}
}
@Override
public void onPropertyChange(String... paths) {
}
@Override
public void setDelegate(EditorDelegate<T> delegate) {
this.delegate = delegate;
}
@Override
public RequestFactoryEditor<T> createEditorForTraversal() {
return subeditor;
}
@Override
public String getPathElement(RequestFactoryEditor<T> subEditor) {
return delegate.getPath();
}
@Override
public void setEditorChain(EditorChain<T, RequestFactoryEditor<T>> chain) {
}
@Override
public void setRequestContext(RequestContext ctx) {
this.ctx = ctx;
}
}
```
Our example sub-editor:
```
public static class VirtualProductEditor implements RequestFactoryEditor<ProductProxy> {
interface Driver extends RequestFactoryEditorDriver<ProductProxy, VirtualProductEditor> {}
private static final Driver driver = GWT.create(Driver.class);
public Driver createDriver() {
driver.initialize(this);
return driver;
}
...
}
```
Our usage example:
```
@Path("")
DynamicEditor<ProductProxy> productDetailsEditor;
...
public void setProductType(ProductType type){
if (ProductType.VIRTUAL==type){
productDetailsEditor = DynamicEditor.of(new VirtualProductEditor());
} else if (ProductType.PHYSICAL==type){
productDetailsEditor = DynamicEditor.of(new PhysicalProductEditor());
}
}
```
Would be great to hear your comments. |
7,043,761 | We have a Grails (1.3.7) application deployed to 2 web servers that are sitting behind a load balancer. The problem we're seeing is that when we modify the RequestMaps the springSecurityService.clearCachedRequestmaps() only gets called on whatever server the user has a session to at that time. So that cache isn't getting reset on the other server.
This causes issues when logging in with a connection to the other server and not having the correct permissions because of bad request map cache. What is the right thing to do here?
One thought is to have a quartz job running that clears the cache every, say, 5 minutes. But I'm not sure that is optimal. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7043761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261159/"
] | Fundamentally, you want a `CompositeEditor` to handle cases where objects are dynamically added or removed from the Editor hierarchy. The `ListEditor` and `OptionalFieldEditor` adaptors implement `CompositeEditor`.
If the information required for the different types of questions is fundamentally orthogonal, then multiple `OptionalFieldEditor` could be used with different fields, one for each question type. This will work when you have only a few question types, but won't really scale well in the future.
A different approach, that will scale better would be to use a custom implementation of a `CompositeEditor + LeafValueEditor` that handles a polymorphic `QuestionData` type hierarchy. The type drop-down UI element would become an implementation detail of the `CompositeEditor`. When a question type is selected, the editor will call `EditorChain.attach()` with an instance of a `QuestionData` subtype and the type-specific sub-Editor. The newly-created `QuestionData` instance should be retained to implement `LeafValueEditor.getValue()`. The implementation of `CompositeEditor.setValue()` just creates the type-specific sub-Editor and calls `EditorChain.attach()`.
FWIW, `OptionalFieldEditor` can be used with `ListEditor` or any other editor type. | Isn't the fundamental problem that the binding happens at compile time so will only bind to QuestionDataProxy so won't have sub-type specific bindings? The CompositeEditor javadoc says "An interface that indicates that a given Editor is composed of an unknown number of sub-Editors all of the same type" so that rules this usage out?
At my current job I'm pushing to avoid polymorphism altogether as the RDBMS doesn't support it either. Sadly we do have some at the moment so I'm experimenting with a dummy wrapper class that exposes all the sub-types with specific getters so the compiler has something to work on. Not pretty though.
Have you seen this post: <http://markmail.org/message/u2cff3mfbiboeejr> this seems along the right lines.
I'm a bit worried about code bloat though.
Hope that makes some sort of sense! |
7,043,761 | We have a Grails (1.3.7) application deployed to 2 web servers that are sitting behind a load balancer. The problem we're seeing is that when we modify the RequestMaps the springSecurityService.clearCachedRequestmaps() only gets called on whatever server the user has a session to at that time. So that cache isn't getting reset on the other server.
This causes issues when logging in with a connection to the other server and not having the correct permissions because of bad request map cache. What is the right thing to do here?
One thought is to have a quartz job running that clears the cache every, say, 5 minutes. But I'm not sure that is optimal. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7043761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261159/"
] | We implemented similar approach (see accepted answer) and it works for us like this.
Since driver is initially unaware of simple editor paths that might be used by sub-editors, every sub-editor has own driver:
```
public interface CreatesEditorDriver<T> {
RequestFactoryEditorDriver<T, ? extends Editor<T>> createDriver();
}
public interface RequestFactoryEditor<T> extends CreatesEditorDriver<T>, Editor<T> {
}
```
Then we use the following editor adapter that would allow any sub-editor that implements RequestFactoryEditor to be used. This is our workaround to support polimorphism in editors:
```
public static class DynamicEditor<T>
implements LeafValueEditor<T>, CompositeEditor<T, T, RequestFactoryEditor<T>>, HasRequestContext<T> {
private RequestFactoryEditorDriver<T, ? extends Editor<T>> subdriver;
private RequestFactoryEditor<T> subeditor;
private T value;
private EditorDelegate<T> delegate;
private RequestContext ctx;
public static <T> DynamicEditor<T> of(RequestFactoryEditor<T> subeditor) {
return new DynamicEditor<T>(subeditor);
}
protected DynamicEditor(RequestFactoryEditor<T> subeditor) {
this.subeditor = subeditor;
}
@Override
public void setValue(T value) {
this.value = value;
subdriver = null;
if (null != value) {
RequestFactoryEditorDriver<T, ? extends Editor<T>> newSubdriver = subeditor.createDriver();
if (null != ctx) {
newSubdriver.edit(value, ctx);
} else {
newSubdriver.display(value);
}
subdriver = newSubdriver;
}
}
@Override
public T getValue() {
return value;
}
@Override
public void flush() {
if (null != subdriver) {
subdriver.flush();
}
}
@Override
public void onPropertyChange(String... paths) {
}
@Override
public void setDelegate(EditorDelegate<T> delegate) {
this.delegate = delegate;
}
@Override
public RequestFactoryEditor<T> createEditorForTraversal() {
return subeditor;
}
@Override
public String getPathElement(RequestFactoryEditor<T> subEditor) {
return delegate.getPath();
}
@Override
public void setEditorChain(EditorChain<T, RequestFactoryEditor<T>> chain) {
}
@Override
public void setRequestContext(RequestContext ctx) {
this.ctx = ctx;
}
}
```
Our example sub-editor:
```
public static class VirtualProductEditor implements RequestFactoryEditor<ProductProxy> {
interface Driver extends RequestFactoryEditorDriver<ProductProxy, VirtualProductEditor> {}
private static final Driver driver = GWT.create(Driver.class);
public Driver createDriver() {
driver.initialize(this);
return driver;
}
...
}
```
Our usage example:
```
@Path("")
DynamicEditor<ProductProxy> productDetailsEditor;
...
public void setProductType(ProductType type){
if (ProductType.VIRTUAL==type){
productDetailsEditor = DynamicEditor.of(new VirtualProductEditor());
} else if (ProductType.PHYSICAL==type){
productDetailsEditor = DynamicEditor.of(new PhysicalProductEditor());
}
}
```
Would be great to hear your comments. | Regarding your question why subtype specific data isn't displayed or flushed:
My scenario is a little bit different but I made the following observation:
GWT editor databinding does not work as one would expect with abstract editors in the editor hierarchy. The subEditor declared in your QuestionDataEditor is of type QuestionBaseDataEditor and this is fully abstract type (an interface). When looking for fields/sub editors to populate with data/flush GWT takes all the fields declared in this type. Since QuestionBaseDataEditor has no sub editors declared nothing is displayed/flushed. From debugging I found out that is happens due to GWT using a generated EditorDelegate for that abstract type rather than the EditorDelegate for the concrete subtype present at that moment.
In my case all the concrete sub editors had the same types of leaf value editors (I had two different concrete editors one to display and one to edit the same bean type) so I could do something like this to work around this limitation:
```
interface MyAbstractEditor1 extends Editor<MyBean>
{
LeafValueEditor<String> description();
}
// or as an alternative
abstract class MyAbstractEditor2 implements Editor<MyBean>
{
@UiField protected LeafValueEditor<String> name;
}
class MyConcreteEditor extends MyAbstractEditor2 implements MyAbstractEditor1
{
@UiField TextBox description;
public LeafValueEditor<String> description()
{
return description;
}
// super.name is bound to a TextBox using UiBinder :)
}
```
Now GWT finds the subeditors in the abstract base class and in both cases I get the corresponding fields name and description populated and flushed.
Unfortunately this approach is not suitable when the concrete subeditors have different values in your bean structure to edit :(
I think this is a bug of the editors framework GWT code generation, that can only be solved by the GWT development team. |
7,043,761 | We have a Grails (1.3.7) application deployed to 2 web servers that are sitting behind a load balancer. The problem we're seeing is that when we modify the RequestMaps the springSecurityService.clearCachedRequestmaps() only gets called on whatever server the user has a session to at that time. So that cache isn't getting reset on the other server.
This causes issues when logging in with a connection to the other server and not having the correct permissions because of bad request map cache. What is the right thing to do here?
One thought is to have a quartz job running that clears the cache every, say, 5 minutes. But I'm not sure that is optimal. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7043761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261159/"
] | Regarding your question why subtype specific data isn't displayed or flushed:
My scenario is a little bit different but I made the following observation:
GWT editor databinding does not work as one would expect with abstract editors in the editor hierarchy. The subEditor declared in your QuestionDataEditor is of type QuestionBaseDataEditor and this is fully abstract type (an interface). When looking for fields/sub editors to populate with data/flush GWT takes all the fields declared in this type. Since QuestionBaseDataEditor has no sub editors declared nothing is displayed/flushed. From debugging I found out that is happens due to GWT using a generated EditorDelegate for that abstract type rather than the EditorDelegate for the concrete subtype present at that moment.
In my case all the concrete sub editors had the same types of leaf value editors (I had two different concrete editors one to display and one to edit the same bean type) so I could do something like this to work around this limitation:
```
interface MyAbstractEditor1 extends Editor<MyBean>
{
LeafValueEditor<String> description();
}
// or as an alternative
abstract class MyAbstractEditor2 implements Editor<MyBean>
{
@UiField protected LeafValueEditor<String> name;
}
class MyConcreteEditor extends MyAbstractEditor2 implements MyAbstractEditor1
{
@UiField TextBox description;
public LeafValueEditor<String> description()
{
return description;
}
// super.name is bound to a TextBox using UiBinder :)
}
```
Now GWT finds the subeditors in the abstract base class and in both cases I get the corresponding fields name and description populated and flushed.
Unfortunately this approach is not suitable when the concrete subeditors have different values in your bean structure to edit :(
I think this is a bug of the editors framework GWT code generation, that can only be solved by the GWT development team. | Isn't the fundamental problem that the binding happens at compile time so will only bind to QuestionDataProxy so won't have sub-type specific bindings? The CompositeEditor javadoc says "An interface that indicates that a given Editor is composed of an unknown number of sub-Editors all of the same type" so that rules this usage out?
At my current job I'm pushing to avoid polymorphism altogether as the RDBMS doesn't support it either. Sadly we do have some at the moment so I'm experimenting with a dummy wrapper class that exposes all the sub-types with specific getters so the compiler has something to work on. Not pretty though.
Have you seen this post: <http://markmail.org/message/u2cff3mfbiboeejr> this seems along the right lines.
I'm a bit worried about code bloat though.
Hope that makes some sort of sense! |
7,043,761 | We have a Grails (1.3.7) application deployed to 2 web servers that are sitting behind a load balancer. The problem we're seeing is that when we modify the RequestMaps the springSecurityService.clearCachedRequestmaps() only gets called on whatever server the user has a session to at that time. So that cache isn't getting reset on the other server.
This causes issues when logging in with a connection to the other server and not having the correct permissions because of bad request map cache. What is the right thing to do here?
One thought is to have a quartz job running that clears the cache every, say, 5 minutes. But I'm not sure that is optimal. | 2011/08/12 | [
"https://Stackoverflow.com/questions/7043761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/261159/"
] | We implemented similar approach (see accepted answer) and it works for us like this.
Since driver is initially unaware of simple editor paths that might be used by sub-editors, every sub-editor has own driver:
```
public interface CreatesEditorDriver<T> {
RequestFactoryEditorDriver<T, ? extends Editor<T>> createDriver();
}
public interface RequestFactoryEditor<T> extends CreatesEditorDriver<T>, Editor<T> {
}
```
Then we use the following editor adapter that would allow any sub-editor that implements RequestFactoryEditor to be used. This is our workaround to support polimorphism in editors:
```
public static class DynamicEditor<T>
implements LeafValueEditor<T>, CompositeEditor<T, T, RequestFactoryEditor<T>>, HasRequestContext<T> {
private RequestFactoryEditorDriver<T, ? extends Editor<T>> subdriver;
private RequestFactoryEditor<T> subeditor;
private T value;
private EditorDelegate<T> delegate;
private RequestContext ctx;
public static <T> DynamicEditor<T> of(RequestFactoryEditor<T> subeditor) {
return new DynamicEditor<T>(subeditor);
}
protected DynamicEditor(RequestFactoryEditor<T> subeditor) {
this.subeditor = subeditor;
}
@Override
public void setValue(T value) {
this.value = value;
subdriver = null;
if (null != value) {
RequestFactoryEditorDriver<T, ? extends Editor<T>> newSubdriver = subeditor.createDriver();
if (null != ctx) {
newSubdriver.edit(value, ctx);
} else {
newSubdriver.display(value);
}
subdriver = newSubdriver;
}
}
@Override
public T getValue() {
return value;
}
@Override
public void flush() {
if (null != subdriver) {
subdriver.flush();
}
}
@Override
public void onPropertyChange(String... paths) {
}
@Override
public void setDelegate(EditorDelegate<T> delegate) {
this.delegate = delegate;
}
@Override
public RequestFactoryEditor<T> createEditorForTraversal() {
return subeditor;
}
@Override
public String getPathElement(RequestFactoryEditor<T> subEditor) {
return delegate.getPath();
}
@Override
public void setEditorChain(EditorChain<T, RequestFactoryEditor<T>> chain) {
}
@Override
public void setRequestContext(RequestContext ctx) {
this.ctx = ctx;
}
}
```
Our example sub-editor:
```
public static class VirtualProductEditor implements RequestFactoryEditor<ProductProxy> {
interface Driver extends RequestFactoryEditorDriver<ProductProxy, VirtualProductEditor> {}
private static final Driver driver = GWT.create(Driver.class);
public Driver createDriver() {
driver.initialize(this);
return driver;
}
...
}
```
Our usage example:
```
@Path("")
DynamicEditor<ProductProxy> productDetailsEditor;
...
public void setProductType(ProductType type){
if (ProductType.VIRTUAL==type){
productDetailsEditor = DynamicEditor.of(new VirtualProductEditor());
} else if (ProductType.PHYSICAL==type){
productDetailsEditor = DynamicEditor.of(new PhysicalProductEditor());
}
}
```
Would be great to hear your comments. | Isn't the fundamental problem that the binding happens at compile time so will only bind to QuestionDataProxy so won't have sub-type specific bindings? The CompositeEditor javadoc says "An interface that indicates that a given Editor is composed of an unknown number of sub-Editors all of the same type" so that rules this usage out?
At my current job I'm pushing to avoid polymorphism altogether as the RDBMS doesn't support it either. Sadly we do have some at the moment so I'm experimenting with a dummy wrapper class that exposes all the sub-types with specific getters so the compiler has something to work on. Not pretty though.
Have you seen this post: <http://markmail.org/message/u2cff3mfbiboeejr> this seems along the right lines.
I'm a bit worried about code bloat though.
Hope that makes some sort of sense! |
59,680,369 | credit table and validtransaction table have million record data from year 2008 onwards.
We are doing a migration. So I need to find out the credittypeids which are no longer in use after 2017 (periodseq=1055), so that these need not be migrated.
This is the query and the >= part is resulting in huge cost. Please suggest an alternative.
```
SELECT CREDITTYPEID
FROM CREDITTYPE ct
WHERE NOT EXISTS
(SELECT 1
FROM CREDIT C
WHERE C.PERIODSEQ>=1055
AND C.CREDITTYPEID=CT.CREDITTYPEID
);
```
[](https://i.stack.imgur.com/tdQYH.png) | 2020/01/10 | [
"https://Stackoverflow.com/questions/59680369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11352888/"
] | I'm thinking aggregation:
```
SELECT C.CREDITTYPEID
FROM CREDIT C
GROUP BY C.CREDITTYPEID
HAVING MAX(C.PERIODSEQ) < 1055;
```
This assumes that the credit type is used in at least one credit record.
Otherwise, for your version of the query, you specifically want an index on `CREDIT(CREDITTYPEID, PERIODSEQ)`. The ordering of the keys matters, and this is the correct order for your query. | The following index on the `CREDIT` table should help:
```
CREATE INDEX idx ON CREDIT (PERIODSEQ, CREDITTYPEID);
```
This should allow the `EXISTS` clause lookup to evaluate more quickly. You could also try the following variant index, which reverses the order of the columns:
```
CREATE INDEX idx ON CREDIT (CREDITTYPEID, PERIODSEQ);
``` |
59,680,369 | credit table and validtransaction table have million record data from year 2008 onwards.
We are doing a migration. So I need to find out the credittypeids which are no longer in use after 2017 (periodseq=1055), so that these need not be migrated.
This is the query and the >= part is resulting in huge cost. Please suggest an alternative.
```
SELECT CREDITTYPEID
FROM CREDITTYPE ct
WHERE NOT EXISTS
(SELECT 1
FROM CREDIT C
WHERE C.PERIODSEQ>=1055
AND C.CREDITTYPEID=CT.CREDITTYPEID
);
```
[](https://i.stack.imgur.com/tdQYH.png) | 2020/01/10 | [
"https://Stackoverflow.com/questions/59680369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11352888/"
] | This should return your (distinct!) list of `CREDITTYPEID` that were used in the past, but are not used curretnly (after PERIODSEQ 1055)
```
SELECT CREDITTYPEID /* used before 1055 */
FROM CREDITTYPE ct
WHERE PERIODSEQ < 1055
MINUS
SELECT CREDITTYPEID /* used after 1055 */
FROM CREDITTYPE ct
WHERE PERIODSEQ>=1055;
```
As the column name suggest `CREDITTYPEID` is a *type* so there are several rows in the table with the same typeId.
The query above return only the *distinct list* and uses no hash anti join.
You may add `parallel option` (with the [PARALLEL](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Comments.html#GUID-D25225CE-2DCE-4D9F-8E82-401839690A6E) hint) if your HW allows it. | The following index on the `CREDIT` table should help:
```
CREATE INDEX idx ON CREDIT (PERIODSEQ, CREDITTYPEID);
```
This should allow the `EXISTS` clause lookup to evaluate more quickly. You could also try the following variant index, which reverses the order of the columns:
```
CREATE INDEX idx ON CREDIT (CREDITTYPEID, PERIODSEQ);
``` |
20,183,599 | I'm trying to sort the integers of an array, but I keep getting errors with what I try. I've tried sort(array); array.sort(); Arrays.sort(array); and Arrays.sort(); but nothing works. Help would be appreciated. The error I get for this Arrays.sort(array) is Cannot find symbol, symbol variable Arrays location: class Main
```
public static void main(String[] args) {
int[] array = new int[20];
array = fillArray(array);
printArray(array);
array = sortArray(array);
printArray(array);
}
public static int[] fillArray(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = (int) (1 + Math.random() * 99);
}
return array;
}
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i > 0) {
System.out.print(" | ");
}
System.out.print(array[i]);
}
}
public static int[] sortArray(int[] array) {
Arrays.sort(array);
return array;
}
```
} | 2013/11/25 | [
"https://Stackoverflow.com/questions/20183599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2802854/"
] | Your code does work. (It does sort the array.) I believe your confusion might be because the unsorted and sorted output of `printArray` appear together on the same line and it is very hard to see. Put a line break at the end of the `printArray` method, and it will be clear that the result is sorted:
```
System.out.println();
```
The output now is (for example):
```
78 | 42 | 88 | 11 | 40 | 64 | 37 | 78 | 42 | 35 | 77 | 33 | 33 | 5 | 89 | 12 | 32 | 86 | 24 | 79
5 | 11 | 12 | 24 | 32 | 33 | 33 | 35 | 37 | 40 | 42 | 42 | 64 | 77 | 78 | 78 | 79 | 86 | 88 | 89
```
Edit: Based on the error message you've now provided, the problem is that [`Arrays`](http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html) is a class in the `java.util` package, and you haven't imported the class or qualified access to it. Put this line at the top of the file:
```
import java.util.Arrays;
```
*Or*, when you call the method, use what is called its "fully-qualified name":
```
java.util.Arrays.sort(array);
```
See [Using Package Members](http://docs.oracle.com/javase/tutorial/java/package/usepkgs.html) in the Java tutorial for the details. | Actually, the code you used is working.
You can make some change in main method to make the array printed in console more cleraly.
like
```
System.out.println("Before sorting...");
printArray(array);
array = sortArray(array);
System.out.println("\nAfter sorting...");
printArray(array);
```
**An run example is as follows:**
```
Before sorting...
47 | 68 | 94 | 17 | 99 | 60 | 92 | 61 | 44 | 99 | 64 | 37 | 15 | 79 | 38 | 52 | 77 | 41 | 62 | 88
After sorting...
15 | 17 | 37 | 38 | 41 | 44 | 47 | 52 | 60 | 61 | 62 | 64 | 68 | 77 | 79 | 88 | 92 | 94 | 99 | 99
``` |
19,710,323 | If I have the following code
```
try {
//some stuff here
catch (Exception e) {
throw new CustomException();
} finally {
finalize();
}
```
where `CustomException` is a checked exception,
Will the `finally` block be called in the event of an `Exception`?
EDIT:
Perhaps "finalize()" was a poor choice of wording. I DID NOT mean the finalize() method of Object. I just meant that there was cleanup code that needed done. Apologies for that. | 2013/10/31 | [
"https://Stackoverflow.com/questions/19710323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2085316/"
] | Finally is ALWAYS called, regardless of exceptions and even return statements.
I recommend checking the [Documentation](http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html) on it. | The `finally` block is always executed. It is designed so that you can perform important operations regardless of any exceptions being thrown, for example close streams. |
19,710,323 | If I have the following code
```
try {
//some stuff here
catch (Exception e) {
throw new CustomException();
} finally {
finalize();
}
```
where `CustomException` is a checked exception,
Will the `finally` block be called in the event of an `Exception`?
EDIT:
Perhaps "finalize()" was a poor choice of wording. I DID NOT mean the finalize() method of Object. I just meant that there was cleanup code that needed done. Apologies for that. | 2013/10/31 | [
"https://Stackoverflow.com/questions/19710323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2085316/"
] | Finally is ALWAYS called, regardless of exceptions and even return statements.
I recommend checking the [Documentation](http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html) on it. | finally block is called in each cases. |
19,710,323 | If I have the following code
```
try {
//some stuff here
catch (Exception e) {
throw new CustomException();
} finally {
finalize();
}
```
where `CustomException` is a checked exception,
Will the `finally` block be called in the event of an `Exception`?
EDIT:
Perhaps "finalize()" was a poor choice of wording. I DID NOT mean the finalize() method of Object. I just meant that there was cleanup code that needed done. Apologies for that. | 2013/10/31 | [
"https://Stackoverflow.com/questions/19710323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2085316/"
] | `finally` is always called(even if you call `return;`), unless you call
```
System.exit();
```
in `try` or `catch` block. | finally block is called in each cases. |
19,710,323 | If I have the following code
```
try {
//some stuff here
catch (Exception e) {
throw new CustomException();
} finally {
finalize();
}
```
where `CustomException` is a checked exception,
Will the `finally` block be called in the event of an `Exception`?
EDIT:
Perhaps "finalize()" was a poor choice of wording. I DID NOT mean the finalize() method of Object. I just meant that there was cleanup code that needed done. Apologies for that. | 2013/10/31 | [
"https://Stackoverflow.com/questions/19710323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2085316/"
] | Finally is ALWAYS called, regardless of exceptions and even return statements.
I recommend checking the [Documentation](http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html) on it. | `finally` is always called(even if you call `return;`), unless you call
```
System.exit();
```
in `try` or `catch` block. |
19,710,323 | If I have the following code
```
try {
//some stuff here
catch (Exception e) {
throw new CustomException();
} finally {
finalize();
}
```
where `CustomException` is a checked exception,
Will the `finally` block be called in the event of an `Exception`?
EDIT:
Perhaps "finalize()" was a poor choice of wording. I DID NOT mean the finalize() method of Object. I just meant that there was cleanup code that needed done. Apologies for that. | 2013/10/31 | [
"https://Stackoverflow.com/questions/19710323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2085316/"
] | Finally is ALWAYS called, regardless of exceptions and even return statements.
I recommend checking the [Documentation](http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html) on it. | It will **always** be called in the event of an exception. For that matter, it will always be called, period. That's what it's for. |
19,710,323 | If I have the following code
```
try {
//some stuff here
catch (Exception e) {
throw new CustomException();
} finally {
finalize();
}
```
where `CustomException` is a checked exception,
Will the `finally` block be called in the event of an `Exception`?
EDIT:
Perhaps "finalize()" was a poor choice of wording. I DID NOT mean the finalize() method of Object. I just meant that there was cleanup code that needed done. Apologies for that. | 2013/10/31 | [
"https://Stackoverflow.com/questions/19710323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2085316/"
] | It will **always** be called in the event of an exception. For that matter, it will always be called, period. That's what it's for. | finally block is called in each cases. |
19,710,323 | If I have the following code
```
try {
//some stuff here
catch (Exception e) {
throw new CustomException();
} finally {
finalize();
}
```
where `CustomException` is a checked exception,
Will the `finally` block be called in the event of an `Exception`?
EDIT:
Perhaps "finalize()" was a poor choice of wording. I DID NOT mean the finalize() method of Object. I just meant that there was cleanup code that needed done. Apologies for that. | 2013/10/31 | [
"https://Stackoverflow.com/questions/19710323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2085316/"
] | It will **always** be called in the event of an exception. For that matter, it will always be called, period. That's what it's for. | The `finally` block is always executed. It is designed so that you can perform important operations regardless of any exceptions being thrown, for example close streams. |
19,710,323 | If I have the following code
```
try {
//some stuff here
catch (Exception e) {
throw new CustomException();
} finally {
finalize();
}
```
where `CustomException` is a checked exception,
Will the `finally` block be called in the event of an `Exception`?
EDIT:
Perhaps "finalize()" was a poor choice of wording. I DID NOT mean the finalize() method of Object. I just meant that there was cleanup code that needed done. Apologies for that. | 2013/10/31 | [
"https://Stackoverflow.com/questions/19710323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2085316/"
] | `finally` is always called(even if you call `return;`), unless you call
```
System.exit();
```
in `try` or `catch` block. | Yes, `finally` is ALWAYS executed, no matter what happens, short of the JVM dying before your code is reached. It will even get called in this case:
```
public boolean doSomething() throws Exception{
boolean iDidIt = true;
try{
//attempt to do it
return iDidIt;
catch(Exception e){
iDidIt = false;
return iDidIt;
} finally {
System.out.println("Did something get done? "+iDidIt);
}
}
```
The print statement will get printed no matter what. |
19,710,323 | If I have the following code
```
try {
//some stuff here
catch (Exception e) {
throw new CustomException();
} finally {
finalize();
}
```
where `CustomException` is a checked exception,
Will the `finally` block be called in the event of an `Exception`?
EDIT:
Perhaps "finalize()" was a poor choice of wording. I DID NOT mean the finalize() method of Object. I just meant that there was cleanup code that needed done. Apologies for that. | 2013/10/31 | [
"https://Stackoverflow.com/questions/19710323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2085316/"
] | Finally is ALWAYS called, regardless of exceptions and even return statements.
I recommend checking the [Documentation](http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html) on it. | Yes, `finally` is ALWAYS executed, no matter what happens, short of the JVM dying before your code is reached. It will even get called in this case:
```
public boolean doSomething() throws Exception{
boolean iDidIt = true;
try{
//attempt to do it
return iDidIt;
catch(Exception e){
iDidIt = false;
return iDidIt;
} finally {
System.out.println("Did something get done? "+iDidIt);
}
}
```
The print statement will get printed no matter what. |
19,710,323 | If I have the following code
```
try {
//some stuff here
catch (Exception e) {
throw new CustomException();
} finally {
finalize();
}
```
where `CustomException` is a checked exception,
Will the `finally` block be called in the event of an `Exception`?
EDIT:
Perhaps "finalize()" was a poor choice of wording. I DID NOT mean the finalize() method of Object. I just meant that there was cleanup code that needed done. Apologies for that. | 2013/10/31 | [
"https://Stackoverflow.com/questions/19710323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2085316/"
] | `finally` is always called(even if you call `return;`), unless you call
```
System.exit();
```
in `try` or `catch` block. | The `finally` block is always executed. It is designed so that you can perform important operations regardless of any exceptions being thrown, for example close streams. |
44,200 | Can we change the meaning of a well established symbol and use the newly defined symbol in our writing? If so how do we go about doing so?
It am not talking about using a symbol in the context of its antithesis. That still relies on the original meaning. In such cases playing symbols in juxtaposition to their opposite meaning and using them in reverse context can be powerful and evocative.
I'm talking about changing the meaning entirely. Can it be done? I assume if it can that it will require a lot of establishing. My thought is to tear away the original meaning by establishing in some way it **does not mean** that, then slowly build up the new meaning. (Besides perhaps publishing a small companion essay explaining it.) | 2019/03/30 | [
"https://writers.stackexchange.com/questions/44200",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/30375/"
] | Reinterpretations of symbols are a common occurence:
1. The letter *x* given the meaning "hazard":
[](https://i.stack.imgur.com/m4OpI.png)
2. The hazard symbol given the meaning "intoxication" or "death":
[](https://i.stack.imgur.com/I13nI.png)
3. The christian cross given the meaning "Switzerland":
[](https://i.stack.imgur.com/Jztwz.png)
4. The Swiss cross given the meaning "medical help":
[](https://i.stack.imgur.com/LajWU.png)
5. The copyright symbol given the meaning "funny tv station":
[](https://i.stack.imgur.com/XJTzs.png)
6. A form of the christian cross given the meaning "white supremacy":
[](https://i.stack.imgur.com/5J5J1.png)
7. The dollar symbol given the meaning "variable":
`$foo = "bar";`
8. The German penny symbol (the letter *d*, for "denarius", in Kurrent script) given the meaning "delete":
[](https://i.stack.imgur.com/dTXBh.png)
and so on ...
Often the new meaning is related to the old one, as in most of these visual examples, but that is not always the case: tv station Comedy Central have nothing specific to do with copyright (or breaking it, as the reverse open circle might suggest) and the dollar sign in programming has no relation to currency.
---
*How do you establish a new meaning for a well-known symbol?*
### By using it in that meaning.
Let us suppose that in your text you want to establish the question mark as a symbol for a god. To do that, you could introduce the symbol and this meaning in a scene, where a character regards the symbol and thinks of or learns its meaning:
>
> Over the altar was what looked like a reversed letter S, with a circle below it.
>
> "What does that serpentine line over the dot mean?", John asked.
>
> "It's a symbol for the new god", Ann explained.
>
>
>
After this introduction you keep using the symbol in this meaning, while you *avoid mentioning the old meaning*. For example, do not write that "John was hunted by a group of men with question marks on their shoulders". Either give the symbol a name (e.g. "the symbol of [name of god]") or always describe it ("... with the god's wavy line and dot on their shoulders.").
This practice works well, as has been shown in the [Third Wave](https://en.wikipedia.org/wiki/The_Third_Wave_(experiment)) experiment, where a cupped hand – originally a sign for "holding [water]" – became a symbol for being a member of a (fascist) community.
But symbols work best when their new meaning is related to the old one. If it isn't, those of your readers who recognize the original symbol, will wonder what the relation is and what you intended with your use of that symbol. | If it is a well known symbol, I sincerely doubt it; unless you are writing a farce or comedy.
The issue is I don't think the reader can divorce themselves from the symbol triggering the well-known meaning. As an example, for an American, "FBI" means one thing, it is a symbol. No matter what you do in your book or movie, "FBI" is going to trigger the well-known meaning, period. They may also remember you want it to mean something different, but that will be a secondary thought. This is a physical, biological phenomenon: Neurons are and neural pathways are **physical** things and cannot be un-grown or put aside for the purpose of your story; they **are** going to fire and trigger their mental models of the **real** "FBI" whether you like it or not.
The same goes for visual symbols. The swastika used to mean other things, some of them spiritual, but once it became appropriated as the symbol of Fascist Germany under Hitler; forget it. You will never supplant that meaning or prevent that meaning from being triggered; the swastika will likely represent Hitler's Germany for many centuries. The same goes for the Christian Cross, the Hammer and Sickle for Communism, etc.
Now, this is a biological phenomenon you can *exploit* in a farce or comedy movie. Say our human crew lands on an alien planet (or in the future) where raising the middle finger solo is a gesture to be taken as a compliment on your style. If not overdone, a writer could wring some laughs out of that, but that is **because** the audience is programmed to realize the dichotomy of the humans seeing one thing and the aliens meaning another, and perhaps vice versa; the aliens taking as a compliment what was intended as an angry insult. And then the humans get used to it, and come home and use it as a compliment which gets taken as an insult.
The only reason I can think one might do this is to force this dichotomy thinking in the reader, as we might want to do in comedy. Other than that, I'd use some imagination and come up with a unique signal. Or appropriate one that is not very well known at all; for example there is a ton of art and religion iconography that only a very tiny percentage of people would know is being used incorrectly or doesn't mean what you claim it means. If your alternative meaning isn't going to cause any cognitive dissonance in 98% of the audience, no big deal. |
44,200 | Can we change the meaning of a well established symbol and use the newly defined symbol in our writing? If so how do we go about doing so?
It am not talking about using a symbol in the context of its antithesis. That still relies on the original meaning. In such cases playing symbols in juxtaposition to their opposite meaning and using them in reverse context can be powerful and evocative.
I'm talking about changing the meaning entirely. Can it be done? I assume if it can that it will require a lot of establishing. My thought is to tear away the original meaning by establishing in some way it **does not mean** that, then slowly build up the new meaning. (Besides perhaps publishing a small companion essay explaining it.) | 2019/03/30 | [
"https://writers.stackexchange.com/questions/44200",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/30375/"
] | Reinterpretations of symbols are a common occurence:
1. The letter *x* given the meaning "hazard":
[](https://i.stack.imgur.com/m4OpI.png)
2. The hazard symbol given the meaning "intoxication" or "death":
[](https://i.stack.imgur.com/I13nI.png)
3. The christian cross given the meaning "Switzerland":
[](https://i.stack.imgur.com/Jztwz.png)
4. The Swiss cross given the meaning "medical help":
[](https://i.stack.imgur.com/LajWU.png)
5. The copyright symbol given the meaning "funny tv station":
[](https://i.stack.imgur.com/XJTzs.png)
6. A form of the christian cross given the meaning "white supremacy":
[](https://i.stack.imgur.com/5J5J1.png)
7. The dollar symbol given the meaning "variable":
`$foo = "bar";`
8. The German penny symbol (the letter *d*, for "denarius", in Kurrent script) given the meaning "delete":
[](https://i.stack.imgur.com/dTXBh.png)
and so on ...
Often the new meaning is related to the old one, as in most of these visual examples, but that is not always the case: tv station Comedy Central have nothing specific to do with copyright (or breaking it, as the reverse open circle might suggest) and the dollar sign in programming has no relation to currency.
---
*How do you establish a new meaning for a well-known symbol?*
### By using it in that meaning.
Let us suppose that in your text you want to establish the question mark as a symbol for a god. To do that, you could introduce the symbol and this meaning in a scene, where a character regards the symbol and thinks of or learns its meaning:
>
> Over the altar was what looked like a reversed letter S, with a circle below it.
>
> "What does that serpentine line over the dot mean?", John asked.
>
> "It's a symbol for the new god", Ann explained.
>
>
>
After this introduction you keep using the symbol in this meaning, while you *avoid mentioning the old meaning*. For example, do not write that "John was hunted by a group of men with question marks on their shoulders". Either give the symbol a name (e.g. "the symbol of [name of god]") or always describe it ("... with the god's wavy line and dot on their shoulders.").
This practice works well, as has been shown in the [Third Wave](https://en.wikipedia.org/wiki/The_Third_Wave_(experiment)) experiment, where a cupped hand – originally a sign for "holding [water]" – became a symbol for being a member of a (fascist) community.
But symbols work best when their new meaning is related to the old one. If it isn't, those of your readers who recognize the original symbol, will wonder what the relation is and what you intended with your use of that symbol. | What are you trying to accomplish here?
If a symbol is well known, getting that meaning out of reader's heads is very hard. Like if you decided that in your story the dollar sign, $, will be a symbol for, I don't know, a new political party, I think readers would be asking, So what does this party have to do with money? Do you mean that this party is all about economic policy? That they are corrupt and take bribes? Or what?
If your goal is simply that you need a symbol in your story for some idea or movement or group, why not just make up a new symbol? What is gained by trying to recycle an existing symbol?
The only reasons I can think of to re-using an existing symbol are:
(a) The characters in your story want to bring connotations of the existing idea into their new idea. The symbol represents something that is highly respected and they want to appropriate that respect. Like, many people see the Statue of Liberty as a symbol of freedom. So you use the Statue of Liberty as a symbol for their movement or organization so that people will associate them with freedom. (This could be legitimate, if they really are all about freedom, or it could be a total sham.)
(b) The characters are trying to tear down some existing idea, maybe are trying to replace it with their own. Like, they hate Christianity and want to replace it with their own religion, so they use a cross as their symbol and try to convince people to associate the cross with their new religion rather than the existing religion.
I'm not saying those are the only possible reasons, just the only ones that occur to me.
It may be necessary to distinguish why you as the author want to re-use a symbol, and why the characters in your story want to do this.
Either way, getting people to forget the meaning of a well-known symbol is hard. user10915156 mentioned how some programming languages use the $ to mean "variable". That's true. But I've been a programmer for 40 years (wow I'm getting old ...), and I still find that distracting. To some extent you can get people to separate "domains" in their minds, to see something as having one meaning in this domain and a different meaning in another domain. Like I recall once noticing with amusement that when I was talking about electronics, "CRT" meant "cathode ray tube", but when I was talking about war-gaming, "CRT" meant "combat results table". But I sincerely doubt that any American, even the person most wrapped up in programming forgets that "$" is a dollar symbol. I can't imagine someone going to the mall and seeing price tags and wondering why the store put variable names on all their products. |
44,200 | Can we change the meaning of a well established symbol and use the newly defined symbol in our writing? If so how do we go about doing so?
It am not talking about using a symbol in the context of its antithesis. That still relies on the original meaning. In such cases playing symbols in juxtaposition to their opposite meaning and using them in reverse context can be powerful and evocative.
I'm talking about changing the meaning entirely. Can it be done? I assume if it can that it will require a lot of establishing. My thought is to tear away the original meaning by establishing in some way it **does not mean** that, then slowly build up the new meaning. (Besides perhaps publishing a small companion essay explaining it.) | 2019/03/30 | [
"https://writers.stackexchange.com/questions/44200",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/30375/"
] | If it is a well known symbol, I sincerely doubt it; unless you are writing a farce or comedy.
The issue is I don't think the reader can divorce themselves from the symbol triggering the well-known meaning. As an example, for an American, "FBI" means one thing, it is a symbol. No matter what you do in your book or movie, "FBI" is going to trigger the well-known meaning, period. They may also remember you want it to mean something different, but that will be a secondary thought. This is a physical, biological phenomenon: Neurons are and neural pathways are **physical** things and cannot be un-grown or put aside for the purpose of your story; they **are** going to fire and trigger their mental models of the **real** "FBI" whether you like it or not.
The same goes for visual symbols. The swastika used to mean other things, some of them spiritual, but once it became appropriated as the symbol of Fascist Germany under Hitler; forget it. You will never supplant that meaning or prevent that meaning from being triggered; the swastika will likely represent Hitler's Germany for many centuries. The same goes for the Christian Cross, the Hammer and Sickle for Communism, etc.
Now, this is a biological phenomenon you can *exploit* in a farce or comedy movie. Say our human crew lands on an alien planet (or in the future) where raising the middle finger solo is a gesture to be taken as a compliment on your style. If not overdone, a writer could wring some laughs out of that, but that is **because** the audience is programmed to realize the dichotomy of the humans seeing one thing and the aliens meaning another, and perhaps vice versa; the aliens taking as a compliment what was intended as an angry insult. And then the humans get used to it, and come home and use it as a compliment which gets taken as an insult.
The only reason I can think one might do this is to force this dichotomy thinking in the reader, as we might want to do in comedy. Other than that, I'd use some imagination and come up with a unique signal. Or appropriate one that is not very well known at all; for example there is a ton of art and religion iconography that only a very tiny percentage of people would know is being used incorrectly or doesn't mean what you claim it means. If your alternative meaning isn't going to cause any cognitive dissonance in 98% of the audience, no big deal. | Short Answer
**It Depends on your world.**
Long Answer:
If your world supposedly is a battle between Real and Mirror world, then you can formulate the meaning of the existing symbols of real world to work exactly opposite in Mirror world. If your world is on different planet, you can set up your own meanings for the same set of symbols, culture and civilization. If your world is same but you are writing a mystery or horror genre that requires consideration of a new meaning than the actual one for that symbol - in this case also you can smoothly make the readers accept the fact. If you are writing a constructed language, you can define the new symbol in a completely new way.
In short, it's relative and according to me depends on need of your story or plot. If your story or world or genre strongly demands it, do it - else leave it. |
44,200 | Can we change the meaning of a well established symbol and use the newly defined symbol in our writing? If so how do we go about doing so?
It am not talking about using a symbol in the context of its antithesis. That still relies on the original meaning. In such cases playing symbols in juxtaposition to their opposite meaning and using them in reverse context can be powerful and evocative.
I'm talking about changing the meaning entirely. Can it be done? I assume if it can that it will require a lot of establishing. My thought is to tear away the original meaning by establishing in some way it **does not mean** that, then slowly build up the new meaning. (Besides perhaps publishing a small companion essay explaining it.) | 2019/03/30 | [
"https://writers.stackexchange.com/questions/44200",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/30375/"
] | Reinterpretations of symbols are a common occurence:
1. The letter *x* given the meaning "hazard":
[](https://i.stack.imgur.com/m4OpI.png)
2. The hazard symbol given the meaning "intoxication" or "death":
[](https://i.stack.imgur.com/I13nI.png)
3. The christian cross given the meaning "Switzerland":
[](https://i.stack.imgur.com/Jztwz.png)
4. The Swiss cross given the meaning "medical help":
[](https://i.stack.imgur.com/LajWU.png)
5. The copyright symbol given the meaning "funny tv station":
[](https://i.stack.imgur.com/XJTzs.png)
6. A form of the christian cross given the meaning "white supremacy":
[](https://i.stack.imgur.com/5J5J1.png)
7. The dollar symbol given the meaning "variable":
`$foo = "bar";`
8. The German penny symbol (the letter *d*, for "denarius", in Kurrent script) given the meaning "delete":
[](https://i.stack.imgur.com/dTXBh.png)
and so on ...
Often the new meaning is related to the old one, as in most of these visual examples, but that is not always the case: tv station Comedy Central have nothing specific to do with copyright (or breaking it, as the reverse open circle might suggest) and the dollar sign in programming has no relation to currency.
---
*How do you establish a new meaning for a well-known symbol?*
### By using it in that meaning.
Let us suppose that in your text you want to establish the question mark as a symbol for a god. To do that, you could introduce the symbol and this meaning in a scene, where a character regards the symbol and thinks of or learns its meaning:
>
> Over the altar was what looked like a reversed letter S, with a circle below it.
>
> "What does that serpentine line over the dot mean?", John asked.
>
> "It's a symbol for the new god", Ann explained.
>
>
>
After this introduction you keep using the symbol in this meaning, while you *avoid mentioning the old meaning*. For example, do not write that "John was hunted by a group of men with question marks on their shoulders". Either give the symbol a name (e.g. "the symbol of [name of god]") or always describe it ("... with the god's wavy line and dot on their shoulders.").
This practice works well, as has been shown in the [Third Wave](https://en.wikipedia.org/wiki/The_Third_Wave_(experiment)) experiment, where a cupped hand – originally a sign for "holding [water]" – became a symbol for being a member of a (fascist) community.
But symbols work best when their new meaning is related to the old one. If it isn't, those of your readers who recognize the original symbol, will wonder what the relation is and what you intended with your use of that symbol. | Can you completely replace the meaning in the reader's mind? Probably not - it's pretty similar to trying to change the definition of a word. What might be easier is the change the symbol's meaning *for your PoV characters*. Try showing the change from their perspectives.
Add some event that makes the question their initial beliefs, and eventually discard those beliefs. Then slowly build up the new meaning in their mind. Show *why* that symbol has a new meaning.
To use Rasdashan's shield example: Suppose the shield is adopted as the symbol of a newly-formed political party (to show that they're pledging to protect the country from some threat). This political party manages to get a psychopathic dictator elected. The shield, once a symbol of protection, is now a symbol of oppression in your world. Show your characters reacting to the change - have your MC look at someone carrying a shield and think "There's someone who might break down my door at 4 A.M." |
44,200 | Can we change the meaning of a well established symbol and use the newly defined symbol in our writing? If so how do we go about doing so?
It am not talking about using a symbol in the context of its antithesis. That still relies on the original meaning. In such cases playing symbols in juxtaposition to their opposite meaning and using them in reverse context can be powerful and evocative.
I'm talking about changing the meaning entirely. Can it be done? I assume if it can that it will require a lot of establishing. My thought is to tear away the original meaning by establishing in some way it **does not mean** that, then slowly build up the new meaning. (Besides perhaps publishing a small companion essay explaining it.) | 2019/03/30 | [
"https://writers.stackexchange.com/questions/44200",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/30375/"
] | Can you completely replace the meaning in the reader's mind? Probably not - it's pretty similar to trying to change the definition of a word. What might be easier is the change the symbol's meaning *for your PoV characters*. Try showing the change from their perspectives.
Add some event that makes the question their initial beliefs, and eventually discard those beliefs. Then slowly build up the new meaning in their mind. Show *why* that symbol has a new meaning.
To use Rasdashan's shield example: Suppose the shield is adopted as the symbol of a newly-formed political party (to show that they're pledging to protect the country from some threat). This political party manages to get a psychopathic dictator elected. The shield, once a symbol of protection, is now a symbol of oppression in your world. Show your characters reacting to the change - have your MC look at someone carrying a shield and think "There's someone who might break down my door at 4 A.M." | Short Answer
**It Depends on your world.**
Long Answer:
If your world supposedly is a battle between Real and Mirror world, then you can formulate the meaning of the existing symbols of real world to work exactly opposite in Mirror world. If your world is on different planet, you can set up your own meanings for the same set of symbols, culture and civilization. If your world is same but you are writing a mystery or horror genre that requires consideration of a new meaning than the actual one for that symbol - in this case also you can smoothly make the readers accept the fact. If you are writing a constructed language, you can define the new symbol in a completely new way.
In short, it's relative and according to me depends on need of your story or plot. If your story or world or genre strongly demands it, do it - else leave it. |
44,200 | Can we change the meaning of a well established symbol and use the newly defined symbol in our writing? If so how do we go about doing so?
It am not talking about using a symbol in the context of its antithesis. That still relies on the original meaning. In such cases playing symbols in juxtaposition to their opposite meaning and using them in reverse context can be powerful and evocative.
I'm talking about changing the meaning entirely. Can it be done? I assume if it can that it will require a lot of establishing. My thought is to tear away the original meaning by establishing in some way it **does not mean** that, then slowly build up the new meaning. (Besides perhaps publishing a small companion essay explaining it.) | 2019/03/30 | [
"https://writers.stackexchange.com/questions/44200",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/30375/"
] | To both create the new meaning and repudiate the old might be nearly impossible.
We are a symbolic creature at heart, always seeking pattern and meaning and seeing things that might never have been intended.
Meanings abide. Laurels are still a symbol of victory and success though millennia have passed since they were awarded in the Olympic Games. There are probably many who know the symbolism without understanding its genesis. Would it be possible to make the laurel mean something else to someone - perhaps, but removing the meaning already assigned would be unwise as it would break immersion and be seen as an attack on an established symbol.
You could take the simple shield, a symbol of protection, and try to make it mean something else. The reader will still know what that symbol usually means and hold onto that. Removing that meaning would take more effort than it is worth and likely fail. | Short Answer
**It Depends on your world.**
Long Answer:
If your world supposedly is a battle between Real and Mirror world, then you can formulate the meaning of the existing symbols of real world to work exactly opposite in Mirror world. If your world is on different planet, you can set up your own meanings for the same set of symbols, culture and civilization. If your world is same but you are writing a mystery or horror genre that requires consideration of a new meaning than the actual one for that symbol - in this case also you can smoothly make the readers accept the fact. If you are writing a constructed language, you can define the new symbol in a completely new way.
In short, it's relative and according to me depends on need of your story or plot. If your story or world or genre strongly demands it, do it - else leave it. |
44,200 | Can we change the meaning of a well established symbol and use the newly defined symbol in our writing? If so how do we go about doing so?
It am not talking about using a symbol in the context of its antithesis. That still relies on the original meaning. In such cases playing symbols in juxtaposition to their opposite meaning and using them in reverse context can be powerful and evocative.
I'm talking about changing the meaning entirely. Can it be done? I assume if it can that it will require a lot of establishing. My thought is to tear away the original meaning by establishing in some way it **does not mean** that, then slowly build up the new meaning. (Besides perhaps publishing a small companion essay explaining it.) | 2019/03/30 | [
"https://writers.stackexchange.com/questions/44200",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/30375/"
] | If it is a well known symbol, I sincerely doubt it; unless you are writing a farce or comedy.
The issue is I don't think the reader can divorce themselves from the symbol triggering the well-known meaning. As an example, for an American, "FBI" means one thing, it is a symbol. No matter what you do in your book or movie, "FBI" is going to trigger the well-known meaning, period. They may also remember you want it to mean something different, but that will be a secondary thought. This is a physical, biological phenomenon: Neurons are and neural pathways are **physical** things and cannot be un-grown or put aside for the purpose of your story; they **are** going to fire and trigger their mental models of the **real** "FBI" whether you like it or not.
The same goes for visual symbols. The swastika used to mean other things, some of them spiritual, but once it became appropriated as the symbol of Fascist Germany under Hitler; forget it. You will never supplant that meaning or prevent that meaning from being triggered; the swastika will likely represent Hitler's Germany for many centuries. The same goes for the Christian Cross, the Hammer and Sickle for Communism, etc.
Now, this is a biological phenomenon you can *exploit* in a farce or comedy movie. Say our human crew lands on an alien planet (or in the future) where raising the middle finger solo is a gesture to be taken as a compliment on your style. If not overdone, a writer could wring some laughs out of that, but that is **because** the audience is programmed to realize the dichotomy of the humans seeing one thing and the aliens meaning another, and perhaps vice versa; the aliens taking as a compliment what was intended as an angry insult. And then the humans get used to it, and come home and use it as a compliment which gets taken as an insult.
The only reason I can think one might do this is to force this dichotomy thinking in the reader, as we might want to do in comedy. Other than that, I'd use some imagination and come up with a unique signal. Or appropriate one that is not very well known at all; for example there is a ton of art and religion iconography that only a very tiny percentage of people would know is being used incorrectly or doesn't mean what you claim it means. If your alternative meaning isn't going to cause any cognitive dissonance in 98% of the audience, no big deal. | What are you trying to accomplish here?
If a symbol is well known, getting that meaning out of reader's heads is very hard. Like if you decided that in your story the dollar sign, $, will be a symbol for, I don't know, a new political party, I think readers would be asking, So what does this party have to do with money? Do you mean that this party is all about economic policy? That they are corrupt and take bribes? Or what?
If your goal is simply that you need a symbol in your story for some idea or movement or group, why not just make up a new symbol? What is gained by trying to recycle an existing symbol?
The only reasons I can think of to re-using an existing symbol are:
(a) The characters in your story want to bring connotations of the existing idea into their new idea. The symbol represents something that is highly respected and they want to appropriate that respect. Like, many people see the Statue of Liberty as a symbol of freedom. So you use the Statue of Liberty as a symbol for their movement or organization so that people will associate them with freedom. (This could be legitimate, if they really are all about freedom, or it could be a total sham.)
(b) The characters are trying to tear down some existing idea, maybe are trying to replace it with their own. Like, they hate Christianity and want to replace it with their own religion, so they use a cross as their symbol and try to convince people to associate the cross with their new religion rather than the existing religion.
I'm not saying those are the only possible reasons, just the only ones that occur to me.
It may be necessary to distinguish why you as the author want to re-use a symbol, and why the characters in your story want to do this.
Either way, getting people to forget the meaning of a well-known symbol is hard. user10915156 mentioned how some programming languages use the $ to mean "variable". That's true. But I've been a programmer for 40 years (wow I'm getting old ...), and I still find that distracting. To some extent you can get people to separate "domains" in their minds, to see something as having one meaning in this domain and a different meaning in another domain. Like I recall once noticing with amusement that when I was talking about electronics, "CRT" meant "cathode ray tube", but when I was talking about war-gaming, "CRT" meant "combat results table". But I sincerely doubt that any American, even the person most wrapped up in programming forgets that "$" is a dollar symbol. I can't imagine someone going to the mall and seeing price tags and wondering why the store put variable names on all their products. |
44,200 | Can we change the meaning of a well established symbol and use the newly defined symbol in our writing? If so how do we go about doing so?
It am not talking about using a symbol in the context of its antithesis. That still relies on the original meaning. In such cases playing symbols in juxtaposition to their opposite meaning and using them in reverse context can be powerful and evocative.
I'm talking about changing the meaning entirely. Can it be done? I assume if it can that it will require a lot of establishing. My thought is to tear away the original meaning by establishing in some way it **does not mean** that, then slowly build up the new meaning. (Besides perhaps publishing a small companion essay explaining it.) | 2019/03/30 | [
"https://writers.stackexchange.com/questions/44200",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/30375/"
] | Reinterpretations of symbols are a common occurence:
1. The letter *x* given the meaning "hazard":
[](https://i.stack.imgur.com/m4OpI.png)
2. The hazard symbol given the meaning "intoxication" or "death":
[](https://i.stack.imgur.com/I13nI.png)
3. The christian cross given the meaning "Switzerland":
[](https://i.stack.imgur.com/Jztwz.png)
4. The Swiss cross given the meaning "medical help":
[](https://i.stack.imgur.com/LajWU.png)
5. The copyright symbol given the meaning "funny tv station":
[](https://i.stack.imgur.com/XJTzs.png)
6. A form of the christian cross given the meaning "white supremacy":
[](https://i.stack.imgur.com/5J5J1.png)
7. The dollar symbol given the meaning "variable":
`$foo = "bar";`
8. The German penny symbol (the letter *d*, for "denarius", in Kurrent script) given the meaning "delete":
[](https://i.stack.imgur.com/dTXBh.png)
and so on ...
Often the new meaning is related to the old one, as in most of these visual examples, but that is not always the case: tv station Comedy Central have nothing specific to do with copyright (or breaking it, as the reverse open circle might suggest) and the dollar sign in programming has no relation to currency.
---
*How do you establish a new meaning for a well-known symbol?*
### By using it in that meaning.
Let us suppose that in your text you want to establish the question mark as a symbol for a god. To do that, you could introduce the symbol and this meaning in a scene, where a character regards the symbol and thinks of or learns its meaning:
>
> Over the altar was what looked like a reversed letter S, with a circle below it.
>
> "What does that serpentine line over the dot mean?", John asked.
>
> "It's a symbol for the new god", Ann explained.
>
>
>
After this introduction you keep using the symbol in this meaning, while you *avoid mentioning the old meaning*. For example, do not write that "John was hunted by a group of men with question marks on their shoulders". Either give the symbol a name (e.g. "the symbol of [name of god]") or always describe it ("... with the god's wavy line and dot on their shoulders.").
This practice works well, as has been shown in the [Third Wave](https://en.wikipedia.org/wiki/The_Third_Wave_(experiment)) experiment, where a cupped hand – originally a sign for "holding [water]" – became a symbol for being a member of a (fascist) community.
But symbols work best when their new meaning is related to the old one. If it isn't, those of your readers who recognize the original symbol, will wonder what the relation is and what you intended with your use of that symbol. | To both create the new meaning and repudiate the old might be nearly impossible.
We are a symbolic creature at heart, always seeking pattern and meaning and seeing things that might never have been intended.
Meanings abide. Laurels are still a symbol of victory and success though millennia have passed since they were awarded in the Olympic Games. There are probably many who know the symbolism without understanding its genesis. Would it be possible to make the laurel mean something else to someone - perhaps, but removing the meaning already assigned would be unwise as it would break immersion and be seen as an attack on an established symbol.
You could take the simple shield, a symbol of protection, and try to make it mean something else. The reader will still know what that symbol usually means and hold onto that. Removing that meaning would take more effort than it is worth and likely fail. |
44,200 | Can we change the meaning of a well established symbol and use the newly defined symbol in our writing? If so how do we go about doing so?
It am not talking about using a symbol in the context of its antithesis. That still relies on the original meaning. In such cases playing symbols in juxtaposition to their opposite meaning and using them in reverse context can be powerful and evocative.
I'm talking about changing the meaning entirely. Can it be done? I assume if it can that it will require a lot of establishing. My thought is to tear away the original meaning by establishing in some way it **does not mean** that, then slowly build up the new meaning. (Besides perhaps publishing a small companion essay explaining it.) | 2019/03/30 | [
"https://writers.stackexchange.com/questions/44200",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/30375/"
] | To both create the new meaning and repudiate the old might be nearly impossible.
We are a symbolic creature at heart, always seeking pattern and meaning and seeing things that might never have been intended.
Meanings abide. Laurels are still a symbol of victory and success though millennia have passed since they were awarded in the Olympic Games. There are probably many who know the symbolism without understanding its genesis. Would it be possible to make the laurel mean something else to someone - perhaps, but removing the meaning already assigned would be unwise as it would break immersion and be seen as an attack on an established symbol.
You could take the simple shield, a symbol of protection, and try to make it mean something else. The reader will still know what that symbol usually means and hold onto that. Removing that meaning would take more effort than it is worth and likely fail. | What are you trying to accomplish here?
If a symbol is well known, getting that meaning out of reader's heads is very hard. Like if you decided that in your story the dollar sign, $, will be a symbol for, I don't know, a new political party, I think readers would be asking, So what does this party have to do with money? Do you mean that this party is all about economic policy? That they are corrupt and take bribes? Or what?
If your goal is simply that you need a symbol in your story for some idea or movement or group, why not just make up a new symbol? What is gained by trying to recycle an existing symbol?
The only reasons I can think of to re-using an existing symbol are:
(a) The characters in your story want to bring connotations of the existing idea into their new idea. The symbol represents something that is highly respected and they want to appropriate that respect. Like, many people see the Statue of Liberty as a symbol of freedom. So you use the Statue of Liberty as a symbol for their movement or organization so that people will associate them with freedom. (This could be legitimate, if they really are all about freedom, or it could be a total sham.)
(b) The characters are trying to tear down some existing idea, maybe are trying to replace it with their own. Like, they hate Christianity and want to replace it with their own religion, so they use a cross as their symbol and try to convince people to associate the cross with their new religion rather than the existing religion.
I'm not saying those are the only possible reasons, just the only ones that occur to me.
It may be necessary to distinguish why you as the author want to re-use a symbol, and why the characters in your story want to do this.
Either way, getting people to forget the meaning of a well-known symbol is hard. user10915156 mentioned how some programming languages use the $ to mean "variable". That's true. But I've been a programmer for 40 years (wow I'm getting old ...), and I still find that distracting. To some extent you can get people to separate "domains" in their minds, to see something as having one meaning in this domain and a different meaning in another domain. Like I recall once noticing with amusement that when I was talking about electronics, "CRT" meant "cathode ray tube", but when I was talking about war-gaming, "CRT" meant "combat results table". But I sincerely doubt that any American, even the person most wrapped up in programming forgets that "$" is a dollar symbol. I can't imagine someone going to the mall and seeing price tags and wondering why the store put variable names on all their products. |
44,200 | Can we change the meaning of a well established symbol and use the newly defined symbol in our writing? If so how do we go about doing so?
It am not talking about using a symbol in the context of its antithesis. That still relies on the original meaning. In such cases playing symbols in juxtaposition to their opposite meaning and using them in reverse context can be powerful and evocative.
I'm talking about changing the meaning entirely. Can it be done? I assume if it can that it will require a lot of establishing. My thought is to tear away the original meaning by establishing in some way it **does not mean** that, then slowly build up the new meaning. (Besides perhaps publishing a small companion essay explaining it.) | 2019/03/30 | [
"https://writers.stackexchange.com/questions/44200",
"https://writers.stackexchange.com",
"https://writers.stackexchange.com/users/30375/"
] | Can you completely replace the meaning in the reader's mind? Probably not - it's pretty similar to trying to change the definition of a word. What might be easier is the change the symbol's meaning *for your PoV characters*. Try showing the change from their perspectives.
Add some event that makes the question their initial beliefs, and eventually discard those beliefs. Then slowly build up the new meaning in their mind. Show *why* that symbol has a new meaning.
To use Rasdashan's shield example: Suppose the shield is adopted as the symbol of a newly-formed political party (to show that they're pledging to protect the country from some threat). This political party manages to get a psychopathic dictator elected. The shield, once a symbol of protection, is now a symbol of oppression in your world. Show your characters reacting to the change - have your MC look at someone carrying a shield and think "There's someone who might break down my door at 4 A.M." | What are you trying to accomplish here?
If a symbol is well known, getting that meaning out of reader's heads is very hard. Like if you decided that in your story the dollar sign, $, will be a symbol for, I don't know, a new political party, I think readers would be asking, So what does this party have to do with money? Do you mean that this party is all about economic policy? That they are corrupt and take bribes? Or what?
If your goal is simply that you need a symbol in your story for some idea or movement or group, why not just make up a new symbol? What is gained by trying to recycle an existing symbol?
The only reasons I can think of to re-using an existing symbol are:
(a) The characters in your story want to bring connotations of the existing idea into their new idea. The symbol represents something that is highly respected and they want to appropriate that respect. Like, many people see the Statue of Liberty as a symbol of freedom. So you use the Statue of Liberty as a symbol for their movement or organization so that people will associate them with freedom. (This could be legitimate, if they really are all about freedom, or it could be a total sham.)
(b) The characters are trying to tear down some existing idea, maybe are trying to replace it with their own. Like, they hate Christianity and want to replace it with their own religion, so they use a cross as their symbol and try to convince people to associate the cross with their new religion rather than the existing religion.
I'm not saying those are the only possible reasons, just the only ones that occur to me.
It may be necessary to distinguish why you as the author want to re-use a symbol, and why the characters in your story want to do this.
Either way, getting people to forget the meaning of a well-known symbol is hard. user10915156 mentioned how some programming languages use the $ to mean "variable". That's true. But I've been a programmer for 40 years (wow I'm getting old ...), and I still find that distracting. To some extent you can get people to separate "domains" in their minds, to see something as having one meaning in this domain and a different meaning in another domain. Like I recall once noticing with amusement that when I was talking about electronics, "CRT" meant "cathode ray tube", but when I was talking about war-gaming, "CRT" meant "combat results table". But I sincerely doubt that any American, even the person most wrapped up in programming forgets that "$" is a dollar symbol. I can't imagine someone going to the mall and seeing price tags and wondering why the store put variable names on all their products. |
385,688 | I am trying to find a unified authentication scheme for linux servers to authenticate against Active Directory. Mainly these are Ubuntu and CentOS servers.
What I need:
* Free, stable solution
* Unified UID/GID such that permissions on a folder is the same, regardless of what server it's mounted from
* Support for recursive groups, and group mapping (E.G sudo permissions, and login permissions, such that only members of group X are allowed to log in)
* Home directory crossmount, such that home directory is crossmounted across servers for a unified experience
* Unified support for at least Ubuntu and CentOS (ideally any flavor)
* Keep local accounts (at minimum root)
* Ideally, a solution that doesn't need a computer account, but simply authenticate using LDAP bind, and then do group lookup for authorization (not knowing how this would impact the other requirements)
Alternatives I've found is:
* PowerBroker® Identity Services Open Edition (Formerly Likewise Open)
* Centrify Express
* Winbind
I've had a bad experience with likewise open in the past (authentication was randomly blocking ssh login), but I haven't tested the rebranded version. Centrify I haven't tried, but seems promising, although I haven't found a good resource as to how to accomplish my goals. Winbind I'm guessing is the most customizable one, at least in order to accomplish my last point.
I'm open to whatever solution that will solve my issue, but more than anything, I'm looking for an install guide for how to accomplish all of the above on both Ubuntu and CentOS
Is there any free tool available where I can solve my requirements with relative ease, if so, what's a valid configuration to do so? | 2012/05/03 | [
"https://serverfault.com/questions/385688",
"https://serverfault.com",
"https://serverfault.com/users/74300/"
] | Winbind is likely your best issue (it's what we have running in our infastructure).
The UID/GID's wouldn't necessarily be the same from server to server but you should be able to manage the access to any folders/resources you need through Samba and have it use the domain accounts. In terms of the login and sudo permissions you should be able to manage those with the usual access.conf and sudoers files referencing the windows domain accounts once winbind is set up. I'm not entirely sure about the home directory crossmount (haven't tried to impliment that) but it is supported on both CentOS and Ubuntu. Local accounts will be able to be kept and it wouldn't require a computer account.
I have included some links below to resources that may be able to help you in the implementation.
* [Samba Winbind](http://www.samba.org/samba/docs/man/Samba-HOWTO-Collection/winbind.html)
* [Samba Groups](http://www.samba.org/samba/docs/man/Samba-HOWTO-Collection/groupmapping.html)
* [Ubuntu Winbind Howto](https://help.ubuntu.com/community/ActiveDirectoryWinbindHowto)
* [Redhat 6 Authentication docs](http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/6/html/Deployment_Guide/ch-Configuring_Authentication.html) | Have you researched if [FreeIPA](http://freeipa.org/docs/1.2/Installation_Deployment_Guide/en-US/html/chap-Installation_and_Deployment_Guide-Setting_up_Synchronization_Between_IPA_and_Active_Directory.html) meets your needs?
Also check this [link](https://serverfault.com/questions/50925/what-would-it-take-to-get-an-active-directory-like-system-in-a-linux-environment/). |
64,320 | I've been reading this:
<http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html>
But there are some things I don't understand, for example the article says to use something like this for pathfinding with diagonal movement:
```
function heuristic(node) =
dx = abs(node.x - goal.x)
dy = abs(node.y - goal.y)
return D * max(dx, dy)
```
I don't know how do set D to get a natural looking path like in the article, I set D to the lowest cost between adjacent squares like it said, and I don't know what they meant by the stuff about the heuristic should be 4\*D, that does not seem to change any thing.
This is my heuristic function and move function:
```
def heuristic(self, node, goal):
D = 5
dx = abs(node.x - goal.x)
dy = abs(node.y - goal.y)
return D * max(dx, dy)
def move_cost(self, current, node):
cross = abs(current.x - node.x) == 1 and abs(current.y - node.y) == 1
return 7 if cross else 5
```
Result:

The smooth sailing path we want to happen:

The rest of my code: <http://pastebin.com/TL2cEkeX>
---
**Update**
This is the best solution I have found so far:
```
def heuristic(node, start, goal):
dx1 = node.x - goal.x
dy1 = node.y - goal.y
dx2 = start.x - goal.x
dy2 = start.y - goal.y
cross = abs(dx1*dy2 - dx2*dy1)
dx3 = abs(dx1)
dy3 = abs(dy1)
return 5 + (cross*0.01) * (dx3+dy3) + (sqrt(2)-2) * min(dx3, dy3)
def move_cost(current, node):
cross = abs(current.x - node.x) == 1 and abs(current.y - node.y) == 1
return 7 if cross else 5
```
It produces the desired path from the second pic, but does not handle obstacles very well (tends to crawl on walls) and fails to produce optimal paths sometimes on longer distances.
What are some tweaks and optimizations I can apply to improve it? | 2013/11/01 | [
"https://gamedev.stackexchange.com/questions/64320",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/18564/"
] | A\* gives you the shortest path in the graph. When using a grid as your graph there are often *multiple* shortest paths. In your first diagram, that *is* one of the shortest paths. It puts all the axial movements first and all the diagonal movements afterwards. But that's the same length path as if you put all the diagonals first, or if you mixed axial and diagonal movements. These are all equivalently short, and which one A\* picks depends on how the code is written and how the graph is represented.
I think what you're wanting is either:
1. You need to move on the grid, but you want to mix the axial and diagonal steps so that it looks better. One approach is to choose one of the other equally short paths; keep reading that Heuristics page to find “tie breaking”. Another approach is when you're evaluating neighbors, choose randomly which one to evaluate first so that it doesn't always pick one before the other. I do *not* recommend using Euclidean/Cartesian distance if you want to move on the grid; it's a mismatch that makes A\* run slower.
2. You don't need to move on the grid, and want to move in a straight line. One approach is to straighten out the paths using “string pulling”. You're looking for places where the path turns, and drawing straight lines between those points. Another approach is to apply this to the underlying graph itself. Instead of pathfinding on the grid, pathfind on the key points on the map, and then move along straight lines between those key points. You can see an example [here](http://theory.stanford.edu/~amitp/GameProgramming/MapRepresentations.html#polygonal-maps). Yet another approach is the [Theta\* algorithm](http://aigamedev.com/open/tutorials/theta-star-any-angle-paths/). | The A\* algorithm allows you to assign different costs to path edges. You can also assign costs depending on circumstances. This is your main tool to shape A\* paths into looking the way you want them to look.
When you want to discourage long diagonals, you can penalize them. Add a tiny bit of cost for each time the path goes into the same direction. When you do this, the algorithm will automatically try to distribute diagonal steps as evenly as possible over the whole path. Just make sure this additional cost is never more the the cost of taking an additional edge, or the algorithm will start to make completely unnecessary detours just to avoid straight lines.
A good formula could be:
`cost = normal_cost * (1.1 - 0.1 / num_of_steps_in_the_same_direction`)
Note that this requires that the path-cost is tracked as floating-point values, not as integers. |
64,320 | I've been reading this:
<http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html>
But there are some things I don't understand, for example the article says to use something like this for pathfinding with diagonal movement:
```
function heuristic(node) =
dx = abs(node.x - goal.x)
dy = abs(node.y - goal.y)
return D * max(dx, dy)
```
I don't know how do set D to get a natural looking path like in the article, I set D to the lowest cost between adjacent squares like it said, and I don't know what they meant by the stuff about the heuristic should be 4\*D, that does not seem to change any thing.
This is my heuristic function and move function:
```
def heuristic(self, node, goal):
D = 5
dx = abs(node.x - goal.x)
dy = abs(node.y - goal.y)
return D * max(dx, dy)
def move_cost(self, current, node):
cross = abs(current.x - node.x) == 1 and abs(current.y - node.y) == 1
return 7 if cross else 5
```
Result:

The smooth sailing path we want to happen:

The rest of my code: <http://pastebin.com/TL2cEkeX>
---
**Update**
This is the best solution I have found so far:
```
def heuristic(node, start, goal):
dx1 = node.x - goal.x
dy1 = node.y - goal.y
dx2 = start.x - goal.x
dy2 = start.y - goal.y
cross = abs(dx1*dy2 - dx2*dy1)
dx3 = abs(dx1)
dy3 = abs(dy1)
return 5 + (cross*0.01) * (dx3+dy3) + (sqrt(2)-2) * min(dx3, dy3)
def move_cost(current, node):
cross = abs(current.x - node.x) == 1 and abs(current.y - node.y) == 1
return 7 if cross else 5
```
It produces the desired path from the second pic, but does not handle obstacles very well (tends to crawl on walls) and fails to produce optimal paths sometimes on longer distances.
What are some tweaks and optimizations I can apply to improve it? | 2013/11/01 | [
"https://gamedev.stackexchange.com/questions/64320",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/18564/"
] | The A\* algorithm allows you to assign different costs to path edges. You can also assign costs depending on circumstances. This is your main tool to shape A\* paths into looking the way you want them to look.
When you want to discourage long diagonals, you can penalize them. Add a tiny bit of cost for each time the path goes into the same direction. When you do this, the algorithm will automatically try to distribute diagonal steps as evenly as possible over the whole path. Just make sure this additional cost is never more the the cost of taking an additional edge, or the algorithm will start to make completely unnecessary detours just to avoid straight lines.
A good formula could be:
`cost = normal_cost * (1.1 - 0.1 / num_of_steps_in_the_same_direction`)
Note that this requires that the path-cost is tracked as floating-point values, not as integers. | Adapting A\*
------------
As Philipp said, you should add costs when the direction doesn't change for long time. But, the function by Philipp may quickly lead to summing up additional costs, that are higher than the cost for traversing an additional tile. But his key idea is correct!
It seems easy to adapt A\* to calculate "all" optimal paths (with shortest length) and then selecting one of them by another heuristic. But there is a problem. If you have a long path, there might be a lot of solutions with optimal length. This causes the A\* algorithm to take much longer to compute all these other solutions, too. This is because the grid. You can not walk 80 degrees instead of 90 degrees, which leads to multiple suboptimal solutions instead of one optimal solution. For imagination, imagine a map without obstacles. The x-distance is 2 the y-distance is 3. This means, all shortest paths have 2 diagonal moves and 1 straight move. There are 3 valid combinations: S-D-D, D-S-D, D-D-S (where D=diagonal, S=straight) for this simple path. The real "fun" starts already when you have paths with e.g. 3 straight and 2 diagonal moves: S-S-S-D-D, S-S-D-S-D, S-S-D-D-S, S-D-S-S-D, S-D-S-D-S, S-D-D-S-S, D-S-S-S-D, D-S-S-D-S, D-S-D-S-S, D-D-S-S-S (10 variations of the shortest path, if I didn't miss any). I think you should have got the idea...
So we should fix this by adapting the cost function in a way that fewer solutions (or even only one solution) are "optimal".
Adapting the Cost Function
--------------------------
Doing the adaptation as Philipp suggests in his example formula will give you much better results, but has still some problems. It will not evenly distribute the shorter/longer "parts" along the path, meaning: the direction changes will be more often at the beginning of the path or vice-versa.
Additionally, a path with endlessly having the actor to "turn" seems to be suboptimal when observed by a human. As it takes time (to show the turn animation) and therefore it must be slower.
How ever, instead of using floats for the costs you can implement a "secondary cost" or secondary sort criteria. If the primary costs are the same the secondary cost is used to estimate which solution is to be preferred. This will not accidentally cause the primary costs (route length in grid measure) to increase. |
64,320 | I've been reading this:
<http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html>
But there are some things I don't understand, for example the article says to use something like this for pathfinding with diagonal movement:
```
function heuristic(node) =
dx = abs(node.x - goal.x)
dy = abs(node.y - goal.y)
return D * max(dx, dy)
```
I don't know how do set D to get a natural looking path like in the article, I set D to the lowest cost between adjacent squares like it said, and I don't know what they meant by the stuff about the heuristic should be 4\*D, that does not seem to change any thing.
This is my heuristic function and move function:
```
def heuristic(self, node, goal):
D = 5
dx = abs(node.x - goal.x)
dy = abs(node.y - goal.y)
return D * max(dx, dy)
def move_cost(self, current, node):
cross = abs(current.x - node.x) == 1 and abs(current.y - node.y) == 1
return 7 if cross else 5
```
Result:

The smooth sailing path we want to happen:

The rest of my code: <http://pastebin.com/TL2cEkeX>
---
**Update**
This is the best solution I have found so far:
```
def heuristic(node, start, goal):
dx1 = node.x - goal.x
dy1 = node.y - goal.y
dx2 = start.x - goal.x
dy2 = start.y - goal.y
cross = abs(dx1*dy2 - dx2*dy1)
dx3 = abs(dx1)
dy3 = abs(dy1)
return 5 + (cross*0.01) * (dx3+dy3) + (sqrt(2)-2) * min(dx3, dy3)
def move_cost(current, node):
cross = abs(current.x - node.x) == 1 and abs(current.y - node.y) == 1
return 7 if cross else 5
```
It produces the desired path from the second pic, but does not handle obstacles very well (tends to crawl on walls) and fails to produce optimal paths sometimes on longer distances.
What are some tweaks and optimizations I can apply to improve it? | 2013/11/01 | [
"https://gamedev.stackexchange.com/questions/64320",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/18564/"
] | A\* gives you the shortest path in the graph. When using a grid as your graph there are often *multiple* shortest paths. In your first diagram, that *is* one of the shortest paths. It puts all the axial movements first and all the diagonal movements afterwards. But that's the same length path as if you put all the diagonals first, or if you mixed axial and diagonal movements. These are all equivalently short, and which one A\* picks depends on how the code is written and how the graph is represented.
I think what you're wanting is either:
1. You need to move on the grid, but you want to mix the axial and diagonal steps so that it looks better. One approach is to choose one of the other equally short paths; keep reading that Heuristics page to find “tie breaking”. Another approach is when you're evaluating neighbors, choose randomly which one to evaluate first so that it doesn't always pick one before the other. I do *not* recommend using Euclidean/Cartesian distance if you want to move on the grid; it's a mismatch that makes A\* run slower.
2. You don't need to move on the grid, and want to move in a straight line. One approach is to straighten out the paths using “string pulling”. You're looking for places where the path turns, and drawing straight lines between those points. Another approach is to apply this to the underlying graph itself. Instead of pathfinding on the grid, pathfind on the key points on the map, and then move along straight lines between those key points. You can see an example [here](http://theory.stanford.edu/~amitp/GameProgramming/MapRepresentations.html#polygonal-maps). Yet another approach is the [Theta\* algorithm](http://aigamedev.com/open/tutorials/theta-star-any-angle-paths/). | Adapting A\*
------------
As Philipp said, you should add costs when the direction doesn't change for long time. But, the function by Philipp may quickly lead to summing up additional costs, that are higher than the cost for traversing an additional tile. But his key idea is correct!
It seems easy to adapt A\* to calculate "all" optimal paths (with shortest length) and then selecting one of them by another heuristic. But there is a problem. If you have a long path, there might be a lot of solutions with optimal length. This causes the A\* algorithm to take much longer to compute all these other solutions, too. This is because the grid. You can not walk 80 degrees instead of 90 degrees, which leads to multiple suboptimal solutions instead of one optimal solution. For imagination, imagine a map without obstacles. The x-distance is 2 the y-distance is 3. This means, all shortest paths have 2 diagonal moves and 1 straight move. There are 3 valid combinations: S-D-D, D-S-D, D-D-S (where D=diagonal, S=straight) for this simple path. The real "fun" starts already when you have paths with e.g. 3 straight and 2 diagonal moves: S-S-S-D-D, S-S-D-S-D, S-S-D-D-S, S-D-S-S-D, S-D-S-D-S, S-D-D-S-S, D-S-S-S-D, D-S-S-D-S, D-S-D-S-S, D-D-S-S-S (10 variations of the shortest path, if I didn't miss any). I think you should have got the idea...
So we should fix this by adapting the cost function in a way that fewer solutions (or even only one solution) are "optimal".
Adapting the Cost Function
--------------------------
Doing the adaptation as Philipp suggests in his example formula will give you much better results, but has still some problems. It will not evenly distribute the shorter/longer "parts" along the path, meaning: the direction changes will be more often at the beginning of the path or vice-versa.
Additionally, a path with endlessly having the actor to "turn" seems to be suboptimal when observed by a human. As it takes time (to show the turn animation) and therefore it must be slower.
How ever, instead of using floats for the costs you can implement a "secondary cost" or secondary sort criteria. If the primary costs are the same the secondary cost is used to estimate which solution is to be preferred. This will not accidentally cause the primary costs (route length in grid measure) to increase. |
586,201 | **What I want to do:** Have a Ubuntu development VM on Windows 8.1.
**Setup:** I have a new SSD that I just installed Windows onto. I have an old SSD (60GB) that has Ubuntu on it.
**Problem:** I am a developer and have projects on the old SSD and don't want to screw anything up.
I think what I should do is take the entire development folder I have (with all of my projects) and a dump of my databases and move them to Windows. At that point I can wipe the drive and start fresh, using the drive for VMs and storage.
Is that doable? I know I would still need to put my projects onto the VM, and though I don't know how at least I have the files and can figure it out. | 2015/02/16 | [
"https://askubuntu.com/questions/586201",
"https://askubuntu.com",
"https://askubuntu.com/users/278035/"
] | As it is possible to also [attach a physical disk to a virtual machine](https://askubuntu.com/questions/192254/access-secondary-hard-disk-from-virtual-machine) this procedure may lead to data loss on write access to this disk. If your data matter I would therefore not recommend you take the risk.
A much easier way to move your data, that presumably are stored on a file system inaccessible to Windows, is just booting an Ubuntu live system from where you can mount both, your Ubuntu SSD, and your Windows drive. You can then safely copy the data over from the SSD to your hard drive with no risk to these data, as these are still untouched on the SSD.
Alternatively we can also install [Windows utilities to mount your Ubuntu partitions](https://askubuntu.com/questions/20853/mount-ubuntus-partition-on-windows-7). The you are able to copy and paste your data over to your Windows drive.
After you had set up your Ubuntu VM you can give the data folder on your Windows host access via [shared folders](https://askubuntu.com/questions/252853/how-to-mount-a-virtualbox-shared-folder-at-startup), networking, or copy the data into the VM (not recommended because making backups is much harder). | While there are ways to create virtual environments right from a hard drive (if you were to boot back to your Ubuntu system) I would be worried about something going wrong and losing the data. Your own suggestion of moving the files and doing a data dump of the database is the route I take when I move from one development environment to another.
Load your Ubuntu drive back in the machine and boot to it, export the database(s) and back up your exports and code.
Then you can load your Windows drive back in, format your 60 gig drive for use with windows to hold the VM(s).
Create the VM, and install whatever OS you're going to use.
To get the files onto the new VM you have a couple options. First you could share a folder between the VM and the host computer (not something I typically do, but specifically for personal reasons), or, in the event your development environment (VM) will continue to be Ubuntu you could simply install openssh-server on your Ubuntu VM, then using an FTP client on your windows machine (I typically use Filezilla) you can SFTP into your virtual machine and transfer all your files to it.
Filezilla can be downloaded free from their website, and to install openssh-server on your VM you simply open a terminal `CTRL`-`ALT`-`T` and enter
```
sudo apt-get install openssh-server
``` |
34,827,159 | I have a class called `Car`, this class has attributes such as: id, name, price, color and size. When I am creating an object, for color and size I want a list to select the attribute value from. I don't want the user to write "black" or "small", i want to find them somewhere in the app.
```
Car c1 = new Car(1, "Super Car", 152.5, "black", "small");
```
Does anyone can help me with that? | 2016/01/16 | [
"https://Stackoverflow.com/questions/34827159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5798422/"
] | How about this:
```
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string str1, str2;
int i;
getline(cin, str1);
getline(cin, str2);
if(str1 != str2)
{
bool restart = true;
while(restart)
{
restart = false;
const int str1Len = str1.size();
for (int i=0 ; i<str1Len ; i++)
{
const int str2Len = str2.size();
for (int j=0 ; j<str2Len ; j++)
{
if (str1[i]==str2[j])
{
str1 = str1.erase(i,1);
str2 = str2.erase(j,1);
restart = true;
break;
}
}
if(restart)
break;
}
}
}
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << endl;
return 0;
}
```
In C++ you can use `std::string` so you don't have to mess around with fixed char arrays. I'm guessing you don't want that. Because you did not tag this as C++11 I did not use for-each loops. I'm sure though it wouldn't change the result. | Writing modern C++ code always produces smaller, and compact code, as compared to writing C code with random bits of C++ thrown in:
```
#include <iostream>
#include <string>
int main()
{
std::string str1, str2;
std::getline(std::cin, str1);
std::getline(std::cin, str2);
size_t i;
for (i=0; i<str1.size() && i<str2.size(); ++i)
if (str1[i] != str2[i])
break;
std::cout << str1.substr(i) << std::endl;
std::cout << str2.substr(i) << std::endl;
return 0;
}
```
Instead of trying to figure out which parts of both strings are different, you will find it much easier, and simpler, to think of the problem on the other end: find out which initial parts of each string are the same with each other. Then what's left is, obviously, your answer.
In the original version, limiting each string to a 100 characters is not important, and does not affect the algorithm, so I left it out. If you still wish to do that, the changes would also be trivial, and I'll leave that part as your homework assignment. |
34,827,159 | I have a class called `Car`, this class has attributes such as: id, name, price, color and size. When I am creating an object, for color and size I want a list to select the attribute value from. I don't want the user to write "black" or "small", i want to find them somewhere in the app.
```
Car c1 = new Car(1, "Super Car", 152.5, "black", "small");
```
Does anyone can help me with that? | 2016/01/16 | [
"https://Stackoverflow.com/questions/34827159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5798422/"
] | If you may not change the strings themselves then you can use an approach with `std::set` container. For example
```
#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <iterator>
int main()
{
std::string s1( "abd" );
std::string s2( "ace" );
std::set<char> set1( s1.begin(), s1.end() );
std::set<char> set2( s2.begin(), s2.end() );
std::set_symmetric_difference( set1.begin(), set1.end(), set2.begin(), set2.end(),
std::ostream_iterator<char>( std::cout ) );
std::cout << std::endl;
}
```
The output is
```
bcde
```
At least the program gives the expected result `d` for strings `abc` and `abcd`.:)
Otherwise you could sort the strings and apply the same standard algorithm `std::set_symmetric_difference`. | Writing modern C++ code always produces smaller, and compact code, as compared to writing C code with random bits of C++ thrown in:
```
#include <iostream>
#include <string>
int main()
{
std::string str1, str2;
std::getline(std::cin, str1);
std::getline(std::cin, str2);
size_t i;
for (i=0; i<str1.size() && i<str2.size(); ++i)
if (str1[i] != str2[i])
break;
std::cout << str1.substr(i) << std::endl;
std::cout << str2.substr(i) << std::endl;
return 0;
}
```
Instead of trying to figure out which parts of both strings are different, you will find it much easier, and simpler, to think of the problem on the other end: find out which initial parts of each string are the same with each other. Then what's left is, obviously, your answer.
In the original version, limiting each string to a 100 characters is not important, and does not affect the algorithm, so I left it out. If you still wish to do that, the changes would also be trivial, and I'll leave that part as your homework assignment. |
34,827,159 | I have a class called `Car`, this class has attributes such as: id, name, price, color and size. When I am creating an object, for color and size I want a list to select the attribute value from. I don't want the user to write "black" or "small", i want to find them somewhere in the app.
```
Car c1 = new Car(1, "Super Car", 152.5, "black", "small");
```
Does anyone can help me with that? | 2016/01/16 | [
"https://Stackoverflow.com/questions/34827159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5798422/"
] | If you may not change the strings themselves then you can use an approach with `std::set` container. For example
```
#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <iterator>
int main()
{
std::string s1( "abd" );
std::string s2( "ace" );
std::set<char> set1( s1.begin(), s1.end() );
std::set<char> set2( s2.begin(), s2.end() );
std::set_symmetric_difference( set1.begin(), set1.end(), set2.begin(), set2.end(),
std::ostream_iterator<char>( std::cout ) );
std::cout << std::endl;
}
```
The output is
```
bcde
```
At least the program gives the expected result `d` for strings `abc` and `abcd`.:)
Otherwise you could sort the strings and apply the same standard algorithm `std::set_symmetric_difference`. | How about this:
```
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string str1, str2;
int i;
getline(cin, str1);
getline(cin, str2);
if(str1 != str2)
{
bool restart = true;
while(restart)
{
restart = false;
const int str1Len = str1.size();
for (int i=0 ; i<str1Len ; i++)
{
const int str2Len = str2.size();
for (int j=0 ; j<str2Len ; j++)
{
if (str1[i]==str2[j])
{
str1 = str1.erase(i,1);
str2 = str2.erase(j,1);
restart = true;
break;
}
}
if(restart)
break;
}
}
}
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << endl;
return 0;
}
```
In C++ you can use `std::string` so you don't have to mess around with fixed char arrays. I'm guessing you don't want that. Because you did not tag this as C++11 I did not use for-each loops. I'm sure though it wouldn't change the result. |
34,827,159 | I have a class called `Car`, this class has attributes such as: id, name, price, color and size. When I am creating an object, for color and size I want a list to select the attribute value from. I don't want the user to write "black" or "small", i want to find them somewhere in the app.
```
Car c1 = new Car(1, "Super Car", 152.5, "black", "small");
```
Does anyone can help me with that? | 2016/01/16 | [
"https://Stackoverflow.com/questions/34827159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5798422/"
] | How about this:
```
#include <iostream>
#include <string>
using namespace std;
int main()
{
std::string str1, str2;
int i;
getline(cin, str1);
getline(cin, str2);
if(str1 != str2)
{
bool restart = true;
while(restart)
{
restart = false;
const int str1Len = str1.size();
for (int i=0 ; i<str1Len ; i++)
{
const int str2Len = str2.size();
for (int j=0 ; j<str2Len ; j++)
{
if (str1[i]==str2[j])
{
str1 = str1.erase(i,1);
str2 = str2.erase(j,1);
restart = true;
break;
}
}
if(restart)
break;
}
}
}
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << endl;
return 0;
}
```
In C++ you can use `std::string` so you don't have to mess around with fixed char arrays. I'm guessing you don't want that. Because you did not tag this as C++11 I did not use for-each loops. I'm sure though it wouldn't change the result. | its weird, I was going to edit your question but i realized it was the answer.
You’re missing a end bracket for that first if statement, I put that in.
you're comparing an int to a unsinged int with strlen(), I left it in the conext of 100 character limit, its fine.
int i =0; is not the Same int as in your for loop, and is unused.I commented that out.
Is there a reason not to use namespace std?
Those other header files were not necessary.
added a line break, so I can see what the output is easily.
I'm not sure what exit\_success is, I’d use return 0;
```
#include<iostream>
#include<cstdlib>
#include <iomanip>
//----------------------
using namespace std;
//-------------------
const int MAX_STR_LEN=100;
//-----------------------
int main()
{
char str1 [MAX_STR_LEN];
char str2 [MAX_STR_LEN];
// int i;
cin >> setw(MAX_STR_LEN)>>str1;
cin >> setw(MAX_STR_LEN)>>str2;
if (strcmp(str1, str2)!=0)
{
for (int i=0; i < strlen(str1); i++)
{
for (int j=0; j < strlen(str2); j++)
{
if (str1[i]==str2[j]) // we want to check whats common first
cout << str2[j];
}
}
cout <<"\n";
}
return 0;
}
```
I suspect this is the answer you desired. sure, its C/C++ flavour so what? |
34,827,159 | I have a class called `Car`, this class has attributes such as: id, name, price, color and size. When I am creating an object, for color and size I want a list to select the attribute value from. I don't want the user to write "black" or "small", i want to find them somewhere in the app.
```
Car c1 = new Car(1, "Super Car", 152.5, "black", "small");
```
Does anyone can help me with that? | 2016/01/16 | [
"https://Stackoverflow.com/questions/34827159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5798422/"
] | If you may not change the strings themselves then you can use an approach with `std::set` container. For example
```
#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <iterator>
int main()
{
std::string s1( "abd" );
std::string s2( "ace" );
std::set<char> set1( s1.begin(), s1.end() );
std::set<char> set2( s2.begin(), s2.end() );
std::set_symmetric_difference( set1.begin(), set1.end(), set2.begin(), set2.end(),
std::ostream_iterator<char>( std::cout ) );
std::cout << std::endl;
}
```
The output is
```
bcde
```
At least the program gives the expected result `d` for strings `abc` and `abcd`.:)
Otherwise you could sort the strings and apply the same standard algorithm `std::set_symmetric_difference`. | its weird, I was going to edit your question but i realized it was the answer.
You’re missing a end bracket for that first if statement, I put that in.
you're comparing an int to a unsinged int with strlen(), I left it in the conext of 100 character limit, its fine.
int i =0; is not the Same int as in your for loop, and is unused.I commented that out.
Is there a reason not to use namespace std?
Those other header files were not necessary.
added a line break, so I can see what the output is easily.
I'm not sure what exit\_success is, I’d use return 0;
```
#include<iostream>
#include<cstdlib>
#include <iomanip>
//----------------------
using namespace std;
//-------------------
const int MAX_STR_LEN=100;
//-----------------------
int main()
{
char str1 [MAX_STR_LEN];
char str2 [MAX_STR_LEN];
// int i;
cin >> setw(MAX_STR_LEN)>>str1;
cin >> setw(MAX_STR_LEN)>>str2;
if (strcmp(str1, str2)!=0)
{
for (int i=0; i < strlen(str1); i++)
{
for (int j=0; j < strlen(str2); j++)
{
if (str1[i]==str2[j]) // we want to check whats common first
cout << str2[j];
}
}
cout <<"\n";
}
return 0;
}
```
I suspect this is the answer you desired. sure, its C/C++ flavour so what? |
28,536,111 | I am using facebook api for PHP.
i can get only basic information like username,fullname,link,id.
i cannot get country,email,place..etc
```
<?php
session_start();
// added in v4.0.0
require_once 'autoload.php';
require_once( 'src/Facebook/FacebookSession.php');
require_once( 'src/Facebook/FacebookRequest.php' );
require_once( 'src/Facebook/FacebookResponse.php' );
require_once( 'src/Facebook/FacebookSDKException.php' );
require_once( 'src/Facebook/FacebookRequestException.php' );
require_once( 'src/Facebook/FacebookRedirectLoginHelper.php');
require_once( 'src/Facebook/FacebookAuthorizationException.php' );
require_once( 'src/Facebook/GraphObject.php' );
require_once( 'src/Facebook/GraphLocation.php' );
require_once( 'src/Facebook/GraphUser.php' );
require_once( 'src/Facebook/GraphSessionInfo.php' );
require_once( 'src/Facebook/Entities/AccessToken.php');
require_once( 'src/Facebook/HttpClients/FacebookCurl.php' );
require_once( 'src/Facebook/HttpClients/FacebookHttpable.php');
require_once( 'src/Facebook/HttpClients/FacebookCurlHttpClient.php');
/* USE NAMESPACES */
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphLocation;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;
use Facebook\FacebookHttpable;
use Facebook\FacebookCurlHttpClient;
use Facebook\FacebookCurl;
// init app with app id and secret
FacebookSession::setDefaultApplication( '518573344952566','a3afc2397a81e216e60714f83142e2f9' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('http://localhost/1353/fbconfig.php' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
/*
$graphObject = $response->getGraphObject();
$fbid = $graphObject->getProperty('id'); // To Get Facebook ID
$fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
$femail = $graphObject->getProperty('email');
$fplace=$graphObject->getProperty('place');
/* ---- Session Variables -----*/
// Get the base class GraphObject from the response
// Get the base class GraphObject from the response
$object = $response->getGraphObject();
// Get the response typed as a GraphUser
$user = $response->getGraphObject(GraphUser::className());
// or convert the base object previously accessed
// $user = $object->cast(GraphUser::className());
// Get the response typed as a GraphLocation
$loc = $response->getGraphObject(GraphLocation::className());
// or convert the base object previously accessed
// $loc = $object->cast(GraphLocation::className());
// User example
echo $object->getProperty('name');
echo $user->getName();
// Location example
echo $object->getProperty('country');
echo $loc->getCountry();
echo $object->getProperty('email');
// SessionInfo example
$info = $session->getSessionInfo();
echo $info->getxpiresAt();
/* ---- header location after session ----*/
header("Location: index.php");
} else {
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
}
?>
```
This is my code, When i print like country , email ,place, it shows nothing !
when i print `$response`
it shows following
```
Facebook\FacebookRequest Object ( [session:Facebook\FacebookRequest:private] => Facebook\FacebookSession Object ( [accessToken:Facebook\FacebookSession:private] => Facebook\Entities\AccessToken Object ( [accessToken:protected] => CAAHXo8QEEPYBAPwxcD0DT08AuysfOCGl7TWYCViyZB0PnXFQGB5LrfreJh3hxM1xtDQpD7zqJReTJESo96VS4Wi2qIQRKzpMaWZCBkTFIlHzyhbq96k8aXJGdS77jysotckuGEcgyCPJp7veRyJL4SZCN8a9m9sZAKtcvS3ZCLO6COorMTQKSYAyJAXkYuIb1biS7sLd0MMhH3c9aylAJ [machineId:protected] => [expiresAt:protected] => ) [signedRequest:Facebook\FacebookSession:private] => ) [method:Facebook\FacebookRequest:private] => GET [path:Facebook\FacebookRequest:private] => /me [params:Facebook\FacebookRequest:private] => Array ( [access_token] => CAAHXo8QEEPYBAPwxcD0DT08AuysfOCGl7TWYCViyZB0PnXFQGB5LrfreJh3hxM1xtDQpD7zqJReTJESo96VS4Wi2qIQRKzpMaWZCBkTFIlHzyhbq96k8aXJGdS77jysotckuGEcgyCPJp7veRyJL4SZCN8a9m9sZAKtcvS3ZCLO6COorMTQKSYAyJAXkYuIb1biS7sLd0MMhH3c9aylAJ [appsecret_proof] => fbd9e3248da5678fc68be8bfcee6368ed56fdf71507d16d7b19dc494c22280dc ) [version:Facebook\FacebookRequest:private] => v2.2 [etag:Facebook\FacebookRequest:private] => )
``` | 2015/02/16 | [
"https://Stackoverflow.com/questions/28536111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975952/"
] | From my understanding of your Views stack in your `viewController`, you simply need to move the transparent view to the front of the stack (it is currently at the back of your `superView`).
You can do this by calling.
```
[self.view bringSubViewToFront:<your transparent view>];
```
And in the `storyboard` just set the view to the correct values
If you want to hide the view just call
```
[self.view bringSubViewToFront:<your tableView>];
```
**EDIT**
To create a transparent view on top of you `UITableView`, you need to add a `UIView` in the `storyBoard` that is a `subView` of your `viewController` main view(then set all the attributes you want in the attributes inspector). Your `tableView` need to be also a `subView` of your `viewController` main view.
\*make sure that the transparent view is front of the `tableView` in your `storyBoard`
In order to handle the gestures (because the transparent view is "blocking" the gestures from the `tableView` read this post [Link](https://stackoverflow.com/questions/12960427/passing-vertical-scrolling-gesture-to-uitableview-below)) | ```
tableView.backgroundColor = [UIColor clearColor];
tableView.backgroundView.backgroundColor = [UIColor clearColor];
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
if ([view isKindOfClass:[UITableViewHeaderFooterView class]])
{
UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
headerView.contentView.backgroundColor = [UIColor clearColor];
headerView.backgroundView.backgroundColor = [UIColor clearColor];
}
}
``` |
258,955 | Recently Foxit Reader started popping up the UAC dialog on each start asking if I want to run it as administrator, and allow it to make changes to my computer.
How could I make that stop? Disabling UAC is not an option. | 2011/03/18 | [
"https://superuser.com/questions/258955",
"https://superuser.com",
"https://superuser.com/users/12652/"
] | Find a foxit shortcut, right click, properties, compatibility, change for all users, and uncheck run this program as administrator. | There's a problem with the plugin loader of build 1126. It's not about elevated permissions on the shortcut it makes.
<http://forums.foxitsoftware.com/forum/portable-document-format-pdf-tools/foxit-reader/42009-why-is-there-a-uac-prompt-win7-with-the-latest-version> |
219,138 | I need to run a Linux CLI command and get its stdout output from C.
I can use pipe() to create a pipe, then fork/exec, redirecting child's stdout descriptor into the pipe before calling exec(), and reading from the pipe in parent. Plus I'll need to wait on the child.
Is there a simple call to do fork + redirect + exec + wait, like system() does fork + exec + wait, only system() doesn't do the redirect.
There's popen(), which does fork + redirect + exec, but doesn't do wait, so I can't get exit status. | 2008/10/20 | [
"https://Stackoverflow.com/questions/219138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23420/"
] | Is this it?
```
NAME
popen, pclose - process I/O
SYNOPSIS
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
DESCRIPTION
The popen() function opens a process by creating a pipe, forking,
and invoking the shell. Since a pipe is by definition unidirectional, the
type argument may specify only reading or writing, not both; the resulting
stream is correspondingly read-only or write-only.
The command argument is a pointer to a null-terminated string
containing a shell command line. This command is passed to /bin/sh
using the -c flag; interpretation, if any, is performed by the shell.
The type argument is a pointer to a null-terminated string which must be
either ‘r’ for reading or ‘w’ for writing.
The return value from popen() is a normal standard I/O stream in
all respects save that it must be closed with pclose() rather than fclose().
Writing to such a stream writes to the standard input of the command; the
command’s standard output is the same as that of the process that called
popen(), unless this is altered by the command itself. Conversely, reading
from a ‘‘popened’’ stream reads the command’s standard output, and the
command’s standard input is the same as that of the process that called
popen().
Note that output popen() streams are fully buffered by default.
The pclose() function waits for the associated process to terminate
and returns the exit status of the command as returned by wait4().
``` | Use `popen()` and `pclose()`.
---
`popen()` does not actually wait, of course, but reads on the pipe will block until there is data available.
`pclose()` waits, but calling it prematurely could cut off some output from the forked process. You'll want to determine from the stream when the child is done...
---
Possibly already discussed at [[How can I run an external program from C and parse its output?](https://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output)](https://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output) |
219,138 | I need to run a Linux CLI command and get its stdout output from C.
I can use pipe() to create a pipe, then fork/exec, redirecting child's stdout descriptor into the pipe before calling exec(), and reading from the pipe in parent. Plus I'll need to wait on the child.
Is there a simple call to do fork + redirect + exec + wait, like system() does fork + exec + wait, only system() doesn't do the redirect.
There's popen(), which does fork + redirect + exec, but doesn't do wait, so I can't get exit status. | 2008/10/20 | [
"https://Stackoverflow.com/questions/219138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23420/"
] | GLib has a nice function for this -- `g_spawn_sync()`:
<http://library.gnome.org/devel/glib/stable/glib-Spawning-Processes.html#g-spawn-sync>
For example, to run a command and get its exit status and output:
```
const char *argv[] = { "your_command", NULL };
char *output = NULL; // will contain command output
GError *error = NULL;
int exit_status = 0;
if (!g_spawn_sync(NULL, argv, NULL, 0, NULL, NULL,
&output, NULL, &exit_status, &error))
{
// handle error here
}
``` | Use `popen()` and `pclose()`.
---
`popen()` does not actually wait, of course, but reads on the pipe will block until there is data available.
`pclose()` waits, but calling it prematurely could cut off some output from the forked process. You'll want to determine from the stream when the child is done...
---
Possibly already discussed at [[How can I run an external program from C and parse its output?](https://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output)](https://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output) |
219,138 | I need to run a Linux CLI command and get its stdout output from C.
I can use pipe() to create a pipe, then fork/exec, redirecting child's stdout descriptor into the pipe before calling exec(), and reading from the pipe in parent. Plus I'll need to wait on the child.
Is there a simple call to do fork + redirect + exec + wait, like system() does fork + exec + wait, only system() doesn't do the redirect.
There's popen(), which does fork + redirect + exec, but doesn't do wait, so I can't get exit status. | 2008/10/20 | [
"https://Stackoverflow.com/questions/219138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23420/"
] | Is this it?
```
NAME
popen, pclose - process I/O
SYNOPSIS
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
DESCRIPTION
The popen() function opens a process by creating a pipe, forking,
and invoking the shell. Since a pipe is by definition unidirectional, the
type argument may specify only reading or writing, not both; the resulting
stream is correspondingly read-only or write-only.
The command argument is a pointer to a null-terminated string
containing a shell command line. This command is passed to /bin/sh
using the -c flag; interpretation, if any, is performed by the shell.
The type argument is a pointer to a null-terminated string which must be
either ‘r’ for reading or ‘w’ for writing.
The return value from popen() is a normal standard I/O stream in
all respects save that it must be closed with pclose() rather than fclose().
Writing to such a stream writes to the standard input of the command; the
command’s standard output is the same as that of the process that called
popen(), unless this is altered by the command itself. Conversely, reading
from a ‘‘popened’’ stream reads the command’s standard output, and the
command’s standard input is the same as that of the process that called
popen().
Note that output popen() streams are fully buffered by default.
The pclose() function waits for the associated process to terminate
and returns the exit status of the command as returned by wait4().
``` | Here is what I use:
```
/* simply invoke a app, pipe output*/
pipe = popen(buf, "r" );
if (pipe == NULL ) {
printf("invoking %s failed: %s\n", buf, strerror(errno));
return 1;
}
waitfor(10);
while(!feof(pipe) ) {
if( fgets( buf, 128, pipe ) != NULL ) {
printf("%s\n", buf );
}
}
/* Close pipe */
rc = pclose(pipe);
``` |
219,138 | I need to run a Linux CLI command and get its stdout output from C.
I can use pipe() to create a pipe, then fork/exec, redirecting child's stdout descriptor into the pipe before calling exec(), and reading from the pipe in parent. Plus I'll need to wait on the child.
Is there a simple call to do fork + redirect + exec + wait, like system() does fork + exec + wait, only system() doesn't do the redirect.
There's popen(), which does fork + redirect + exec, but doesn't do wait, so I can't get exit status. | 2008/10/20 | [
"https://Stackoverflow.com/questions/219138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23420/"
] | Is this it?
```
NAME
popen, pclose - process I/O
SYNOPSIS
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
DESCRIPTION
The popen() function opens a process by creating a pipe, forking,
and invoking the shell. Since a pipe is by definition unidirectional, the
type argument may specify only reading or writing, not both; the resulting
stream is correspondingly read-only or write-only.
The command argument is a pointer to a null-terminated string
containing a shell command line. This command is passed to /bin/sh
using the -c flag; interpretation, if any, is performed by the shell.
The type argument is a pointer to a null-terminated string which must be
either ‘r’ for reading or ‘w’ for writing.
The return value from popen() is a normal standard I/O stream in
all respects save that it must be closed with pclose() rather than fclose().
Writing to such a stream writes to the standard input of the command; the
command’s standard output is the same as that of the process that called
popen(), unless this is altered by the command itself. Conversely, reading
from a ‘‘popened’’ stream reads the command’s standard output, and the
command’s standard input is the same as that of the process that called
popen().
Note that output popen() streams are fully buffered by default.
The pclose() function waits for the associated process to terminate
and returns the exit status of the command as returned by wait4().
``` | GLib has a nice function for this -- `g_spawn_sync()`:
<http://library.gnome.org/devel/glib/stable/glib-Spawning-Processes.html#g-spawn-sync>
For example, to run a command and get its exit status and output:
```
const char *argv[] = { "your_command", NULL };
char *output = NULL; // will contain command output
GError *error = NULL;
int exit_status = 0;
if (!g_spawn_sync(NULL, argv, NULL, 0, NULL, NULL,
&output, NULL, &exit_status, &error))
{
// handle error here
}
``` |
219,138 | I need to run a Linux CLI command and get its stdout output from C.
I can use pipe() to create a pipe, then fork/exec, redirecting child's stdout descriptor into the pipe before calling exec(), and reading from the pipe in parent. Plus I'll need to wait on the child.
Is there a simple call to do fork + redirect + exec + wait, like system() does fork + exec + wait, only system() doesn't do the redirect.
There's popen(), which does fork + redirect + exec, but doesn't do wait, so I can't get exit status. | 2008/10/20 | [
"https://Stackoverflow.com/questions/219138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23420/"
] | GLib has a nice function for this -- `g_spawn_sync()`:
<http://library.gnome.org/devel/glib/stable/glib-Spawning-Processes.html#g-spawn-sync>
For example, to run a command and get its exit status and output:
```
const char *argv[] = { "your_command", NULL };
char *output = NULL; // will contain command output
GError *error = NULL;
int exit_status = 0;
if (!g_spawn_sync(NULL, argv, NULL, 0, NULL, NULL,
&output, NULL, &exit_status, &error))
{
// handle error here
}
``` | Here is what I use:
```
/* simply invoke a app, pipe output*/
pipe = popen(buf, "r" );
if (pipe == NULL ) {
printf("invoking %s failed: %s\n", buf, strerror(errno));
return 1;
}
waitfor(10);
while(!feof(pipe) ) {
if( fgets( buf, 128, pipe ) != NULL ) {
printf("%s\n", buf );
}
}
/* Close pipe */
rc = pclose(pipe);
``` |
11,025,436 | For some reason I can't detect I can't set a z index for any triangle. The triangle will display, at the same depth, from 1 to -1 (inclusive), but after that it dissapers. I am not applying any MVP matrix (trying to figure out this first) and I would expect to be able to see my triangle get smaller as I decrease the z value. This is what I have so far:
```
//My main function
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA|GLUT_ALPHA|GLUT_DOUBLE|GLUT_DEPTH);
glutInitWindowSize(640, 480);
glutCreateWindow("Window");
if (init_resources()) {
glutDisplayFunc(onDisplay);
glutIdleFunc(idle);
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
glutMainLoop();
}
//And in my display function
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
```
And with my vertext shader:
```
gl_Position = vec4(coord2d, 0.0, 1.0);
```
`glGetIntegerv(GL_DEPTH_BITS, &depth)` also returns 24.
edit: full code
```
Sprite *sprite1;
Sprite *sprite2;
GLuint program;
GLuint cameraAttribute;
int init_resources()
{
//Link shaders, create program and attach shaders
GLint link_ok = GL_FALSE;
GLuint vs, fs;
if ((vs = create_shader("vertShader.sh", GL_VERTEX_SHADER)) == 0) return 0;
if ((fs = create_shader("fragShader.sh", GL_FRAGMENT_SHADER)) == 0) return 0;
program = glCreateProgram();
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &link_ok);
if (!link_ok) {
fprintf(stderr, "glLinkProgram:");
print_log(program);
return 0;
}
//Create Attributes
cameraAttribute = glGetUniformLocation(program, "camera");
if(cameraAttribute == -1){
cout << "Error!";
}
//Init sprites
sprite1 = new Sprite();
sprite2 = new Sprite();
return 1;
}
void onDisplay()
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
glUseProgram(program);
sprite1->render();
sprite2->render();
glutSwapBuffers();
}
void idle()
{
//Create Projection Matrix to change clip space.
mat4 projectionMatrix = perspective(60.0f, (float)glutGet(GLUT_WINDOW_WIDTH) / (float)glutGet(GLUT_WINDOW_HEIGHT), 0.1f, 100.f);
glUniformMatrix4fv(cameraAttribute, 1, GL_FALSE, &projectionMatrix[0][0]);
}
void free_resources()
{
glDeleteProgram(program);
}
int main(int argc, char* argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA|GLUT_ALPHA|GLUT_DOUBLE|GLUT_DEPTH);
glutInitWindowSize(640, 480);
glutCreateWindow("My Second Triangle");
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
if (init_resources()) {
glutDisplayFunc(onDisplay);
glutIdleFunc(idle);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//uses glGetError to check for how many errors there are.
cout << CheckGLErrors() << "\n";
glutMainLoop();
}
free_resources();
return 0;
}
```
And my sprite file:
```
#include "Sprite.h"
Sprite::Sprite(){
init();
}
void Sprite::init(){
GLfloat triangle_vertices[] = {
0.0, 0.8f,
-0.8f, -0.8f,
0.8f, -0.8f,
};
//Set attributes
locationAttribute = glGetAttribLocation(program, "coord2d");
if (locationAttribute == -1) {
fprintf(stderr, "Could not bind attribute location");
}
translationUniform = glGetUniformLocation(program, "translationUniform");
if(translationUniform == -1){
fprintf(stderr, "Could not bind attribute transformation");
}
//Create buffer
glGenBuffers(1, &mainBuffer);
glBindBuffer(GL_ARRAY_BUFFER, mainBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(triangle_vertices), triangle_vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(
locationAttribute, // attribute
2, // number of elements per vertex, here (x,y)
GL_FLOAT, // the type of each element
GL_FALSE, // take our values as-is
0, // no extra data between each position
0 // offset of first element
);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void Sprite::render(){
glBindBuffer(GL_ARRAY_BUFFER, mainBuffer);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
```
And Vertex shader: (note, versions are added by the parser)
```
attribute vec2 coord2d;
uniform mat4 translationUniform;
uniform mat4 camera;
void main(void) {
gl_Position = camera * vec4(coord2d, -1.1, 1.0);
}
``` | 2012/06/14 | [
"https://Stackoverflow.com/questions/11025436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/467427/"
] | Bamboo could possibly do this, giving you a dashboard to kick of the job of installing the third party software on the machines, however Bamboo is more of the orchestration of the implementing script or install executable.
Your problem really sounds like you would use [Puppet](http://puppetlabs.com/) for or some equivalent tool. This is specific software for describing how an environment should be set up and therefore is more of an implementation tool, with it's own language for describing users, files, and software packages etc. I've found it very useful for setting up my own environment (dev) to be exactly like the CI environment that runs the build.
You could always use Bamboo to run puppet however! | Are you talking about the automatic deployment on the dev environment? That can be done pretty easy with bamboo. |
11,025,436 | For some reason I can't detect I can't set a z index for any triangle. The triangle will display, at the same depth, from 1 to -1 (inclusive), but after that it dissapers. I am not applying any MVP matrix (trying to figure out this first) and I would expect to be able to see my triangle get smaller as I decrease the z value. This is what I have so far:
```
//My main function
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA|GLUT_ALPHA|GLUT_DOUBLE|GLUT_DEPTH);
glutInitWindowSize(640, 480);
glutCreateWindow("Window");
if (init_resources()) {
glutDisplayFunc(onDisplay);
glutIdleFunc(idle);
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
glutMainLoop();
}
//And in my display function
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
```
And with my vertext shader:
```
gl_Position = vec4(coord2d, 0.0, 1.0);
```
`glGetIntegerv(GL_DEPTH_BITS, &depth)` also returns 24.
edit: full code
```
Sprite *sprite1;
Sprite *sprite2;
GLuint program;
GLuint cameraAttribute;
int init_resources()
{
//Link shaders, create program and attach shaders
GLint link_ok = GL_FALSE;
GLuint vs, fs;
if ((vs = create_shader("vertShader.sh", GL_VERTEX_SHADER)) == 0) return 0;
if ((fs = create_shader("fragShader.sh", GL_FRAGMENT_SHADER)) == 0) return 0;
program = glCreateProgram();
glAttachShader(program, vs);
glAttachShader(program, fs);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &link_ok);
if (!link_ok) {
fprintf(stderr, "glLinkProgram:");
print_log(program);
return 0;
}
//Create Attributes
cameraAttribute = glGetUniformLocation(program, "camera");
if(cameraAttribute == -1){
cout << "Error!";
}
//Init sprites
sprite1 = new Sprite();
sprite2 = new Sprite();
return 1;
}
void onDisplay()
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
glUseProgram(program);
sprite1->render();
sprite2->render();
glutSwapBuffers();
}
void idle()
{
//Create Projection Matrix to change clip space.
mat4 projectionMatrix = perspective(60.0f, (float)glutGet(GLUT_WINDOW_WIDTH) / (float)glutGet(GLUT_WINDOW_HEIGHT), 0.1f, 100.f);
glUniformMatrix4fv(cameraAttribute, 1, GL_FALSE, &projectionMatrix[0][0]);
}
void free_resources()
{
glDeleteProgram(program);
}
int main(int argc, char* argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA|GLUT_ALPHA|GLUT_DOUBLE|GLUT_DEPTH);
glutInitWindowSize(640, 480);
glutCreateWindow("My Second Triangle");
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
if (init_resources()) {
glutDisplayFunc(onDisplay);
glutIdleFunc(idle);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//uses glGetError to check for how many errors there are.
cout << CheckGLErrors() << "\n";
glutMainLoop();
}
free_resources();
return 0;
}
```
And my sprite file:
```
#include "Sprite.h"
Sprite::Sprite(){
init();
}
void Sprite::init(){
GLfloat triangle_vertices[] = {
0.0, 0.8f,
-0.8f, -0.8f,
0.8f, -0.8f,
};
//Set attributes
locationAttribute = glGetAttribLocation(program, "coord2d");
if (locationAttribute == -1) {
fprintf(stderr, "Could not bind attribute location");
}
translationUniform = glGetUniformLocation(program, "translationUniform");
if(translationUniform == -1){
fprintf(stderr, "Could not bind attribute transformation");
}
//Create buffer
glGenBuffers(1, &mainBuffer);
glBindBuffer(GL_ARRAY_BUFFER, mainBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(triangle_vertices), triangle_vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(
locationAttribute, // attribute
2, // number of elements per vertex, here (x,y)
GL_FLOAT, // the type of each element
GL_FALSE, // take our values as-is
0, // no extra data between each position
0 // offset of first element
);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void Sprite::render(){
glBindBuffer(GL_ARRAY_BUFFER, mainBuffer);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
```
And Vertex shader: (note, versions are added by the parser)
```
attribute vec2 coord2d;
uniform mat4 translationUniform;
uniform mat4 camera;
void main(void) {
gl_Position = camera * vec4(coord2d, -1.1, 1.0);
}
``` | 2012/06/14 | [
"https://Stackoverflow.com/questions/11025436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/467427/"
] | Bamboo could possibly do this, giving you a dashboard to kick of the job of installing the third party software on the machines, however Bamboo is more of the orchestration of the implementing script or install executable.
Your problem really sounds like you would use [Puppet](http://puppetlabs.com/) for or some equivalent tool. This is specific software for describing how an environment should be set up and therefore is more of an implementation tool, with it's own language for describing users, files, and software packages etc. I've found it very useful for setting up my own environment (dev) to be exactly like the CI environment that runs the build.
You could always use Bamboo to run puppet however! | As other people have stated Bamboo can do this but have you looked at Attunity Replicate?
[Attunity Replicate](http://www.attunity.com/products/attunity-replicate) |
875,904 | Let $O$ be an open subset of $\mathbb R^2$ and suppose the function $f:O\to\mathbb R$ is continuous at the point $(x\_0,y\_0)$ in $O$.
Define tangent plane as $\phi(x,y)=a+b(x-x\_0)+c(y-y\_0)$ where $a,b,c$ are real numbers, which has the property that
$$\lim\_{(x,y)\to(x\_0,y\_0)}\frac{f(x,y)-\phi(x,y)}{\sqrt{(x-x\_0)^2+(y-y\_0)^2}}=0$$
clearly that $\phi $ is a first order approximation of $f$.
I know that if $f$ is continuously differentiable, then the tangent plane at the point $(x\_0,y\_0)$ is defined by $$\phi(x,y)=f(x\_0,y\_0)+\frac{\partial f}{\partial x}(x\_0,y\_0)(x-x\_0)+\frac{\partial f}{\partial y}(x\_0,y\_0)(y-y\_0)$$
However I don't know how to prove the converse theorem:
If $\phi$ is a tangent plane of a function $f:O\to\mathbb R$ at the point $(x\_0,y\_0,f(x\_0,y\_0))$ (which at the point is continuous?), then $f$ has first order partial derivatives at $(x\_0,y\_0)$ and $a=f(x\_0,y\_0)$, $b=\frac{\partial f}{\partial x}(x\_0,y\_0)$, $c=\frac{\partial f}{\partial y}(x\_0,y\_0)$ such that the tangent plane is unique. Also $f$ has directional derivatives in all direction at the point $(x\_0,y\_0)$
The bracket (which at the point is continuous?) means that I don't know whether it is a necessary condition for the theorem to hold, since I do not know whether tangent plane exist implies continuous at the point. | 2014/07/23 | [
"https://math.stackexchange.com/questions/875904",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/71563/"
] | Hint:
The better way to solve this problems to use [cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
The sphere of center $(0,0,0)$ and radius $2$ has equation: $r^2+z^2=4$ and, without loss of generality, we can assume that cylinder has the axis parallel to the $z$ axis , and center at $(0,1,0)$ and radius $1$ so it has equation: $r=2\sin \theta$.
this means that the limits of the volume limited by the sphere and the cylinder are:
$$
0\le \theta \le 2\pi \qquad 0\le r \le 2 \sin \theta \qquad-\sqrt{4-r^2}\le z \le \sqrt{4-r^2}
$$
so, using the symmetries of the figure, the volume is:
$$
V=4 \int\_0^{\frac{\pi}{2}}\int\_0^{2\sin \theta}\int\_0^{\sqrt{4-r^2}}rdzdrd\theta
$$
where $rdzdrd\theta$ is the volume element in cylindrical coordinates.
can you do from this? | The equation for the ball is
$$
x^2 + y^2 + z^2 = 2^2
$$
and we have a cylinder inside this ball with radius 1, this would give the limits:
$$
0 \le r \le 1\\
0 \le \theta \le 2\pi
$$
since the radius is 1 and a cylinder has a circular bottom which is a "full lap" around the unit circle hence the $2\pi$
The height of the cylinder is
$$
4^2 - 2^2 = h^2 \Rightarrow h = \sqrt{12}
$$
you can draw a rectangle inside a circle and get a triangle with cathetus 2 (radius = 1) and h (the unknown). The diagonal is the diameter of the circle which is 4. Since the cylinder is stationed in the origin, z has the limits $$-\frac{\sqrt{12}}{2} \le z \le\frac{\sqrt{12}}{2}$$
Which would give you the integral
$$
\int\_{\theta=0}^{2\pi} \int\_{z=-\frac{\sqrt{12}}{2}}^{\frac{\sqrt{12}}{2}}\int\_{r=0}^{1}(r^2 + z^2)r \cdot drdzd\theta
$$
I might have made some mistake somewhere, but hope this helps you anyway! |
8,207,398 | I have installed rvm after installing Mac OS Lion. The problem which I am facing is whenever I try to run a new Rails application, it gives me following error.
The problem gets resolved once choose a particular rvm. `$ rvm gemset use global`
I know about using .rvmrc file per project. But I don't want to keep on using this command every time I create a demo project. Why doesn't rvm uses the "global" gemset automatically every time I create new project?
I used [this documentation](http://pragmaticstudio.com/blog/2010/9/23/install-rails-ruby-mac) to install rvm.
```
JP:demo3 jayparteek$ rails s
/Users/jayparteek/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.1/lib/rails/commands/server.rb:3:in `require': no such file to load -- action_dispatch (LoadError)
from /Users/jayparteek/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.1/lib/rails/commands/server.rb:3:in `<top (required)>'
from /Users/jayparteek/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.1/lib/rails/commands.rb:48:in `require'
from /Users/jayparteek/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.1/lib/rails/commands.rb:48:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
``` | 2011/11/21 | [
"https://Stackoverflow.com/questions/8207398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/917158/"
] | You can specify a "default" gemset for a given ruby interpreter, by doing:
```
rvm use ruby-1.9.2-p0@gemsetname --default
```
See: <http://beginrescueend.com/gemsets/using/> and <http://beginrescueend.com/gemsets/basics/>
it's probably a better idea to use a specific gemset for each of your projects, together with it's specific Gemfile. Problems could happen if you require '>= x.y.z' in your Gemfiles, and you do a `bundle update` in one project, but not in the other...
```
cd ProjectA
rvm gemset create projecta
rvm gemset use projecta
cd ProjectB
rvm gemset create projectb
rvm gemset use projectb
```
This way, although you update the gems in ProjectA via `bundle update` to the latest and greatest, they still don't get modified for ProjectB -- eliminating the possibility for interference between projects.
---
you can also add a .rvmrc file to a directory, e.g. your project directory. RVM will then use the ruby-version and gem set listed in the .rvmrc file as the default for all sub-directories.
e.g. assuming that you have ruby 1.9.3 installed, and a gem set "rails\_3.2" for that ruby version:
```
# cat .rvmrc
rvm use ruby-1.9.3-p0@rails_3.2
``` | You can make default gemset by using following command
```
rvm --default gemset use <gemsetname>
```
or
```
rvm gemset use <gemsetname> --default
```
For example, if you have rails4 gemset then you can make it default by
```
rvm --default gemset use rails4
```
or
```
rvm gemset use rails4 --default
``` |
18,832,148 | I am trying to create a SQL Job that sits on what I like to call a Maintenance Server where details about all the other server databases sit. So I have a stored procedure to gather all the required data I have and this stored procedure is now in MaintenanceServer.MaintenanceDB.pr\_MyProcedure.
Now what i'd like to do this is. I am creating Linked Servers on my MaintenanceServer which points to all the other Servers I'd like to maintain. Next on my list is to be able to run this procedure pr\_MyProcedure against all those LinkedServers. I have over 25 servers to maintain and what i want to do is to run the procedure against them and insert the result to my local MaintenanceDB.
Can someone point me to a good way to do this? Also i'd like to hear the drawbacks of this method.
Thanks and Cheers!
**EDIT:**
I was also thinking about storing the SP on all the master databases of my other Servers and running them remotely on my Maintenance Server. Then i'll use `OPENQUERY()` to gather all the results that I need. However, I don't think I want to touch all the master databases on my server list. Please tell me if this would be better than the once I stated above. | 2013/09/16 | [
"https://Stackoverflow.com/questions/18832148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387906/"
] | The nice way to do it is run the SP on the target server, as that's nicely modular. If you want to query the remote server, it's going to be more painful. I'm not sure whether the undocumented sp\_foreachdb deals with linked databases, if not you are down to dynamic sql.
As in build a string and call it with Exec(@somesql), that will need to deal with the results itself, as any variables will only be in scope inside the exec.
Personally I'd consider inverting all this. Have each server call it's own SP and the call an SP on the maintenance box to store the results. | EXEC [RemoteServer] .DatabaseName.DatabaseOwner.StoredProcedureName
‘Params’
Example:
EXEC [RemoteServer] .DatabaseName.DatabaseOwner.StoredProcedureName ’PramValue’ |
17,743,638 | 
Hi im trying to line up my button horizontally like an "inline" but it wont let me. I know about btn-group but then I cant have space in between the buttons like I want because they're attached to one another. so im trying to align them horizontally without btn-group
**Here is my code:**
```
<footer class="bottom visible-phone">
<div class="container">
<div class="row text-center">
<div class="span1"><a class="btn btn-primary btn-small" href="#">
<div class="icon-user icon-white"></div> Facebook</a></div>
<div class="span1"><a class="btn btn-info btn-small" href="#">
<div class="icon-user icon-white"></div> Twitter</a></div>
<div class="span1"><a class="btn btn-danger btn-small" href="#">
<div class="icon-user icon-white"></div> Youtube</a></div>
<div class="span1"><a class="btn btn-small" href="#">
<div class="icon-user"></div> Instagram</a></div>
</div><!--row END-->
</div><!--container END-->
</footer>
``` | 2013/07/19 | [
"https://Stackoverflow.com/questions/17743638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2279089/"
] | In Bootsrap, the grid system (span, row, container) will make all span's appear underneath eachother as soon as you get to the 'phone' size (which I guess is the case here, due to the visible-phone class you added to the footer). You won't be able to rely just on the grid system for this...
There is however a .inline class available to use on `ul`: <http://twitter.github.io/bootstrap/base-css.html#lists>
This means that with some reformatting of your markup (which would make sense anyway), you should be able to achieve the desired result, without writing a single line of css yourself:
```
<footer class="bottom visible-phone">
<div class="container">
<div class="row text-center">
<ul class='inline span12'>
<li><a class="btn btn-primary btn-small" href="#">
<i class="icon-user icon-white"></i> Facebook</a>
</li>
...
</ul>
</div>
<!--row END-->
</div>
<!--container END-->
</footer>
```
In fact all the extra wrappers (footer, container, row) are not required here, I just kept them as they where present in your code. Only the code from `<ul>` (without the .span12) to `</ul>` should do.
For an example, have a look at this: <http://jsfiddle.net/jRm3Z/1/> | I would recommend makeing the Row div a UL and the other elements in the list LI tags.
Then you should be able to modify your css code:
```
display: list-item;
```
or
```
display: block;
```
UPDATE #:
```
<div class="icon-user icon-white"></div>
```
Replace with
```
<i class="icon-user icon-white"></div>
``` |
2,308,435 | When I run the code the click event works the first time. When I click it more then one time it seems that the click even has unbounded. How do I keep the click event bounded?
```
var Categories = function() {
$("select[id^='CategoryListBox-']").click(
function() {
SelectedItem = $(this).val();
$(this).parent().load('/Categories/CategoryPicker?CatID=' + SelectedItem);
//send CatID to the requesting page
$('form#SubmitPost').prepend('<input id="CatID" name="CatID" type="hidden" value="' + SelectedItem + '" />');
});
}
Categories();
``` | 2010/02/22 | [
"https://Stackoverflow.com/questions/2308435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184773/"
] | You are overwriting the click handler by replacing the dom inside of it's parent element. You can use `live` instead to always keep the binding.
Line 2 would be:
`$("select[id^='CategoryListBox-']").live('click',`
And that should do it | Are you possibly creating/re-creating the object and then failing to re-bind the event? I have one site where we do a fair amount of AJAX updating (using the jQuery taconite plugin), and the last thing we do is explicitly bind the click events on the newly created DOM objects. |
2,308,435 | When I run the code the click event works the first time. When I click it more then one time it seems that the click even has unbounded. How do I keep the click event bounded?
```
var Categories = function() {
$("select[id^='CategoryListBox-']").click(
function() {
SelectedItem = $(this).val();
$(this).parent().load('/Categories/CategoryPicker?CatID=' + SelectedItem);
//send CatID to the requesting page
$('form#SubmitPost').prepend('<input id="CatID" name="CatID" type="hidden" value="' + SelectedItem + '" />');
});
}
Categories();
``` | 2010/02/22 | [
"https://Stackoverflow.com/questions/2308435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184773/"
] | You are overwriting the click handler by replacing the dom inside of it's parent element. You can use `live` instead to always keep the binding.
Line 2 would be:
`$("select[id^='CategoryListBox-']").live('click',`
And that should do it | I think that when you load() into parent(), you're replacing the original CategoryListBox-\* element with a new one. The new one has nothing bound to it. You can either re-bind the function to the new element, which would be ugly and possibly get you into a nasty recursion situation, or you can use the .live() function to bind Categories() to any DOM element with the id of CategoryListBox-\*. That would look something like:
```
$("select[id^='CategoryListBox-']").live('click', function() { [body of your Categories() function] } );
```
<http://api.jquery.com/live/>
This will work in jQuery 1.3+. If you're using 1.2, you should upgrade or use the livequery plugin to get similar functionality. |
2,308,435 | When I run the code the click event works the first time. When I click it more then one time it seems that the click even has unbounded. How do I keep the click event bounded?
```
var Categories = function() {
$("select[id^='CategoryListBox-']").click(
function() {
SelectedItem = $(this).val();
$(this).parent().load('/Categories/CategoryPicker?CatID=' + SelectedItem);
//send CatID to the requesting page
$('form#SubmitPost').prepend('<input id="CatID" name="CatID" type="hidden" value="' + SelectedItem + '" />');
});
}
Categories();
``` | 2010/02/22 | [
"https://Stackoverflow.com/questions/2308435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184773/"
] | It looks like you are using AJAX to load new HTML from the server and you're overwriting the existing select box with a new one. This will remove event listeners. One solution is to use `live()`:
```
$("select[id^='CategoryListBox-']").live("click", function() {
SelectedItem = $(this).val();
$(this).parent().load('/Categories/CategoryPicker?CatID=' + SelectedItem);
//send CatID to the requesting page
$('form#SubmitPost').prepend('<input id="CatID" name="CatID" type="hidden" value="' + SelectedItem + '" />');
});
```
One suggestion: don't use an attribute selector like this. Give all the relevant select boxes a class like "category" and then do:
```
$("select.category").live("click", function() { ... }
```
It's much faster.
Lastly, this is a better way of creating your hidden inputs:
```
$("<input>").attr({id: "CatID", name: "CatID", type: "hidden", value: SelectedItem}).prependTo("#SubmitPost");
```
The reason being that this creates the DOM element directly rather than interpreting HTML, which again is much slower. | Are you possibly creating/re-creating the object and then failing to re-bind the event? I have one site where we do a fair amount of AJAX updating (using the jQuery taconite plugin), and the last thing we do is explicitly bind the click events on the newly created DOM objects. |
2,308,435 | When I run the code the click event works the first time. When I click it more then one time it seems that the click even has unbounded. How do I keep the click event bounded?
```
var Categories = function() {
$("select[id^='CategoryListBox-']").click(
function() {
SelectedItem = $(this).val();
$(this).parent().load('/Categories/CategoryPicker?CatID=' + SelectedItem);
//send CatID to the requesting page
$('form#SubmitPost').prepend('<input id="CatID" name="CatID" type="hidden" value="' + SelectedItem + '" />');
});
}
Categories();
``` | 2010/02/22 | [
"https://Stackoverflow.com/questions/2308435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184773/"
] | It looks like you are using AJAX to load new HTML from the server and you're overwriting the existing select box with a new one. This will remove event listeners. One solution is to use `live()`:
```
$("select[id^='CategoryListBox-']").live("click", function() {
SelectedItem = $(this).val();
$(this).parent().load('/Categories/CategoryPicker?CatID=' + SelectedItem);
//send CatID to the requesting page
$('form#SubmitPost').prepend('<input id="CatID" name="CatID" type="hidden" value="' + SelectedItem + '" />');
});
```
One suggestion: don't use an attribute selector like this. Give all the relevant select boxes a class like "category" and then do:
```
$("select.category").live("click", function() { ... }
```
It's much faster.
Lastly, this is a better way of creating your hidden inputs:
```
$("<input>").attr({id: "CatID", name: "CatID", type: "hidden", value: SelectedItem}).prependTo("#SubmitPost");
```
The reason being that this creates the DOM element directly rather than interpreting HTML, which again is much slower. | I think that when you load() into parent(), you're replacing the original CategoryListBox-\* element with a new one. The new one has nothing bound to it. You can either re-bind the function to the new element, which would be ugly and possibly get you into a nasty recursion situation, or you can use the .live() function to bind Categories() to any DOM element with the id of CategoryListBox-\*. That would look something like:
```
$("select[id^='CategoryListBox-']").live('click', function() { [body of your Categories() function] } );
```
<http://api.jquery.com/live/>
This will work in jQuery 1.3+. If you're using 1.2, you should upgrade or use the livequery plugin to get similar functionality. |
26,269,985 | I'm trying to convert factor values in R into numeric. I tried various methods but no matter what I do, I get the error "NAs introduced by coercion". Here is a sample code I run and the error I get:
```
> demand <- read.csv("file.csv" )
> demand[3,3]
[1] 5,185
25 Levels: 2/Jan/2011 3,370 4,339 4,465 4,549 4,676 4,767 4,844 5,055 5,139 5,185 5,265 5,350 5,434 ... dam
> a <- demand[3,3]
> as.numeric(as.character(a))
[1] NA
Warning message:
NAs introduced by coercion
```
How can I get numeric values? | 2014/10/09 | [
"https://Stackoverflow.com/questions/26269985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2683407/"
] | You should replace
```
as.numeric(as.character(a))
```
in your code with
```
as.numeric( gsub("[,]", "", as.character(a) ) )
``` | I got 2 comments here:
1. You are using probably files from East Europe Excel float notation (',' instead of '.').
To make it working well, use `read.csv2()` function.
2. The firs observation is probably the header? I guess the observations below are somehow connected via this date (2/Jan/2011). I will suggest to use `header=T` argument.
Summarizing:
Try `read.csv2("file.csv", head=T)`
If for any reasons you still need to change factors to numeric values, I suggest :
`f = as.factor(1:10)`
`as.numeric(f[f])`
Best,
Adii\_ |
276,256 | >
> Find the smallest positive integer $k$, such that product of $420$ and $k$ is a perfect square.
>
>
>
Please help me in this question. | 2013/01/12 | [
"https://math.stackexchange.com/questions/276256",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/57004/"
] | What you *really* need is not an answer to the specific question but an understanding of the general principle you need to be deploying here. So let's think about the general problem: Given $n$ find the smallest $k$ such that $m = n \cdot k$ is a perfect square. What to do?
Good hint for questions such as this: *think about factorization* (as the question, *is $m$ a perfect square* is a question about how it factorizes). So ...
What are the properties of the factors of perfect squares $m$? Well since $m = j^2$ any factor of $j$ must occur twice in $m$. So any prime factor of $m$ must occur an even number of times.
And that gives us our clue to how to proceed:
>
> Step one. Factorize $n$.
>
>
> Step two. Look to see which primes *don't* appear an even number of times in the factorization.
>
>
> Step three. Take $k$ to be the product of those primes with an odd number of occurrences in $n$.
>
>
>
So -- by brute force construction -- $n \cdot k$ is the product of primes, each one of which now occurs an even number of times as we want. So $m = n \cdot k$ is a perfect square. And we've put into $k$ the fewest prime factors needed to make the product with $n$ a perfect square. So we are done.
Now you have the principle of the thing, you should be able to see how to do *this* problem too: *Find the smallest number $k$ such that $420 \cdot k$ is a perfect cube* and other problems in the same family. | $420=2^2\cdot3\cdot5\cdot7$
Observe that the power of $3,5$ and $7$ in $420$ is $1$
So, to make the power of $3$ even, we need to multiply $420$ by $3^{2a+1}$ where $a$ is a non-negative integer.
So, the general value of $k$ is $3^{2a+1}\cdot5^{2b+1}\cdot7^{2c+1}$ where $a,b,c$ are non-negative integers.
So, the smallest positive integer value of $k$ is $3\cdot5\cdot7=105$ (putting $a=b=c=0$)
Observe that $\frac{420}{105}=4=2^2$ is also a perfect square.
If $A\cdot B$ is perfect square, so will be $\frac AB$ if $B\mid A$ |
15,257,513 | Hi I am just starting to learn how to program and have a function that I need to write in Python, this is the idea behind it:
It returns `True` if `word` is in the `wordList` and is entirely composed of letters in the hand. Otherwise, returns `False`. Does not mutate hand or wordList.
There is a function to call that checks the frequency of the letters in the word the user comes up with and that is a converted to a dict, I have tried using iteritems various ways but to no avail, I am getting stuck on the words that have repeated letters, they are being returned as true when I don't have two entries for that letter in the users hand.
Sorry if this is unclear I only started two weeks ago.
any pointers would be great I have been stuck on this for a long time!
```
def isValidWord(hand,word,wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
wordC = getFrequencyDict(word)
handC = dict.copy(hand)
if word not in wordList:
return False
for c in word:
if c not in hand:
return False
for k,v in wordC.iteritems():
if k in hand and v > 1:
handC[k] -= 1
```
basically my next step was trying to figure out how to compare word to handC with amended value and discounting any key with a value of zero.
I think(hope) that will work. | 2013/03/06 | [
"https://Stackoverflow.com/questions/15257513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141635/"
] | Without your code, let me see if I understand what you want: you're trying to see if the given word can be spelled using the letters in `hand` as if the user had a Scrabble tile for each letter in `hand`, yes?
Personally I'd just copy the `hand` dictionary and then allow changes to the copy. Something like this:
```
def is_valid_word(hand, word, wordlist):
hand_cp = dict(hand)
for letter in word:
if hand_cp.get(letter):
# The letter is in our hand, so "use it up".
hand_cp[letter] = hand_cp[letter] - 1
else:
# The letter isn't in our hand, so the word isn't valid.
return False
# If we can make the word, now make sure it's a real word:
# (If wordlist is long, you might want to sort it and do a real search)
if word not in wordlist:
return False
# We haven't found any reason to return False, so this is a valid word.
return True
``` | How about something like this:
```
def isValidWord(hand, word, word_list):
if word not in word_list:
return False
for c in word:
if c not in hand:
return False
return True
```
As strings are iterable you can check character by character.
Good luck |
15,257,513 | Hi I am just starting to learn how to program and have a function that I need to write in Python, this is the idea behind it:
It returns `True` if `word` is in the `wordList` and is entirely composed of letters in the hand. Otherwise, returns `False`. Does not mutate hand or wordList.
There is a function to call that checks the frequency of the letters in the word the user comes up with and that is a converted to a dict, I have tried using iteritems various ways but to no avail, I am getting stuck on the words that have repeated letters, they are being returned as true when I don't have two entries for that letter in the users hand.
Sorry if this is unclear I only started two weeks ago.
any pointers would be great I have been stuck on this for a long time!
```
def isValidWord(hand,word,wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
wordC = getFrequencyDict(word)
handC = dict.copy(hand)
if word not in wordList:
return False
for c in word:
if c not in hand:
return False
for k,v in wordC.iteritems():
if k in hand and v > 1:
handC[k] -= 1
```
basically my next step was trying to figure out how to compare word to handC with amended value and discounting any key with a value of zero.
I think(hope) that will work. | 2013/03/06 | [
"https://Stackoverflow.com/questions/15257513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141635/"
] | How about something like this:
```
def isValidWord(hand, word, word_list):
if word not in word_list:
return False
for c in word:
if c not in hand:
return False
return True
```
As strings are iterable you can check character by character.
Good luck | The python `Counter` class is your friend. You can do this in [python 2.7 and later](http://docs.python.org/2/library/collections.html#collections.Counter):
```
from collections import Counter
def is_valid_word(hand, word, word_list):
letter_leftover = Counter(hand)
letter_leftover.subtract(Counter(word))
return word in word_list and all(v >= 0 for v in letter_leftover.values())
```
Then:
```
>>> def test():
... hand = "traipse"
... word_list = ["all", "the", "words", "in", "English",
"parts", "pines", "partiers"]
... print is_valid_word(hand, "parts", word_list)
... print is_valid_word(hand, "pines", word_list)
... print is_valid_word(hand, "partiers", word_list)
...
>>> test()
True
False
False
``` |
15,257,513 | Hi I am just starting to learn how to program and have a function that I need to write in Python, this is the idea behind it:
It returns `True` if `word` is in the `wordList` and is entirely composed of letters in the hand. Otherwise, returns `False`. Does not mutate hand or wordList.
There is a function to call that checks the frequency of the letters in the word the user comes up with and that is a converted to a dict, I have tried using iteritems various ways but to no avail, I am getting stuck on the words that have repeated letters, they are being returned as true when I don't have two entries for that letter in the users hand.
Sorry if this is unclear I only started two weeks ago.
any pointers would be great I have been stuck on this for a long time!
```
def isValidWord(hand,word,wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
wordC = getFrequencyDict(word)
handC = dict.copy(hand)
if word not in wordList:
return False
for c in word:
if c not in hand:
return False
for k,v in wordC.iteritems():
if k in hand and v > 1:
handC[k] -= 1
```
basically my next step was trying to figure out how to compare word to handC with amended value and discounting any key with a value of zero.
I think(hope) that will work. | 2013/03/06 | [
"https://Stackoverflow.com/questions/15257513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141635/"
] | How about something like this:
```
def isValidWord(hand, word, word_list):
if word not in word_list:
return False
for c in word:
if c not in hand:
return False
return True
```
As strings are iterable you can check character by character.
Good luck | here is mine
```
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
if word in wordList:
if set(word).issubset(set(hand)):
return True
else:
return False
else:
return False
``` |
15,257,513 | Hi I am just starting to learn how to program and have a function that I need to write in Python, this is the idea behind it:
It returns `True` if `word` is in the `wordList` and is entirely composed of letters in the hand. Otherwise, returns `False`. Does not mutate hand or wordList.
There is a function to call that checks the frequency of the letters in the word the user comes up with and that is a converted to a dict, I have tried using iteritems various ways but to no avail, I am getting stuck on the words that have repeated letters, they are being returned as true when I don't have two entries for that letter in the users hand.
Sorry if this is unclear I only started two weeks ago.
any pointers would be great I have been stuck on this for a long time!
```
def isValidWord(hand,word,wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
wordC = getFrequencyDict(word)
handC = dict.copy(hand)
if word not in wordList:
return False
for c in word:
if c not in hand:
return False
for k,v in wordC.iteritems():
if k in hand and v > 1:
handC[k] -= 1
```
basically my next step was trying to figure out how to compare word to handC with amended value and discounting any key with a value of zero.
I think(hope) that will work. | 2013/03/06 | [
"https://Stackoverflow.com/questions/15257513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141635/"
] | Without your code, let me see if I understand what you want: you're trying to see if the given word can be spelled using the letters in `hand` as if the user had a Scrabble tile for each letter in `hand`, yes?
Personally I'd just copy the `hand` dictionary and then allow changes to the copy. Something like this:
```
def is_valid_word(hand, word, wordlist):
hand_cp = dict(hand)
for letter in word:
if hand_cp.get(letter):
# The letter is in our hand, so "use it up".
hand_cp[letter] = hand_cp[letter] - 1
else:
# The letter isn't in our hand, so the word isn't valid.
return False
# If we can make the word, now make sure it's a real word:
# (If wordlist is long, you might want to sort it and do a real search)
if word not in wordlist:
return False
# We haven't found any reason to return False, so this is a valid word.
return True
``` | The python `Counter` class is your friend. You can do this in [python 2.7 and later](http://docs.python.org/2/library/collections.html#collections.Counter):
```
from collections import Counter
def is_valid_word(hand, word, word_list):
letter_leftover = Counter(hand)
letter_leftover.subtract(Counter(word))
return word in word_list and all(v >= 0 for v in letter_leftover.values())
```
Then:
```
>>> def test():
... hand = "traipse"
... word_list = ["all", "the", "words", "in", "English",
"parts", "pines", "partiers"]
... print is_valid_word(hand, "parts", word_list)
... print is_valid_word(hand, "pines", word_list)
... print is_valid_word(hand, "partiers", word_list)
...
>>> test()
True
False
False
``` |
15,257,513 | Hi I am just starting to learn how to program and have a function that I need to write in Python, this is the idea behind it:
It returns `True` if `word` is in the `wordList` and is entirely composed of letters in the hand. Otherwise, returns `False`. Does not mutate hand or wordList.
There is a function to call that checks the frequency of the letters in the word the user comes up with and that is a converted to a dict, I have tried using iteritems various ways but to no avail, I am getting stuck on the words that have repeated letters, they are being returned as true when I don't have two entries for that letter in the users hand.
Sorry if this is unclear I only started two weeks ago.
any pointers would be great I have been stuck on this for a long time!
```
def isValidWord(hand,word,wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
wordC = getFrequencyDict(word)
handC = dict.copy(hand)
if word not in wordList:
return False
for c in word:
if c not in hand:
return False
for k,v in wordC.iteritems():
if k in hand and v > 1:
handC[k] -= 1
```
basically my next step was trying to figure out how to compare word to handC with amended value and discounting any key with a value of zero.
I think(hope) that will work. | 2013/03/06 | [
"https://Stackoverflow.com/questions/15257513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141635/"
] | Without your code, let me see if I understand what you want: you're trying to see if the given word can be spelled using the letters in `hand` as if the user had a Scrabble tile for each letter in `hand`, yes?
Personally I'd just copy the `hand` dictionary and then allow changes to the copy. Something like this:
```
def is_valid_word(hand, word, wordlist):
hand_cp = dict(hand)
for letter in word:
if hand_cp.get(letter):
# The letter is in our hand, so "use it up".
hand_cp[letter] = hand_cp[letter] - 1
else:
# The letter isn't in our hand, so the word isn't valid.
return False
# If we can make the word, now make sure it's a real word:
# (If wordlist is long, you might want to sort it and do a real search)
if word not in wordlist:
return False
# We haven't found any reason to return False, so this is a valid word.
return True
``` | here is mine
```
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
if word in wordList:
if set(word).issubset(set(hand)):
return True
else:
return False
else:
return False
``` |
25,359,380 | ```
#include <stdio.h>
#include <math.h>
#include <string.h>
long fctl(int n){
int a=1,i;
for(i=n;i>1;--i)
a*=i;
return a;
}
long ch(int n, int r){
return fctl(n) / (fctl(n-r)*fctl(r));
}
int main(){
char *hands[] = {"onepair", "twopair", "triple", "straight", "flush", "fullhouse", "fourofakind", "straightflush", "royalflush"};
double handprobs[9];
handprobs[0] = ch(13,1)*ch(4,2) * ch(12,3)*pow(ch(4,1), 3) / ch(52,5);
handprobs[1] = ch(13,2)*pow(ch(4,2), 2) * ch(11,1)*ch(4,1) / ch(52,5);
handprobs[2] = ch(13,1)*ch(4,3) * ch(12,2)*pow(ch(4,1), 2) / ch(52,5);
handprobs[3] = 10.0 * pow(ch(4, 1),5) / ch(52, 5) - 10.0/ch(52,5) - 4.0/ch(52,5);
handprobs[4] = ch(13,5)*ch(4,1) / ch(52, 5) - 10.0/ch(52,5);
handprobs[5] = ch(13,1)*ch(4,3) * ch(12,1)*ch(4,2) / ch(52,5);
handprobs[6] = ch(13,1)*1 * ch(12,1)*ch(4,1) / ch(52,5);
handprobs[7] = 40.0 / ch(52, 5) - 4.0/ch(52,5),
handprobs[8] = 4.0 / ch(52, 5);
int i;
for(i=0;hands[i];++i){
printf("%s\t%f\n",hands[i], handprobs[i]);
}
}
```
When I compile it returns "Floating point exception (core dumped)", not sure why. (Have tried converting all the probs with (double).) Any ideas? | 2014/08/18 | [
"https://Stackoverflow.com/questions/25359380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2380150/"
] | You need another API key to use while testing. its different from the API key you generated from keystore file.
From eclipse-->windows-->Preferences-->Android-->Build. Use this SHA1 fingerprint and get another API key from Google API console and use it for testing.
Don't forget to change it to the production one before uploading the APK to google play.
**Update:**
I use this way and it works fine. Its different from the one you use:
fragment\_map.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
```
this is my MapFragment Class. I locate a point on the map and give it a title:
```
public class MapFragment extends Fragment {
final static String TAG = "map";
final static String LONG = "long";
final static String LAT = "lat";
final static String TITLE = "title";
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
Bundle args;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.fragment_map, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
args = getArguments();
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(args.getDouble(LAT), args.getDouble(LONG))).title(args.getString(TITLE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(args.getDouble(LAT), args.getDouble(LONG)), 15));
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
@Override
public void onStart() {
super.onStart();
}
}
```
And this is how I add it to the screen:
```
MapFragment mapFragment = new MapFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Bundle args = new Bundle();
args.putString(MapFragment.TITLE, title);
args.putDouble(MapFragment.LONG, longitude);
args.putDouble(MapFragment.LAT, latitude);
mapFragment.setArguments(args);
transaction.replace(R.id.content_frame, mapFragment,"map");
transaction.addToBackStack(null);
transaction.commit();
```
I hope it helps. | Try the below code . this worked for me...
```
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:name="com.google.android.gms.maps.MapFragment"
android:id="@+id/thapar_map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
setContentView(R.layout.maps);
GoogleMap map;
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.thapar_map)).getMap();
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setPadding(5, 5, 5, 5);
map.setMyLocationEnabled(true);
``` |
25,359,380 | ```
#include <stdio.h>
#include <math.h>
#include <string.h>
long fctl(int n){
int a=1,i;
for(i=n;i>1;--i)
a*=i;
return a;
}
long ch(int n, int r){
return fctl(n) / (fctl(n-r)*fctl(r));
}
int main(){
char *hands[] = {"onepair", "twopair", "triple", "straight", "flush", "fullhouse", "fourofakind", "straightflush", "royalflush"};
double handprobs[9];
handprobs[0] = ch(13,1)*ch(4,2) * ch(12,3)*pow(ch(4,1), 3) / ch(52,5);
handprobs[1] = ch(13,2)*pow(ch(4,2), 2) * ch(11,1)*ch(4,1) / ch(52,5);
handprobs[2] = ch(13,1)*ch(4,3) * ch(12,2)*pow(ch(4,1), 2) / ch(52,5);
handprobs[3] = 10.0 * pow(ch(4, 1),5) / ch(52, 5) - 10.0/ch(52,5) - 4.0/ch(52,5);
handprobs[4] = ch(13,5)*ch(4,1) / ch(52, 5) - 10.0/ch(52,5);
handprobs[5] = ch(13,1)*ch(4,3) * ch(12,1)*ch(4,2) / ch(52,5);
handprobs[6] = ch(13,1)*1 * ch(12,1)*ch(4,1) / ch(52,5);
handprobs[7] = 40.0 / ch(52, 5) - 4.0/ch(52,5),
handprobs[8] = 4.0 / ch(52, 5);
int i;
for(i=0;hands[i];++i){
printf("%s\t%f\n",hands[i], handprobs[i]);
}
}
```
When I compile it returns "Floating point exception (core dumped)", not sure why. (Have tried converting all the probs with (double).) Any ideas? | 2014/08/18 | [
"https://Stackoverflow.com/questions/25359380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2380150/"
] | You need another API key to use while testing. its different from the API key you generated from keystore file.
From eclipse-->windows-->Preferences-->Android-->Build. Use this SHA1 fingerprint and get another API key from Google API console and use it for testing.
Don't forget to change it to the production one before uploading the APK to google play.
**Update:**
I use this way and it works fine. Its different from the one you use:
fragment\_map.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
```
this is my MapFragment Class. I locate a point on the map and give it a title:
```
public class MapFragment extends Fragment {
final static String TAG = "map";
final static String LONG = "long";
final static String LAT = "lat";
final static String TITLE = "title";
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
Bundle args;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.fragment_map, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
args = getArguments();
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(args.getDouble(LAT), args.getDouble(LONG))).title(args.getString(TITLE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(args.getDouble(LAT), args.getDouble(LONG)), 15));
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
@Override
public void onStart() {
super.onStart();
}
}
```
And this is how I add it to the screen:
```
MapFragment mapFragment = new MapFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Bundle args = new Bundle();
args.putString(MapFragment.TITLE, title);
args.putDouble(MapFragment.LONG, longitude);
args.putDouble(MapFragment.LAT, latitude);
mapFragment.setArguments(args);
transaction.replace(R.id.content_frame, mapFragment,"map");
transaction.addToBackStack(null);
transaction.commit();
```
I hope it helps. | as per my understanding this issue is happening because of three reason
**Reasons**
1) first is lack of internet connectivity
2) second is your google api key is missmatching
3) third if key is ok then your provided package name during key generation is not exact same as your project package name
**Solutions**
for first you need to check your internet conncetion is working or not then you need to go further
for second and third you need to create key with proper steps
If your using eclipse then
Eclipse-->windows-->Preferences-->Android-->Build you will get SHA key
Use that SHA key to generate your android key
after pasting SHA key append your project package name by following symbol ";"
for example
**YOR\_SHA\_KEY;YOUR\_PROJECT\_MAIN\_PACKAGE\_NAME**
then generate key finally you will get google map key for android use that one hope it will resolve your problem make sure that your using same pakcage name which is your project package name
hope it will solve your problem happy coding :) |
21,519 | ---
I have an expression. I want to change all the Integers to a new form. The rule is, x\_Integer->x.\_f. But we should consider some special cases.
For example,
```
input = 22 + 4/5 x1 x1 x1 + (2 x2^4 + 343 Pi^4)/
Sqrt[67 - x1 x1 x3 x3 + x2^(5/4)] + (4 x1 - x2)^(-3/2 q) +
Exp[-x1 x1 + 4 x2 x2 - 3 x1];
```
The output expression should be,
```
output = 22. _f + E^(-3. _f x1 - x1^(2. _f) + 4. _f x2^(2. _f)) + (
4. _f x1^(3. _f))/(5. _f) + (4. _f x1 - x2)^(-3. _f x3/2. _f) + (
343. _f \[Pi]^(4. _f) + 2. _f x2^(4. _f))/Sqrt[
67. _f + x2^(5. _f/4. _f) - x1^(2. _f) x3^(2. _f)];
```
So, how to construct the rule function? Thanks! | 2013/03/17 | [
"https://mathematica.stackexchange.com/questions/21519",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5824/"
] | One simple way would be to do:
```
Unprotect[Integer];
Integer /:
Format[r_Integer, FortranForm] := (SequenceForm[r // N, "_f"]);
Protect[Integer];
Unprotect[Rational];
Rational /:
Format[r_Rational,
FortranForm] := (SequenceForm[Numerator[r] // N, "_f", "/",
Denominator[r] // N, "_f"]);
Protect[Rational];
Protect[Integer];
tos = ToString[#, InputForm] &;
pow[a_Symbol, b_Integer] := tos[a] <> "^" <> tos[FortranForm[b]];
pow[a_Symbol, b_] := tos[a] <> "^(" <> tos[FortranForm[b]] <> ")";
pow[a_, b_] := "(" <> tos[a] <> ")^(" <> tos[FortranForm[b]] <> ")";
input = 22 +
4/5 x1 x1 x1 + (2 x2^4 + 343 Pi^4)/
Sqrt[67 - x1 x1 x3 x3 + x2^(5/4)] + (4 x1 - x2)^(-3/2 q) +
Exp[-x1 x1 + 4 x2 x2 - 3 x1];
StringReplace[
ToString[FortranForm[input /. Power -> pow], InputForm], {"\\" -> "",
"\"" -> ""}]
```
which gives:
```
"22._f + (4 x1 - x2)^((-3._f*q)/2.) + E^(-x1^2._f + 4._f*x2^2._f - \
3._f*x1) + (4._f*x1^3._f)/5. + (67 + x2^(5._f/4._f) - x1^2._f \
x3^2._f)^(-1._f/2._f)*(343._f*Pi^4._f + 2._f*x2^4._f)"
``` | Simplifications/reordering that will separate the numbers from the `_f` pattern in a way that you seem to not want will take place on your given output expression if it is evaluated.
Therefore you will need some kind of hold function here. I will use `HoldForm`.
```
input = 22 +
4/5 x1 x1 x1 + (2 x2^4 + 343 Pi^4)/
Sqrt[67 - x1 x1 x3 x3 + x2^(5/4)] + (4 x1 - x2)^(-3/2 q) +
Exp[-x1 x1 + 4 x2 x2 - 3 x1];
input /. {
Rational[n_, d_] :> Divide @@ HoldForm /@ {N@n f_, N@d f_},
n_Integer :> HoldForm @@ {N[n] _f}
}
```
 |
106,278 | I've been wanting to know how to do 3d projections.[](https://i.stack.imgur.com/or349.png)
Can someone explain how i can use this to find the position for x and y on the 2d plane that is 600 \* 600 pixels. | 2015/08/25 | [
"https://gamedev.stackexchange.com/questions/106278",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/69577/"
] | Assuming that you want to compute the position that an arbitrary 3D vertex (x,y,z,1) has on the view plane after the projection: You can use the given parameters to compute a projection matrix:
[](https://i.stack.imgur.com/GdMJL.png)
where `f = cotangent(fovy * 0.5)`
This is also the matrix that will be set by a call to [gluPerspective](https://www.opengl.org/sdk/docs/man2/xhtml/gluPerspective.xml). Then, you can multiply this matrix with your vertex to obtain the projected vertex position. | Generally, you have to use a bunch of matrices. With the traditional OpenGL pipeline, you'd have to mutiply these matrices:
```
finalMatrix = modelMatrix
*
viewMatrix
*
projectionMatrix
*
viewport.windowMatrix;
```
To find the position of the vertex on your viewport, just multiply the vertex by the matrix:
```
onViewportVertex = in3dVertex * finalMatrix;
```
Of course, this implies that no shader modifies the vertex or the pixel. |
13,283,843 | I have a rails application where I get the following response when I use jQuery `get` function. I have to get all div elements with `id='users_belonging_to_project'`.
As you can see there are multiple divs with same id. I want to get the whole html() for those ids.
As it is returned from response, I used `$(data).find("div[id^='users_belonging_to_project']")` which is not giving the array of divs.
```
<div id='i_1' class='clicked'>A</div>
<div id='users_belonging_to_project' class='demo-container'>
<div id='2' class='user_clicked'>
tm@gmail.com
</div>
</div>
<div id='i_2' class='clicked'>B</div>
<div id='users_belonging_to_project' class='demo-container'>
<div id='2' class='user_clicked'>
tm@gmail.com
</div>
</div>
<div id='i_3' class='clicked'>dsf</div>
<div id='users_belonging_to_project' class='demo-container'>
<div id='3' class='user_clicked'>
tm1@gmail.com
</div>
</div>
<div id='i_4' class='clicked'>fd</div>
<div id='users_belonging_to_project' class='demo-container'>
<div id='2' class='user_clicked'>
tm@gmail.com
</div>
<div id='3' class='user_clicked'>
tm1@gmail.com
</div>
</div>
``` | 2012/11/08 | [
"https://Stackoverflow.com/questions/13283843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755162/"
] | I'll answer my own question: onInterceptTouchEvent only get called if the parent has a child view which returns "true" from onTouchEvent. Once the child returns true, the parent now has a chance to intercept that event.
 | I get the same problem. I had read many posts about it:
[onInterceptTouchEvent only gets ACTION\_DOWN](https://stackoverflow.com/questions/13283827/onintercepttouchevent-only-gets-action-down)
[onInterceptTouchEvent's ACTION\_UP and ACTION\_MOVE never gets called](https://stackoverflow.com/questions/21288081/onintercepttouchevents-action-up-and-action-move-never-gets-called)
[onInterceptTouchEvent, onTouchEvent only see ACTION\_DOWN](https://stackoverflow.com/questions/12592610/onintercepttouchevent-ontouchevent-only-see-action-down)
[onInterceptTouchEvent never receives action\_move](https://stackoverflow.com/questions/23725102/onintercepttouchevent-never-receives-action-move)
I also had read android doc:
<http://developer.android.com/training/gestures/viewgroup.html>
<http://developer.android.com/reference/android/view/ViewGroup.html#onInterceptTouchEvent(android.view.MotionEvent)>
All answers are same. I tried many times, always not get onInterceptTouchEvent
() be called if not down event.
I read source code, I guess that something is changed:
```
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
```
According above code, `onInterceptTouchEvent(ev)` is only be called when `MotionEvent.ACTION_DOWN`, this is what we tried and found. So, what I guess is, the code is changed, but doc not.
If you want spy or monitor all the events include those been sent to child views, you can override `dispatchTouchEvent()` like this:
```
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
MyLog.d(MyLog.DEBUG, "dispatchTouchEvent(): "+event.getAction());
if (isEnabled()) {
MyLog.d(MyLog.DEBUG, "dispatchTouchEvent()2: "+event.getAction());
processEvent(event);//here you get all events include move & up
super.dispatchTouchEvent(event);
return true; //to keep receive event that follow down event
}
return super.dispatchTouchEvent(event);
}
```
I have the runnable code at: <https://github.com/maxyou/gesturebutton/blob/master/src/com/maxproj/gesturebutton/GestureButtonLayout.java> |
13,283,843 | I have a rails application where I get the following response when I use jQuery `get` function. I have to get all div elements with `id='users_belonging_to_project'`.
As you can see there are multiple divs with same id. I want to get the whole html() for those ids.
As it is returned from response, I used `$(data).find("div[id^='users_belonging_to_project']")` which is not giving the array of divs.
```
<div id='i_1' class='clicked'>A</div>
<div id='users_belonging_to_project' class='demo-container'>
<div id='2' class='user_clicked'>
tm@gmail.com
</div>
</div>
<div id='i_2' class='clicked'>B</div>
<div id='users_belonging_to_project' class='demo-container'>
<div id='2' class='user_clicked'>
tm@gmail.com
</div>
</div>
<div id='i_3' class='clicked'>dsf</div>
<div id='users_belonging_to_project' class='demo-container'>
<div id='3' class='user_clicked'>
tm1@gmail.com
</div>
</div>
<div id='i_4' class='clicked'>fd</div>
<div id='users_belonging_to_project' class='demo-container'>
<div id='2' class='user_clicked'>
tm@gmail.com
</div>
<div id='3' class='user_clicked'>
tm1@gmail.com
</div>
</div>
``` | 2012/11/08 | [
"https://Stackoverflow.com/questions/13283843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755162/"
] | I'll answer my own question: onInterceptTouchEvent only get called if the parent has a child view which returns "true" from onTouchEvent. Once the child returns true, the parent now has a chance to intercept that event.
 | **dispatchTouchEvent, onInterceptTouchEvent, requestDisallowInterceptTouchEvent**
[[Touch event flow]](https://stackoverflow.com/a/57222691/4770877)
The official [doc](https://developer.android.com/guide/topics/ui/ui-events)
>
> `Activity.dispatchTouchEvent(MotionEvent)` - This allows your Activity to intercept all touch events before they are dispatched to the window.
>
>
> `ViewGroup.onInterceptTouchEvent(MotionEvent)` - This allows a ViewGroup to watch events as they are dispatched to child Views. It is recursively function (from parent to parent)
>
>
> `ViewParent.requestDisallowInterceptTouchEvent(boolean)` - Call this upon a parent View to indicate that it should not intercept touch events with onInterceptTouchEvent(MotionEvent).
>
>
> |
13,283,843 | I have a rails application where I get the following response when I use jQuery `get` function. I have to get all div elements with `id='users_belonging_to_project'`.
As you can see there are multiple divs with same id. I want to get the whole html() for those ids.
As it is returned from response, I used `$(data).find("div[id^='users_belonging_to_project']")` which is not giving the array of divs.
```
<div id='i_1' class='clicked'>A</div>
<div id='users_belonging_to_project' class='demo-container'>
<div id='2' class='user_clicked'>
tm@gmail.com
</div>
</div>
<div id='i_2' class='clicked'>B</div>
<div id='users_belonging_to_project' class='demo-container'>
<div id='2' class='user_clicked'>
tm@gmail.com
</div>
</div>
<div id='i_3' class='clicked'>dsf</div>
<div id='users_belonging_to_project' class='demo-container'>
<div id='3' class='user_clicked'>
tm1@gmail.com
</div>
</div>
<div id='i_4' class='clicked'>fd</div>
<div id='users_belonging_to_project' class='demo-container'>
<div id='2' class='user_clicked'>
tm@gmail.com
</div>
<div id='3' class='user_clicked'>
tm1@gmail.com
</div>
</div>
``` | 2012/11/08 | [
"https://Stackoverflow.com/questions/13283843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755162/"
] | I get the same problem. I had read many posts about it:
[onInterceptTouchEvent only gets ACTION\_DOWN](https://stackoverflow.com/questions/13283827/onintercepttouchevent-only-gets-action-down)
[onInterceptTouchEvent's ACTION\_UP and ACTION\_MOVE never gets called](https://stackoverflow.com/questions/21288081/onintercepttouchevents-action-up-and-action-move-never-gets-called)
[onInterceptTouchEvent, onTouchEvent only see ACTION\_DOWN](https://stackoverflow.com/questions/12592610/onintercepttouchevent-ontouchevent-only-see-action-down)
[onInterceptTouchEvent never receives action\_move](https://stackoverflow.com/questions/23725102/onintercepttouchevent-never-receives-action-move)
I also had read android doc:
<http://developer.android.com/training/gestures/viewgroup.html>
<http://developer.android.com/reference/android/view/ViewGroup.html#onInterceptTouchEvent(android.view.MotionEvent)>
All answers are same. I tried many times, always not get onInterceptTouchEvent
() be called if not down event.
I read source code, I guess that something is changed:
```
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
```
According above code, `onInterceptTouchEvent(ev)` is only be called when `MotionEvent.ACTION_DOWN`, this is what we tried and found. So, what I guess is, the code is changed, but doc not.
If you want spy or monitor all the events include those been sent to child views, you can override `dispatchTouchEvent()` like this:
```
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
MyLog.d(MyLog.DEBUG, "dispatchTouchEvent(): "+event.getAction());
if (isEnabled()) {
MyLog.d(MyLog.DEBUG, "dispatchTouchEvent()2: "+event.getAction());
processEvent(event);//here you get all events include move & up
super.dispatchTouchEvent(event);
return true; //to keep receive event that follow down event
}
return super.dispatchTouchEvent(event);
}
```
I have the runnable code at: <https://github.com/maxyou/gesturebutton/blob/master/src/com/maxproj/gesturebutton/GestureButtonLayout.java> | **dispatchTouchEvent, onInterceptTouchEvent, requestDisallowInterceptTouchEvent**
[[Touch event flow]](https://stackoverflow.com/a/57222691/4770877)
The official [doc](https://developer.android.com/guide/topics/ui/ui-events)
>
> `Activity.dispatchTouchEvent(MotionEvent)` - This allows your Activity to intercept all touch events before they are dispatched to the window.
>
>
> `ViewGroup.onInterceptTouchEvent(MotionEvent)` - This allows a ViewGroup to watch events as they are dispatched to child Views. It is recursively function (from parent to parent)
>
>
> `ViewParent.requestDisallowInterceptTouchEvent(boolean)` - Call this upon a parent View to indicate that it should not intercept touch events with onInterceptTouchEvent(MotionEvent).
>
>
> |
19,283,190 | I would like to know if there is any way of checking if a string exists inside another string (ie contains function). I have been taken a look to <http://forge.puppetlabs.com/puppetlabs/stdlib> but I haven't found this specific function. Maybe this is possible through a regexp, but I am not really sure how to do it. Can anybody help me this one? | 2013/10/09 | [
"https://Stackoverflow.com/questions/19283190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2209390/"
] | This is quite easy to do, check out the docs here:
<http://docs.puppetlabs.com/puppet/2.7/reference/lang_conditional.html>
A simple example:
```
if $hostname =~ /^www(\d+)\./ {
notice("Welcome to web server number $1")
}
``` | There is an ["in" operator in Puppet](https://puppet.com/docs/puppet/6.3/lang_expressions.html#in):
```
# Right operand is a string:
'eat' in 'eaten' # resolves to true
'Eat' in 'eaten' # resolves to true
# Right operand is an array:
'eat' in ['eat', 'ate', 'eating'] # resolves to true
'Eat' in ['eat', 'ate', 'eating'] # resolves to true
# Right operand is a hash:
'eat' in { 'eat' => 'present tense', 'ate' => 'past tense'} # resolves to true
'eat' in { 'present' => 'eat', 'past' => 'ate' } # resolves to false
# Left operand is a regular expression (with the case-insensitive option "?i")
/(?i:EAT)/ in ['eat', 'ate', 'eating'] # resolves to true
# Left operand is a data type (matching integers between 100-199)
Integer[100, 199] in [1, 2, 125] # resolves to true
Integer[100, 199] in [1, 2, 25] # resolves to false
``` |
32,741,811 | Please tell me how can I get all prints that I see when I run ./manage.py runserver locally. I dont want to use logger. Ideally I would like to connect to my manage.py and see what is server is printing for me now.
I tried [django print information on production server](https://stackoverflow.com/questions/5653566/django-print-information-on-production-server) with no success.
I know that i cat just tail -f logfile and i will see last lines, but i could not find where is my prints located. Please help.
Here is my logging config:
```
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
},
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue'
}
},
'formatters': {
'main_formatter': {
'format': '%(levelname)s:%(name)s: %(message)s '
'(%(asctime)s; %(filename)s:%(lineno)d)',
'datefmt': "%Y-%m-%d %H:%M:%S",
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'console':{
#'level': 'DEBUG',
'level': 'ERROR',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'main_formatter',
},
'production_file':{
'level' : 'INFO',
'class' : 'logging.handlers.RotatingFileHandler',
'filename' : 'logs/main.log',
'maxBytes': 1024*1024*5, # 5 MB
'backupCount' : 7,
'formatter': 'main_formatter',
'filters': ['require_debug_false'],
},
'debug_file':{
'level' : 'DEBUG',
'class' : 'logging.handlers.RotatingFileHandler',
'filename' : 'logs/main_debug.log',
'maxBytes': 1024*1024*5, # 5 MB
'backupCount' : 7,
'formatter': 'main_formatter',
'filters': ['require_debug_true'],
},
'null': {
"class": 'django.utils.log.NullHandler',
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins', 'console'],
'level': 'ERROR',
'propagate': True,
},
'django': {
'handlers': ['null', ],
},
'py.warnings': {
'handlers': ['null', ],
},
'': {
'handlers': ['console', 'production_file', 'debug_file'],
'level': "DEBUG",
},
}
```
} | 2015/09/23 | [
"https://Stackoverflow.com/questions/32741811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443062/"
] | If you run your application in production setup, i.e. APACHE server your can find prints in file located in destination, which you configured in your apache config.
For example: 'ErrorLog /var/log/httpd-error.log' | Django can be run as multi-threaded server without master, so there is no simple way to join all std output together. Logging is simplest and best solution here, you can define many log handlers, even send all logs into some socket, where some simple logging server will reside that will catch all logs and print them into console. Running that server on screen will allow you to connect to it and see some last messages from it. |
10,150,513 | Can anyone tell me how I can implement a default template/layout for my whole project in codeigniter?
One way I found is [Templating with Code Igniter (CI Forums)](http://codeigniter.com/forums/viewthread/88664/)
Is there any other way? Can anyone post complete example code? | 2012/04/14 | [
"https://Stackoverflow.com/questions/10150513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884995/"
] | There are a few ways I know of one of them is to create a header and footer view for your site / project.
```
application/views/template/header.php
application/views/template/footer.php
```
Then you have your other pages arranged how you would like.
```
application/views/users/login.php
```
In your controller you would do something like this
```
<?php
class Blah extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('template/header');
$this->load->view('users/login');
$this->load->view('template/footer');
}
}
```
There is also a useful little template library I stumbled across, that makes this even simpler. I don't find it quite as flexible as typing out the other way of doing it though.
<http://maestric.com/doc/php/codeigniter_template>
EDIT::
I should of given some example code for the template so here you go
header.php
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Lovely Title</title>
</head>
<body>
<h1>Check This Out!!1!</h1>
<div class="container">
```
footer.php
```
</div>
</body>
</html>
``` | You can always load a view withing other view and implement what you want.
Other better way is to use a template engine which supports template inheritance like
* [Twig](http://twig.sensiolabs.org/doc/templates.html#template-inheritance)
* [Smarty](http://www.smarty.net/inheritance)
* [Dwoo](http://wiki.dwoo.org/index.php/TemplateInheritance)
Using them in CodeIgniter is fairly easy as there are many implementations of the libraries for CI. |
10,150,513 | Can anyone tell me how I can implement a default template/layout for my whole project in codeigniter?
One way I found is [Templating with Code Igniter (CI Forums)](http://codeigniter.com/forums/viewthread/88664/)
Is there any other way? Can anyone post complete example code? | 2012/04/14 | [
"https://Stackoverflow.com/questions/10150513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884995/"
] | Make one layout view. Some thing like this:
```
<html>
<head>
<title>My awesome site</title>
</head>
<body>
<?= $this->load->view('shared/header') ?>
<?= $this->load->view($partial) ?>
<?= $this->load->view('shared/footer') ?>
</body>
</html>
```
Then in your controller do this:
```
$this->data['partial'] = 'pages/index';
$this->load->view('layout/layout', $this->data);
```
If you have a MY\_Controller file you can create a method there:
```
function load_view($partial)
{
$this->data['partial'] = $partial;
$this->load->view('layout/layout', $this->data);
}
```
Then in controllers that inherit from MY\_Controller you can use:
```
$this->load_view('pages/index'); // pages/index will be loaded in the layout
``` | You can always load a view withing other view and implement what you want.
Other better way is to use a template engine which supports template inheritance like
* [Twig](http://twig.sensiolabs.org/doc/templates.html#template-inheritance)
* [Smarty](http://www.smarty.net/inheritance)
* [Dwoo](http://wiki.dwoo.org/index.php/TemplateInheritance)
Using them in CodeIgniter is fairly easy as there are many implementations of the libraries for CI. |
10,150,513 | Can anyone tell me how I can implement a default template/layout for my whole project in codeigniter?
One way I found is [Templating with Code Igniter (CI Forums)](http://codeigniter.com/forums/viewthread/88664/)
Is there any other way? Can anyone post complete example code? | 2012/04/14 | [
"https://Stackoverflow.com/questions/10150513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/884995/"
] | Make one layout view. Some thing like this:
```
<html>
<head>
<title>My awesome site</title>
</head>
<body>
<?= $this->load->view('shared/header') ?>
<?= $this->load->view($partial) ?>
<?= $this->load->view('shared/footer') ?>
</body>
</html>
```
Then in your controller do this:
```
$this->data['partial'] = 'pages/index';
$this->load->view('layout/layout', $this->data);
```
If you have a MY\_Controller file you can create a method there:
```
function load_view($partial)
{
$this->data['partial'] = $partial;
$this->load->view('layout/layout', $this->data);
}
```
Then in controllers that inherit from MY\_Controller you can use:
```
$this->load_view('pages/index'); // pages/index will be loaded in the layout
``` | There are a few ways I know of one of them is to create a header and footer view for your site / project.
```
application/views/template/header.php
application/views/template/footer.php
```
Then you have your other pages arranged how you would like.
```
application/views/users/login.php
```
In your controller you would do something like this
```
<?php
class Blah extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('template/header');
$this->load->view('users/login');
$this->load->view('template/footer');
}
}
```
There is also a useful little template library I stumbled across, that makes this even simpler. I don't find it quite as flexible as typing out the other way of doing it though.
<http://maestric.com/doc/php/codeigniter_template>
EDIT::
I should of given some example code for the template so here you go
header.php
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Lovely Title</title>
</head>
<body>
<h1>Check This Out!!1!</h1>
<div class="container">
```
footer.php
```
</div>
</body>
</html>
``` |
51,385,015 | I am trying to convert the integers contained into a string like `"15m"` into an `integer`.
With the code below I can achieve what I want. But I am wondering if there is a better solution for this, or a function I'm not aware of which already implements this.
```
s = "15m"
s_result = ""
for char in s:
try:
i = int(char)
s_result = s_result + char
except:
pass
result = int(s_result)
print result
```
This code would output below result:
```
>>>
15
```
Maybe there is no such "better" solution but I would like to see other solutions, like using `regex` maybe. | 2018/07/17 | [
"https://Stackoverflow.com/questions/51385015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5399268/"
] | I found a good solution using regex.
```
import re
result = int(re.sub('[^0-9]','', s))
print result
```
Which results in:
```
>>>
15
``` | You could also match one or more digits from the start of the line `^\d+`
```
import re
regex = r"^\d+"
test_str = "15m"
match = re.search(regex, test_str)
if match:
print (int(match.group()))
``` |
955,056 | Recently, I found a new job which uses O365 in a hybrid environment. Just to explain a bit, the new environment has On-premises Active Directory plus an instance of On-premises Exchange Server (which actually has no user mailboxes inside). The On-premises Active Directory is synced to an Azure AD in the cloud and all user mailboxes are in Exchange Online in O365.
Currently, for day-to-day administration like updating security groups and distribution groups, I basically update the On-premises AD which will synchronize to O365. If I attempt to update them in Office 365 portal, it will display an error saying that I should go to update it on On-premises AD. The security groups are used by local File Server as well as distribution list in sending emails. However, my manager suddenly announced today he planned to make changes so that we have to go to Office 365 Portal to do the update instead of On-premises AD.
My questions are:
1) What config changes do we need to do in Office 365 in order to achieve what he wants?
2) What advantage do we get by updating in Office 365 portal instead of On-premises AD? | 2019/02/21 | [
"https://serverfault.com/questions/955056",
"https://serverfault.com",
"https://serverfault.com/users/510279/"
] | Without knowing exactly what your manager means we can't answer this question. That being said, I suspect he either doesn't understand how directory synchronization works or he's about to break something.
With directory synchronization (through Azure AD Connect) the source of authority for object attributes is the on premises directory. You can't manage most attributes in Office 365 and must manage them on premises. | If the objects are synced from on-premise to online, then the objects could only be managed on-premise.
If you would like to manage the objects online, then it should be the online-only object (not synced). |
589,767 | This question referes to a definition in Eugene M. Luks paper "Isomorphism of Graphs of Bounded Valence Can Be Tested in Polynomial Time" (1981), page 48, available at <http://ix.cs.uoregon.edu/~luks/iso.pdf>.
Let $X$ be a (simple, undirected) trivalent graph (that is, a graph with max node degree 3) and let $e$ be a distinguished edge in $X$. For $r \in \{1,...,n\}$, let $X\_r$ be the subgraph consisting of all vertices and all edges of $X$ which appear in paths of length $\leq{}r$ trough $e$. Let $\text{Aut}\_e(X\_r)$ be the subgroup of $\text{Aut}(X\_r)$ containing all automorphism that fix edge $e$.
It is claimed without proof that $\pi\_r: \text{Aut}\_e(X\_{r+1}) \to \text{Aut}\_e(X\_r)$, $\sigma \mapsto \sigma|\_{X\_r}$ (i.e, every automorphism on $X\_{r+1}$ is restricted to $X\_r$) is a group homomorphism.
However, I do not see how the restriction of any $\sigma\in\text{Aut}\_e(X\_{r+1})$ is a automorphism on $X\_r$ and thus a member of $\text{Aut}\_e(X\_r)$. Moreover, I think I found a counterexample:
Let $X$ be the fully connected graph with three vertices $v\_0,v\_1,v\_2$. Let the distinguished edge $e=(v\_0,v\_1)$. Then $X\_1$ is the graph with nodes $v\_0,v\_1$ and edge $e$. $X\_2 =X$. Therefore, $\text{Aut}\_e(X\_1)$ is isomorphic to $S\_2$ (containing two elements, the identity and the transposition of both nodes). The automorphism group of $X\_2$ however is isomorphic to $S\_3$, which also contains the rotation of the nodes. Thus, let $\sigma$ be the rotation $v\_i \mapsto v\_{i+1}$ with addition modulo 3. Then, for the restriction of $\sigma$ to $X\_1$ it holds $\sigma|\_{X\_1}(v\_2) = v\_3 \notin X\_1$, and therefore $\sigma|\_{X\_1} \notin \text{Aut}\_e(X\_1)$. Thus, $\pi\_2$ cannot be a group homomorphism $\text{Aut}\_e(X\_{2}) \to \text{Aut}\_e(X\_1)$.
I suppose I am missing something. What is it? | 2013/12/02 | [
"https://math.stackexchange.com/questions/589767",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/112918/"
] | No, not necessarily. For a proof to be sound, then indeed, we need for $p\land q$ to be true.
But validity depends only on the *form* of an argument, not the semantic content of the argument. An argument or proof is valid provided the conclusion is logically implied by the premises. Indeed, we can have valid argument *forms* in which one or more premises is false.
>
> If my apple is blue, then pigs can fly.
>
>
> My apple is blue.
>
>
> Therefore, pigs can fly.
>
>
>
This is a **valid** argument but it certainly is **not sound**: It is valid by modus ponens. All arguments of the form $$\begin{align} P \rightarrow Q \\ \\ P \\ \hline \\ \therefore Q\end{align}$$
are valid, *just by virtue of the structure or form of the argument.*
Of course, mathematical proofs usually only become interesting when they are sound: when the premises are true, and the conclusion(s) logically follow(s) from the premises. So indeed, we take great care to ensure that the premises are true, which would ensure us that the premises of an argument, by themselves, are not responsible for any contradiction reached when assuming the negation of the desired conclusion! | It is wrong. What you are describing in your last line, is the *modus ponens*, where from $A \to B$ and $A$ one deduces $B$. But the truth of $A$ has nothing to do with the truth of the implication $A \to B$, in fact this is completely true:
>
> If $1$ is $0$, then $1$ is $1$
>
>
> |
53,559,587 | I have a short bit of code that needs to run for a long long time. I am wondering if the length of the variable's names that I use can alter the speed at which the program executes. Here is a very simple example written in Python.
Program A
```
x = 1
while not x == 0:
print('message')
```
Program B
```
xyz = 1
while not xyz == 0:
print('message')
```
Will Program A print 'message' more times than Program B if I run program A and program B for 30 years on two identical machines. | 2018/11/30 | [
"https://Stackoverflow.com/questions/53559587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8896653/"
] | No, the names themselves have no effect on how quickly the resulting code runs. Variable names are just used to distinguish in the Python source two variables that are represented by integer indices into a lookup table:
```
>>> dis.dis('x=1')
1 0 LOAD_CONST 0 (1)
2 STORE_NAME 0 (x)
4 LOAD_CONST 1 (None)
6 RETURN_VALUE
>>> dis.dis('xyz=1')
1 0 LOAD_CONST 0 (1)
2 STORE_NAME 0 (xyz)
4 LOAD_CONST 1 (None)
6 RETURN_VALUE
>>> dis.dis('x=1;xyz=2;')
1 0 LOAD_CONST 0 (1)
2 STORE_NAME 0 (x)
4 LOAD_CONST 1 (2)
6 STORE_NAME 1 (xyz)
8 LOAD_CONST 2 (None)
10 RETURN_VALUE
```
In the first two, you'll notice no distinction based the variable name is made in the resulting byte code. In the last, you'll see that the byte code differentiates between the two, but only on the order in which they are defined, not the length of the label. | The difference is very small and we cant conclude that is because of name of variable.
```
import timeit
x=1
xyz=1
start_time = timeit.default_timer()
for i in range(1,1000000):
if x==1:
print("message")
elapsed = timeit.default_timer() - start_time
start_time2 = timeit.default_timer()
for i in range(1,1000000):
if xyz==1:
print("message")
elapsed2 = timeit.default_timer() - start_time2
print("small variable printing = ",str(elapsed),"big variable printing = "+str(elapsed2))
```
And the Result was :
```
small variable printing = 3.6490847053481588 big variable printing = 3.7199463989460435
``` |
53,559,587 | I have a short bit of code that needs to run for a long long time. I am wondering if the length of the variable's names that I use can alter the speed at which the program executes. Here is a very simple example written in Python.
Program A
```
x = 1
while not x == 0:
print('message')
```
Program B
```
xyz = 1
while not xyz == 0:
print('message')
```
Will Program A print 'message' more times than Program B if I run program A and program B for 30 years on two identical machines. | 2018/11/30 | [
"https://Stackoverflow.com/questions/53559587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8896653/"
] | No, the names themselves have no effect on how quickly the resulting code runs. Variable names are just used to distinguish in the Python source two variables that are represented by integer indices into a lookup table:
```
>>> dis.dis('x=1')
1 0 LOAD_CONST 0 (1)
2 STORE_NAME 0 (x)
4 LOAD_CONST 1 (None)
6 RETURN_VALUE
>>> dis.dis('xyz=1')
1 0 LOAD_CONST 0 (1)
2 STORE_NAME 0 (xyz)
4 LOAD_CONST 1 (None)
6 RETURN_VALUE
>>> dis.dis('x=1;xyz=2;')
1 0 LOAD_CONST 0 (1)
2 STORE_NAME 0 (x)
4 LOAD_CONST 1 (2)
6 STORE_NAME 1 (xyz)
8 LOAD_CONST 2 (None)
10 RETURN_VALUE
```
In the first two, you'll notice no distinction based the variable name is made in the resulting byte code. In the last, you'll see that the byte code differentiates between the two, but only on the order in which they are defined, not the length of the label. | The results that @chepner mentioned are correct, Python can take longer to run the code in the console, but once the code is compiled the results are the same.
To make sure that this is correct, I created the following code also inspired by the answer from @knifer:
```
from time import time
from numpy import average,std
x = 1
xyzabcdexyzabcdefghidjakeldkjlkfghidjakeldkjlk = 1
short_runs = 0
long_runs = 0
for _ in range(int(2e7)):
t0 = time()
if x:
pass
short_runs += time() - t0
t0 = time()
if xyzabcdexyzabcdefghidjakeldkjlkfghidjakeldkjlk:
pass
long_runs += time() - t0
print('Runtime results:')
print(f"Small variable runs : (sum = {short_runs:.3f})")
print(f"Long variable runs : (sum = {long_runs :.3f})")
```
The code I propose is somewhat different, in the sense that the trial runs for the long and the short variable names are intertwined, such that any differences caused by underlying OS processes are minimized.
The results of the code vary depending on whether you `copy-paste` the code into a Python console, or you call the code as a program (`python trial_runs.py`). Runs using `copy-paste` tend to be slower using long variables names, whereas calling the code as a program yields identical running times.
PS. The actual running times change all the time for me (in one direction or the other), so it's hard to report exact values. Even the long variable names can sometimes run faster, although this is very rare on the Python console. The biggest conclusion is that any differences are really small either way :) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.