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
4,994,071
I am making a use case diagram, and the problem is: I type some text and it is always display in one line, making my use case elipse too big. Does anyone know how to make it go to the next line? I think this option is called wrap text in StarUML... Thank you in advance! Nanek
2011/02/14
[ "https://Stackoverflow.com/questions/4994071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616446/" ]
When you wish to edit a shape, you need to unlock the protection attributes applied on the shape. None of the answers here have informed you how to show the "Shape Data". 1. You need to select File menu on the top. Select "Options" and select "Advanced" 2. Scroll down till the end and select "Run in Developer mode". Press Ok. 3. Select Home menu at the top to return to your diagram. 4. Right click on your Shape (let's say you're editing a Use case shape) 5. Select "Show ShapeSheet" option. 6. You will be able to see a window below the diagram window. In this window, scroll down until you can see the "Protection" preferences. 7. Select "LockTextEdit" variable and double click and change 1 to 0. Press enter to save your preference. 8. Now click on the shape and select "Text" from format menu. 9. Click on the text and you will be able to Edit it. Press Enter key in between the text where you need to insert line break.
Select the shape. use this menu: [Home] -> [Tools] -> [Text] now text editing is available on the shape. Now by just hitting shift+enter on every place you want to end the line, you can wrap text manually. Good Luck
4,994,071
I am making a use case diagram, and the problem is: I type some text and it is always display in one line, making my use case elipse too big. Does anyone know how to make it go to the next line? I think this option is called wrap text in StarUML... Thank you in advance! Nanek
2011/02/14
[ "https://Stackoverflow.com/questions/4994071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616446/" ]
Try editing the TextBox properties in the object properties dialog.
click into the text box and hit enter between the text you want on the next line.
4,994,071
I am making a use case diagram, and the problem is: I type some text and it is always display in one line, making my use case elipse too big. Does anyone know how to make it go to the next line? I think this option is called wrap text in StarUML... Thank you in advance! Nanek
2011/02/14
[ "https://Stackoverflow.com/questions/4994071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616446/" ]
1. Right-click the use case. 2. Select "Show ShapeSheet". 3. Scroll down to the "Protection" section. 4. Change the value near "LockTextEdit" to `0`. 5. Close the ShapeSheet. Now press `F2` and edit the name. Add line breaks with `Enter`. It is tedious to unprotect each use case individually. If you are starting a new diagram, you may want to unprotect one use case and copy it instead of adding new use cases from the palette. The downside of adding line breaks to the name of use case is that when you modify its properties, the name truncates to the first line break. Luckily, use cases do not have much useful properties other than name and documentation.
click into the text box and hit enter between the text you want on the next line.
3,508,560
I'm relatively new to programming in general so be gentle =| I'm trying to start a new activity from a basic one that displays a couple of text inputs, a checkbox, and a button. When the button is pressed I want it to switch to the new activity. The code compiles but when I press the button in Android it simply crashes. Any help would be greatly appreciated. **Here is the code sample:** ``` public class Something extends Activity implements OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); Button login = (Button)findViewById(R.id.login); login.setOnClickListener(this); } @Override public void onClick(View v) { startActivity(new Intent().setClass(Something.this, That.class)); } } ``` **Error Log:** > > I/ActivityManager( 240): Starting activity: Intent { > cmp=jano.huerta.sfgc/.HOME } D/AndroidRuntime(13612): Shutting down > VM W/dalvikvm(13612): threadid=1: thread exiting with uncaught > exception (group=0x4 0025a08) E/AndroidRuntime(13612): FATAL > EXCEPTION: main E/AndroidRuntime(13612): java.lang.RuntimeException: > Unable to start activity Co > mponentInfo{jano.huerta.sfgc/jano.huerta.sfgc.HOME}: > android.content.ActivityNot FoundException: Unable to find explicit > activity class {jano.huerta.sfgc/jano.hu erta.sfgc.SUMMARY}; have you > declared this activity in your AndroidManifest.xml? > > > E/AndroidRuntime(13612): at > android.app.ActivityThread.performLaunchActiv > ity(ActivityThread.java:2787) E/AndroidRuntime(13612): at > android.app.ActivityThread.handleLaunchActivi > ty(ActivityThread.java:2803) E/AndroidRuntime(13612): at > android.app.ActivityThread.access$2300(Activi tyThread.java:135) > E/AndroidRuntime(13612): at > android.app.ActivityThread$H.handleMessage(Ac tivityThread.java:2136) > E/AndroidRuntime(13612): at > android.os.Handler.dispatchMessage(Handler.ja va:99) > E/AndroidRuntime(13612): at > android.os.Looper.loop(Looper.java:144) E/AndroidRuntime(13612): > > at android.app.ActivityThread.main(ActivityThrea d.java:4937) > E/AndroidRuntime(13612): at > java.lang.reflect.Method.invokeNative(Native Method) > E/AndroidRuntime(13612): at > java.lang.reflect.Method.invoke(Method.java:5 21) > E/AndroidRuntime(13612): at > com.android.internal.os.ZygoteInit$MethodAndA > rgsCaller.run(ZygoteInit.java:868) E/AndroidRuntime(13612): at > com.android.internal.os.ZygoteInit.main(Zygot eInit.java:626) > E/AndroidRuntime(13612): at > dalvik.system.NativeStart.main(Native Method) > > > E/AndroidRuntime(13612): Caused by: > android.content.ActivityNotFoundException: U nable to find explicit > activity class {jano.huerta.sfgc/jano.huerta.sfgc.SUMMARY }; have you > declared this activity in your AndroidManifest.xml? > E/AndroidRuntime(13612): at > android.app.Instrumentation.checkStartActivit > yResult(Instrumentation.java:1563) E/AndroidRuntime(13612): at > android.app.ActivityThread.resolveActivityInf > o(ActivityThread.java:2597) E/AndroidRuntime(13612): at > android.app.LocalActivityManager.startActivit > y(LocalActivityManager.java:277) E/AndroidRuntime(13612): at > android.widget.TabHost$IntentContentStrategy. > getContentView(TabHost.java:651) E/AndroidRuntime(13612): at > android.widget.TabHost.setCurrentTab(TabHost. java:323) > E/AndroidRuntime(13612): at > android.widget.TabHost.addTab(TabHost.java:21 3) > E/AndroidRuntime(13612): at > jano.huerta.sfgc.HOME.onCreate(HOME.java:23) E/AndroidRuntime(13612): > at android.app.Instrumentation.callActivityOnCre > ate(Instrumentation.java:1069) E/AndroidRuntime(13612): at > android.app.ActivityThread.performLaunchActiv > ity(ActivityThread.java:2751) E/AndroidRuntime(13612): ... 11 > more W/ActivityManager( 240): Force finishing activity > jano.huerta.sfgc/.HOME W/ActivityManager( 240): Force finishing > activity jano.huerta.sfgc/.SFGC W/ActivityManager( 240): Activity > pause timeout for HistoryRecord{466bbec0 jano .huerta.sfgc/.HOME} > D/dalvikvm( 406): GC\_EXPLICIT freed 418 objects / 26008 bytes in 90ms > I/Process (13612): Sending signal. PID: 13612 SIG: 9 > I/ActivityManager( 240): Process jano.huerta.sfgc (pid 13612) has > died. I/WindowManager( 240): WIN DEATH: Window{466cb800 > jano.huerta.sfgc/jano.huerta. sfgc.SFGC paused=true} > W/ActivityManager( 240): Activity destroy timeout for > HistoryRecord{46654450 ja no.huerta.sfgc/.SFGC} > > >
2010/08/18
[ "https://Stackoverflow.com/questions/3508560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423519/" ]
The most common mistake here is forgetting to register the 'That' activity in your AndroidManifest.xml. Have you done that? Also, it would be much easier to help you if you pasted the stack trace from your crash. You can see crash info, amongst other logging, by running `adb logcat`.
Never forget to add the `<activity>` tag in the Manifest.xml. ============================================================= All activities **MUST** be added in the Manifest File. Android Activity is an essential Android Component which should be registered. ### Why? The Activity is started and destroyed by Android OS. So when you call, ``` Intent i = new Intent(this, TargetActivity.class); startActicvity(i); ``` Then the OS looks for the Activity in the `Manifest.xml` file. If it does not find the matching activity then you will get following error: > > android.content.ActivityNot FoundException: Unable to find explicit > activity > > > ### How to add activity in Manifest file? Add this in the Manifest file. ``` <activity android:name=".TargetActivity"/> ``` It is the most basic form. You can explore more [HERE](https://developer.android.com/guide/topics/manifest/manifest-intro#components)
479,205
I am working on a project where I need to generate random numbers for a given task time which is normally distributed with mean = 40, and standard deviation = 150. Because of the high SD, I will get some negative values and low values when I generated numbers directly which is unrealistic. Is there any way where I can generate random numbers normally distributed with limitations (i.e. bounds)?
2020/07/27
[ "https://stats.stackexchange.com/questions/479205", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/292467/" ]
This sounds like you want to sample from [truncated normal distribution](https://en.wikipedia.org/wiki/Truncated_normal_distribution). If you only want to truncate the tails of the distribution (regions with low probability), than the approach suggested by *Dave* is probably enough. In other cases it might however quickly get inefficient. Better approach was suggested by Christian P. Robert in > > Robert, C.P. (1995). [Simulation of truncated normal variables.](http://arxiv.org/abs/0907.4010) > *Statistics and Computing 5*(2): 121-125. > > > The algorithm is a bit more complicated, so I suggest you check the paper. Alternatively, if you prefer the code [here you can find a C++ implementation](https://github.com/twolodzko/extraDistr/blob/master/src/truncated-normal-distribution.cpp#L109) from R package [extraDistr](https://github.com/twolodzko/extraDistr) (disclaimer: it's written by me).
I could imagine something where you use some if/else logic to screen for unrealistic values. There would be some kind of recursion where you keep drawing random numbers u til you’ve gotten 1000 (or whatever) realistic values. Some pseudocode: ``` i=0 while i < 1000: x = make your draw here # (np.random.normal or rnorm, for instance) if x is realistic: sample[i] = x increase i by 1 ``` This will keep drawing random numbers for observation i until it gets a realistic value. Note that you are not simulating normal data if you do this, as any real number is technically possible for any normal distribution, and you eliminate some values.
479,205
I am working on a project where I need to generate random numbers for a given task time which is normally distributed with mean = 40, and standard deviation = 150. Because of the high SD, I will get some negative values and low values when I generated numbers directly which is unrealistic. Is there any way where I can generate random numbers normally distributed with limitations (i.e. bounds)?
2020/07/27
[ "https://stats.stackexchange.com/questions/479205", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/292467/" ]
I could imagine something where you use some if/else logic to screen for unrealistic values. There would be some kind of recursion where you keep drawing random numbers u til you’ve gotten 1000 (or whatever) realistic values. Some pseudocode: ``` i=0 while i < 1000: x = make your draw here # (np.random.normal or rnorm, for instance) if x is realistic: sample[i] = x increase i by 1 ``` This will keep drawing random numbers for observation i until it gets a realistic value. Note that you are not simulating normal data if you do this, as any real number is technically possible for any normal distribution, and you eliminate some values.
While your question is not entirely clear about what you are trying to achieve (*how* do you wish to go from a Gaussian distribution to a distribution that is truncated at 0?)... ... I thought that it was interesting to show something about the limit of the ratio between the mean and standard deviation of a Gaussian distribution that is truncated at $x=0$. (this issue has been mentioned in some of the comments) --- Below is a piece of code and a graph that shows the computation of Gaussian distributions that have been truncated at different z-values (and shifted and re-scaled appropriately in order to have the truncating occur at $x=0$ and have the population mean equal to $\bar{x} = 40$). What we can notice is that by changing the point where we truncate the distribution we can shift from a curve that looks like a Gaussian distribution (when we cut at a low z-value) to a curve that approaches an exponential distribution (when we cut at a high z-value and only have the right tail, which approximates an exponential function). From this display I guess, intuitively, that the ratio of the standard deviation and the mean for this truncated distribution, is not able to become larger than this ratio for an exponential distribution (for an exponential distribution this ratio is 1). **Therefore: By truncating a normal distribution such that no negative values appear, we can *not* get a distribution whose standard deviation is larger than it's mean.** (and you are looking for sd = 150 and mean = 40, which means that truncating a normal distribution won't be able to do it) [![example of different ways to truncate](https://i.stack.imgur.com/QWzyM.png)](https://i.stack.imgur.com/QWzyM.png) ```r library(truncnorm) x = seq(-10^3,10^3,0.1) ### empty canvas/plot plot(-100,-100, ylim = c(0,0.025), xlim = c(0,200), xlab = "x", ylab = "density") d = 20 ### number of curves i = 0 ### counter used in for-loop varst = rep(0,d-1) for (trunc in qnorm(seq(1/d,1-1/d,1/d))) { ### compute truncated standard normal ### and it's mean and variance y <- dtruncnorm(x, mean = 0, sd = 1, a = trunc) mean = dnorm(trunc)/(1-pnorm(trunc)) var = (1+trunc*dnorm(trunc)/(1-pnorm(trunc)) - mean^2) ### transform such that the mean is equal to 40 xtrans <- (x-trunc)*40/(mean-trunc) ytrans <- y/(40/(mean-trunc)) ### storing variance of transformed trucated standard normal (multipliying with square of scalefactor) varst[i+1] = var*(40/(mean-trunc))^2 ### plot lines(xtrans[xtrans>=0],ytrans[xtrans>=0], col = hsv(0.15+i/2/d,1-i/2/d,1-(d-i)/4/d,1)) i = i+1 } ### exponential distribution lines(x[x>=0],dexp(x,rate=1/40)[x>=0], lty = 2) i = 1:(d-1) legend(200,0.025,xjust = 1, cex = 0.7, legend = c("exponential distribution", "normal distribution cut at 5%", "normal distribution cut at 95%"), lty = c(2,1,1), col = c(1, hsv(0.15+i/2/d,1-i/2/d,1-(d-i)/4/d,1)[c(1,d-1)])) ``` For the equations used to compute the mean and variance of the truncated normal distribution see: <https://en.wikipedia.org/wiki/Truncated_normal_distribution>
479,205
I am working on a project where I need to generate random numbers for a given task time which is normally distributed with mean = 40, and standard deviation = 150. Because of the high SD, I will get some negative values and low values when I generated numbers directly which is unrealistic. Is there any way where I can generate random numbers normally distributed with limitations (i.e. bounds)?
2020/07/27
[ "https://stats.stackexchange.com/questions/479205", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/292467/" ]
This sounds like you want to sample from [truncated normal distribution](https://en.wikipedia.org/wiki/Truncated_normal_distribution). If you only want to truncate the tails of the distribution (regions with low probability), than the approach suggested by *Dave* is probably enough. In other cases it might however quickly get inefficient. Better approach was suggested by Christian P. Robert in > > Robert, C.P. (1995). [Simulation of truncated normal variables.](http://arxiv.org/abs/0907.4010) > *Statistics and Computing 5*(2): 121-125. > > > The algorithm is a bit more complicated, so I suggest you check the paper. Alternatively, if you prefer the code [here you can find a C++ implementation](https://github.com/twolodzko/extraDistr/blob/master/src/truncated-normal-distribution.cpp#L109) from R package [extraDistr](https://github.com/twolodzko/extraDistr) (disclaimer: it's written by me).
Whilst it is certainly quite simple to generate from a truncated normal distribution, if it is unrealistic to have negative values, you should rethink whether this distribution is appropriate. In the present case the lower-bound for the truncation occurs very close to the mean, and so the resulting distribution does not look much like a normal distribution. In any case, in the answer below I show how you can generate values from a truncated normal distribution. --- A simple and efficient method to generate random variables from truncated distributions (without discarding generated values) is to generate uniform random variables over the appropriate quantile range, and then use inverse transformation sampling to get the truncated random variables you want. To generate truncated normal random variables with minimum value $x\_\min$ and maximum value $x\_max$, we first compute the bounds for the quantile: $$u\_\min \equiv \Phi^{-1} \bigg( \frac{x\_\min-\mu}{\sigma} \bigg) \quad \quad \quad u\_\max \equiv \Phi^{-1} \bigg( \frac{x\_\max-\mu}{\sigma} \bigg).$$ We generate the random quantiles $U\_1,...,U\_n \sim \text{IID U}(u\_\min, u\_max)$ and we then compute the variables: $$X\_i = \Phi \Big( (\mu + U\_i) \sigma \Big).$$ The resulting values $X\_1,...,X\_n \sim \text{IID TruncN}(\mu, \sigma, x\_\min, x\_max)$ are lower-truncated normal random variables. Here is a function in `R` to generate these values. ``` #Function to generate IID values from truncated normal distribution rtruncnorm <- function (n, mean = 0, sd = 1, xmin = -Inf, xmax = Inf) { #Check inputs if (!is.numeric(xmin)) { stop('Error: xmin must be numeric') } if (!is.vector(xmin)) { stop('Error: xmin must be a single number') } if (length(xmin) != 1) { stop('Error: xmin must be a single number') } if (!is.numeric(xmax)) { stop('Error: xmax must be numeric') } if (!is.vector(xmax)) { stop('Error: xmax must be a single number') } if (length(xmax) != 1) { stop('Error: xmax must be a single number') } if (xmin > xmax) { stop('Error: xmin cannot be larger than xmax') } #Generate random quantiles UMIN <- pnorm(xmin, mean = mean, sd = sd); UMAX <- pnorm(xmax, mean = mean, sd = sd); RAND <- runif(n = n, min = UMIN, max = UMAX); #Compute output variables OUT <- qnorm(RAND, mean = mean, sd = sd, log = FALSE); OUT; } ``` In your problem you have paramaters $\mu = 40$, $\sigma = 150$, $x\_\min = 0$ and $x\_\max = \infty$, so here is an example of some generated values: ``` set.seed(1); VALUES <- rtruncnorm(100, mean = 40, sd = 150, xmin = 0); VALUES; [1] 60.947620 85.841377 137.204732 278.994441 46.359263 271.360050 314.793282 163.444809 153.594112 14.403486 [11] 47.336980 40.640677 172.019700 88.705945 202.535673 116.956365 182.604309 427.443068 87.731151 205.683304 [21] 303.456097 48.742383 160.555002 29.026587 61.341039 89.188375 3.148357 88.294612 251.922414 78.320798 [31] 112.930065 144.830053 115.879226 42.838959 228.478780 165.909662 212.907688 25.004323 184.797715 95.271195 [41] 225.300966 159.110693 208.001017 131.706871 125.391533 210.766031 5.475137 111.690569 187.948715 173.943869 [51] 111.789944 246.811168 101.857892 56.198740 16.454187 23.064491 72.686603 122.442020 163.830618 94.190402 [61] 282.852262 67.424081 107.090779 76.453855 160.302723 59.227644 112.026195 201.098166 19.574651 255.456402 [71] 78.020904 234.685219 79.811798 76.777400 111.466500 266.837916 248.669289 90.119810 205.631169 337.054094 [81] 101.007310 180.790027 92.533455 74.805628 197.410947 46.589354 180.298258 28.145057 56.356945 33.072365 [91] 55.016521 13.744835 157.628333 256.063229 206.300052 214.271779 106.138756 94.981436 220.480028 146.394828 ``` Note that when you lower-truncate so close to the mean, this means that the actual mean and standard deviation of the truncated distribution are substantially different to the pre-truncation parameter values. If you want your post-truncation mean and standard deviation to be equal to your specified parameters, you would need to change the pre-truncation values of $\mu$ and $\sigma$.
479,205
I am working on a project where I need to generate random numbers for a given task time which is normally distributed with mean = 40, and standard deviation = 150. Because of the high SD, I will get some negative values and low values when I generated numbers directly which is unrealistic. Is there any way where I can generate random numbers normally distributed with limitations (i.e. bounds)?
2020/07/27
[ "https://stats.stackexchange.com/questions/479205", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/292467/" ]
This sounds like you want to sample from [truncated normal distribution](https://en.wikipedia.org/wiki/Truncated_normal_distribution). If you only want to truncate the tails of the distribution (regions with low probability), than the approach suggested by *Dave* is probably enough. In other cases it might however quickly get inefficient. Better approach was suggested by Christian P. Robert in > > Robert, C.P. (1995). [Simulation of truncated normal variables.](http://arxiv.org/abs/0907.4010) > *Statistics and Computing 5*(2): 121-125. > > > The algorithm is a bit more complicated, so I suggest you check the paper. Alternatively, if you prefer the code [here you can find a C++ implementation](https://github.com/twolodzko/extraDistr/blob/master/src/truncated-normal-distribution.cpp#L109) from R package [extraDistr](https://github.com/twolodzko/extraDistr) (disclaimer: it's written by me).
While your question is not entirely clear about what you are trying to achieve (*how* do you wish to go from a Gaussian distribution to a distribution that is truncated at 0?)... ... I thought that it was interesting to show something about the limit of the ratio between the mean and standard deviation of a Gaussian distribution that is truncated at $x=0$. (this issue has been mentioned in some of the comments) --- Below is a piece of code and a graph that shows the computation of Gaussian distributions that have been truncated at different z-values (and shifted and re-scaled appropriately in order to have the truncating occur at $x=0$ and have the population mean equal to $\bar{x} = 40$). What we can notice is that by changing the point where we truncate the distribution we can shift from a curve that looks like a Gaussian distribution (when we cut at a low z-value) to a curve that approaches an exponential distribution (when we cut at a high z-value and only have the right tail, which approximates an exponential function). From this display I guess, intuitively, that the ratio of the standard deviation and the mean for this truncated distribution, is not able to become larger than this ratio for an exponential distribution (for an exponential distribution this ratio is 1). **Therefore: By truncating a normal distribution such that no negative values appear, we can *not* get a distribution whose standard deviation is larger than it's mean.** (and you are looking for sd = 150 and mean = 40, which means that truncating a normal distribution won't be able to do it) [![example of different ways to truncate](https://i.stack.imgur.com/QWzyM.png)](https://i.stack.imgur.com/QWzyM.png) ```r library(truncnorm) x = seq(-10^3,10^3,0.1) ### empty canvas/plot plot(-100,-100, ylim = c(0,0.025), xlim = c(0,200), xlab = "x", ylab = "density") d = 20 ### number of curves i = 0 ### counter used in for-loop varst = rep(0,d-1) for (trunc in qnorm(seq(1/d,1-1/d,1/d))) { ### compute truncated standard normal ### and it's mean and variance y <- dtruncnorm(x, mean = 0, sd = 1, a = trunc) mean = dnorm(trunc)/(1-pnorm(trunc)) var = (1+trunc*dnorm(trunc)/(1-pnorm(trunc)) - mean^2) ### transform such that the mean is equal to 40 xtrans <- (x-trunc)*40/(mean-trunc) ytrans <- y/(40/(mean-trunc)) ### storing variance of transformed trucated standard normal (multipliying with square of scalefactor) varst[i+1] = var*(40/(mean-trunc))^2 ### plot lines(xtrans[xtrans>=0],ytrans[xtrans>=0], col = hsv(0.15+i/2/d,1-i/2/d,1-(d-i)/4/d,1)) i = i+1 } ### exponential distribution lines(x[x>=0],dexp(x,rate=1/40)[x>=0], lty = 2) i = 1:(d-1) legend(200,0.025,xjust = 1, cex = 0.7, legend = c("exponential distribution", "normal distribution cut at 5%", "normal distribution cut at 95%"), lty = c(2,1,1), col = c(1, hsv(0.15+i/2/d,1-i/2/d,1-(d-i)/4/d,1)[c(1,d-1)])) ``` For the equations used to compute the mean and variance of the truncated normal distribution see: <https://en.wikipedia.org/wiki/Truncated_normal_distribution>
479,205
I am working on a project where I need to generate random numbers for a given task time which is normally distributed with mean = 40, and standard deviation = 150. Because of the high SD, I will get some negative values and low values when I generated numbers directly which is unrealistic. Is there any way where I can generate random numbers normally distributed with limitations (i.e. bounds)?
2020/07/27
[ "https://stats.stackexchange.com/questions/479205", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/292467/" ]
Whilst it is certainly quite simple to generate from a truncated normal distribution, if it is unrealistic to have negative values, you should rethink whether this distribution is appropriate. In the present case the lower-bound for the truncation occurs very close to the mean, and so the resulting distribution does not look much like a normal distribution. In any case, in the answer below I show how you can generate values from a truncated normal distribution. --- A simple and efficient method to generate random variables from truncated distributions (without discarding generated values) is to generate uniform random variables over the appropriate quantile range, and then use inverse transformation sampling to get the truncated random variables you want. To generate truncated normal random variables with minimum value $x\_\min$ and maximum value $x\_max$, we first compute the bounds for the quantile: $$u\_\min \equiv \Phi^{-1} \bigg( \frac{x\_\min-\mu}{\sigma} \bigg) \quad \quad \quad u\_\max \equiv \Phi^{-1} \bigg( \frac{x\_\max-\mu}{\sigma} \bigg).$$ We generate the random quantiles $U\_1,...,U\_n \sim \text{IID U}(u\_\min, u\_max)$ and we then compute the variables: $$X\_i = \Phi \Big( (\mu + U\_i) \sigma \Big).$$ The resulting values $X\_1,...,X\_n \sim \text{IID TruncN}(\mu, \sigma, x\_\min, x\_max)$ are lower-truncated normal random variables. Here is a function in `R` to generate these values. ``` #Function to generate IID values from truncated normal distribution rtruncnorm <- function (n, mean = 0, sd = 1, xmin = -Inf, xmax = Inf) { #Check inputs if (!is.numeric(xmin)) { stop('Error: xmin must be numeric') } if (!is.vector(xmin)) { stop('Error: xmin must be a single number') } if (length(xmin) != 1) { stop('Error: xmin must be a single number') } if (!is.numeric(xmax)) { stop('Error: xmax must be numeric') } if (!is.vector(xmax)) { stop('Error: xmax must be a single number') } if (length(xmax) != 1) { stop('Error: xmax must be a single number') } if (xmin > xmax) { stop('Error: xmin cannot be larger than xmax') } #Generate random quantiles UMIN <- pnorm(xmin, mean = mean, sd = sd); UMAX <- pnorm(xmax, mean = mean, sd = sd); RAND <- runif(n = n, min = UMIN, max = UMAX); #Compute output variables OUT <- qnorm(RAND, mean = mean, sd = sd, log = FALSE); OUT; } ``` In your problem you have paramaters $\mu = 40$, $\sigma = 150$, $x\_\min = 0$ and $x\_\max = \infty$, so here is an example of some generated values: ``` set.seed(1); VALUES <- rtruncnorm(100, mean = 40, sd = 150, xmin = 0); VALUES; [1] 60.947620 85.841377 137.204732 278.994441 46.359263 271.360050 314.793282 163.444809 153.594112 14.403486 [11] 47.336980 40.640677 172.019700 88.705945 202.535673 116.956365 182.604309 427.443068 87.731151 205.683304 [21] 303.456097 48.742383 160.555002 29.026587 61.341039 89.188375 3.148357 88.294612 251.922414 78.320798 [31] 112.930065 144.830053 115.879226 42.838959 228.478780 165.909662 212.907688 25.004323 184.797715 95.271195 [41] 225.300966 159.110693 208.001017 131.706871 125.391533 210.766031 5.475137 111.690569 187.948715 173.943869 [51] 111.789944 246.811168 101.857892 56.198740 16.454187 23.064491 72.686603 122.442020 163.830618 94.190402 [61] 282.852262 67.424081 107.090779 76.453855 160.302723 59.227644 112.026195 201.098166 19.574651 255.456402 [71] 78.020904 234.685219 79.811798 76.777400 111.466500 266.837916 248.669289 90.119810 205.631169 337.054094 [81] 101.007310 180.790027 92.533455 74.805628 197.410947 46.589354 180.298258 28.145057 56.356945 33.072365 [91] 55.016521 13.744835 157.628333 256.063229 206.300052 214.271779 106.138756 94.981436 220.480028 146.394828 ``` Note that when you lower-truncate so close to the mean, this means that the actual mean and standard deviation of the truncated distribution are substantially different to the pre-truncation parameter values. If you want your post-truncation mean and standard deviation to be equal to your specified parameters, you would need to change the pre-truncation values of $\mu$ and $\sigma$.
While your question is not entirely clear about what you are trying to achieve (*how* do you wish to go from a Gaussian distribution to a distribution that is truncated at 0?)... ... I thought that it was interesting to show something about the limit of the ratio between the mean and standard deviation of a Gaussian distribution that is truncated at $x=0$. (this issue has been mentioned in some of the comments) --- Below is a piece of code and a graph that shows the computation of Gaussian distributions that have been truncated at different z-values (and shifted and re-scaled appropriately in order to have the truncating occur at $x=0$ and have the population mean equal to $\bar{x} = 40$). What we can notice is that by changing the point where we truncate the distribution we can shift from a curve that looks like a Gaussian distribution (when we cut at a low z-value) to a curve that approaches an exponential distribution (when we cut at a high z-value and only have the right tail, which approximates an exponential function). From this display I guess, intuitively, that the ratio of the standard deviation and the mean for this truncated distribution, is not able to become larger than this ratio for an exponential distribution (for an exponential distribution this ratio is 1). **Therefore: By truncating a normal distribution such that no negative values appear, we can *not* get a distribution whose standard deviation is larger than it's mean.** (and you are looking for sd = 150 and mean = 40, which means that truncating a normal distribution won't be able to do it) [![example of different ways to truncate](https://i.stack.imgur.com/QWzyM.png)](https://i.stack.imgur.com/QWzyM.png) ```r library(truncnorm) x = seq(-10^3,10^3,0.1) ### empty canvas/plot plot(-100,-100, ylim = c(0,0.025), xlim = c(0,200), xlab = "x", ylab = "density") d = 20 ### number of curves i = 0 ### counter used in for-loop varst = rep(0,d-1) for (trunc in qnorm(seq(1/d,1-1/d,1/d))) { ### compute truncated standard normal ### and it's mean and variance y <- dtruncnorm(x, mean = 0, sd = 1, a = trunc) mean = dnorm(trunc)/(1-pnorm(trunc)) var = (1+trunc*dnorm(trunc)/(1-pnorm(trunc)) - mean^2) ### transform such that the mean is equal to 40 xtrans <- (x-trunc)*40/(mean-trunc) ytrans <- y/(40/(mean-trunc)) ### storing variance of transformed trucated standard normal (multipliying with square of scalefactor) varst[i+1] = var*(40/(mean-trunc))^2 ### plot lines(xtrans[xtrans>=0],ytrans[xtrans>=0], col = hsv(0.15+i/2/d,1-i/2/d,1-(d-i)/4/d,1)) i = i+1 } ### exponential distribution lines(x[x>=0],dexp(x,rate=1/40)[x>=0], lty = 2) i = 1:(d-1) legend(200,0.025,xjust = 1, cex = 0.7, legend = c("exponential distribution", "normal distribution cut at 5%", "normal distribution cut at 95%"), lty = c(2,1,1), col = c(1, hsv(0.15+i/2/d,1-i/2/d,1-(d-i)/4/d,1)[c(1,d-1)])) ``` For the equations used to compute the mean and variance of the truncated normal distribution see: <https://en.wikipedia.org/wiki/Truncated_normal_distribution>
114,120
Using GIMP I masked out an unwanted person who was situated in the background of my image. This person was partially concealed by my subject. I used the path tool to trace the outlines of my subject and then masked out the backgound using clone and heal. My problem is that this left very sharp borders on some out-of-focus parts of my subject, wich I would like to blur. My best guess was using the 'paint along path' option while using the blur tool, but this got me insufficient results as the background got blurred without much colour of my subject bleeding into it. I still have all paths used to mask out the background so using these might be a good way to minimise effort. Maybe someobody can suggest different settings on the blur tool or a method using a gradient along a path? Ive also tried doing it manually but this takes a lot of time and it would be very practical to know a better way of doing this in the future. [![Image with unwanted, sharp borders](https://i.stack.imgur.com/wuKSk.png)](https://i.stack.imgur.com/wuKSk.png) This is how the border of the subjects arm looks after the masking of the background [![Manual edit of border above watch](https://i.stack.imgur.com/PQpuG.jpg)](https://i.stack.imgur.com/PQpuG.jpg) And this is how I would like it to look, I did this manually with the stamp tool.
2020/01/15
[ "https://photo.stackexchange.com/questions/114120", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/88987/" ]
> > I wonder, what algorithms are used to achieve such conversion of colorful noise to colorless one? Is it some high-ISO-optimized demosaicing? Or is it a special denoising algorithm applied after demosaicing? Or something else? > > > **Yes.** There are different algorithms that can be applied at various stages of processing. You can look at a raw processing application, such as Raw Therapee, to see what methods are available. Some demosaicing methods are designed to reduce color noise and artifacts. Other noise reduction occurs after demosaicing. What a particular camera or phone uses depends on what the developers decide to implement. If you need to reduce chroma noise in an existing image, a simple way to do so is to blur only the chroma channels.
The most common form of noise is called "fixed-pattern". This is a static like function that occurs when the camera logic turns up the amplification applied to the imaging chip. Their is an amplifier in each light sensitive photosite. Each will have a slightly different efficiency. When the amplification is turned up too high, to gain sensitivity so the camera operates in feeble light, some photosites that should image as white, display some gray or false color. Some that should image as black, display as dark gray or false color. Software can be written to identity these noise induced defects. Thus a correction can be applied to mitigate.
114,120
Using GIMP I masked out an unwanted person who was situated in the background of my image. This person was partially concealed by my subject. I used the path tool to trace the outlines of my subject and then masked out the backgound using clone and heal. My problem is that this left very sharp borders on some out-of-focus parts of my subject, wich I would like to blur. My best guess was using the 'paint along path' option while using the blur tool, but this got me insufficient results as the background got blurred without much colour of my subject bleeding into it. I still have all paths used to mask out the background so using these might be a good way to minimise effort. Maybe someobody can suggest different settings on the blur tool or a method using a gradient along a path? Ive also tried doing it manually but this takes a lot of time and it would be very practical to know a better way of doing this in the future. [![Image with unwanted, sharp borders](https://i.stack.imgur.com/wuKSk.png)](https://i.stack.imgur.com/wuKSk.png) This is how the border of the subjects arm looks after the masking of the background [![Manual edit of border above watch](https://i.stack.imgur.com/PQpuG.jpg)](https://i.stack.imgur.com/PQpuG.jpg) And this is how I would like it to look, I did this manually with the stamp tool.
2020/01/15
[ "https://photo.stackexchange.com/questions/114120", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/88987/" ]
> > I wonder, what algorithms are used to achieve such conversion of colorful noise to colorless one? Is it some high-ISO-optimized demosaicing? Or is it a special denoising algorithm applied after demosaicing? Or something else? > > > **Yes.** There are different algorithms that can be applied at various stages of processing. You can look at a raw processing application, such as Raw Therapee, to see what methods are available. Some demosaicing methods are designed to reduce color noise and artifacts. Other noise reduction occurs after demosaicing. What a particular camera or phone uses depends on what the developers decide to implement. If you need to reduce chroma noise in an existing image, a simple way to do so is to blur only the chroma channels.
There are many algorithms, for instance the Selective Blur in Gimp: > > The Selective Gaussian Blur plug-in doesn't act on all pixels: blur is applied only if the difference between its value and the value of the surrounding pixels is less than a defined Delta value. So, contrasts are preserved because difference is high on contrast limits. > > > Working on your raw image: [![enter image description here](https://i.stack.imgur.com/G0HGl.png)](https://i.stack.imgur.com/G0HGl.png)
27,431,195
I am using SQL Server 2008 BIDS. I am trying to read in an Excel file, having multiple sheets. The names are mostly alphabetical( and few with special char '&'). The data starts at row 8. I have skipped the blank rows by setting the rows and columns in the open rowset property for the Excel source. I get the exact mappings. However, I am not able to preview the data. The package runs successfully(everything turns green), but there is no data in my destination. The error I receive while I try to preview is: > > There was an error displaying the preview. > > > Additional Information: > > > Index and Length must refer to a location within the string. Parameter > name: Length(mscorlib) > > > Please let me know if I am doing anything wrong or I am missing any settings. The links I have referred to: [Skipping rows when importing Excel into SQL using SSIS 2008](https://stackoverflow.com/questions/2417724/skipping-rows-when-importing-excel-into-sql-using-ssis-2008) <https://connect.microsoft.com/SQLServer/feedback/details/557049/ssis-fails-to-preview-excel-source-connector-due-to-incompatible-sheet-name> Thanks
2014/12/11
[ "https://Stackoverflow.com/questions/27431195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760136/" ]
I cracked it with the help of one of my friend . > > In the properties of the Excel Source >> Custom Properties >> Open Rowset >> > **SheetName$A12:J** > > > It means skip the rows till A12. And the data is taken into account from A12 though end of J column. Problem solved.
The way to solve this is to use q SQL command in the data access mode. ``` Select * FROM [Sheet1$A20:K] ``` This will read the data correctly and no preview errors will occur.
27,431,195
I am using SQL Server 2008 BIDS. I am trying to read in an Excel file, having multiple sheets. The names are mostly alphabetical( and few with special char '&'). The data starts at row 8. I have skipped the blank rows by setting the rows and columns in the open rowset property for the Excel source. I get the exact mappings. However, I am not able to preview the data. The package runs successfully(everything turns green), but there is no data in my destination. The error I receive while I try to preview is: > > There was an error displaying the preview. > > > Additional Information: > > > Index and Length must refer to a location within the string. Parameter > name: Length(mscorlib) > > > Please let me know if I am doing anything wrong or I am missing any settings. The links I have referred to: [Skipping rows when importing Excel into SQL using SSIS 2008](https://stackoverflow.com/questions/2417724/skipping-rows-when-importing-excel-into-sql-using-ssis-2008) <https://connect.microsoft.com/SQLServer/feedback/details/557049/ssis-fails-to-preview-excel-source-connector-due-to-incompatible-sheet-name> Thanks
2014/12/11
[ "https://Stackoverflow.com/questions/27431195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760136/" ]
I cracked it with the help of one of my friend . > > In the properties of the Excel Source >> Custom Properties >> Open Rowset >> > **SheetName$A12:J** > > > It means skip the rows till A12. And the data is taken into account from A12 though end of J column. Problem solved.
I was getting this same error trying to import a .xlsx file into SSIS 2008. I first saved the file as .xls (Excel 97-2003). I was still getting the above error and couldn't preview the data with the new file. In case this link breaks in the future: <https://connect.microsoft.com/SQLServer/feedback/details/557049/ssis-fails-to-preview-excel-source-connector-due-to-incompatible-sheet-name> Once I removed the space from the Sheet name, I was able to preview the data. The tab was originally called Time Data; I changed it to TimeData. Some other potential problems with the sheet name, according to the above site: * Sheets named with all numbers (ex: 4385) * Sheet names beginning with a number
27,431,195
I am using SQL Server 2008 BIDS. I am trying to read in an Excel file, having multiple sheets. The names are mostly alphabetical( and few with special char '&'). The data starts at row 8. I have skipped the blank rows by setting the rows and columns in the open rowset property for the Excel source. I get the exact mappings. However, I am not able to preview the data. The package runs successfully(everything turns green), but there is no data in my destination. The error I receive while I try to preview is: > > There was an error displaying the preview. > > > Additional Information: > > > Index and Length must refer to a location within the string. Parameter > name: Length(mscorlib) > > > Please let me know if I am doing anything wrong or I am missing any settings. The links I have referred to: [Skipping rows when importing Excel into SQL using SSIS 2008](https://stackoverflow.com/questions/2417724/skipping-rows-when-importing-excel-into-sql-using-ssis-2008) <https://connect.microsoft.com/SQLServer/feedback/details/557049/ssis-fails-to-preview-excel-source-connector-due-to-incompatible-sheet-name> Thanks
2014/12/11
[ "https://Stackoverflow.com/questions/27431195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760136/" ]
I cracked it with the help of one of my friend . > > In the properties of the Excel Source >> Custom Properties >> Open Rowset >> > **SheetName$A12:J** > > > It means skip the rows till A12. And the data is taken into account from A12 though end of J column. Problem solved.
In my case I was trying to export from SQL into an Excel file and receiving "Index and Length must refer to a location within the string" while trying to preview the destination data. Removing the space from the Excel Sheet in the Excel Destination Editor fixed it for me.
27,431,195
I am using SQL Server 2008 BIDS. I am trying to read in an Excel file, having multiple sheets. The names are mostly alphabetical( and few with special char '&'). The data starts at row 8. I have skipped the blank rows by setting the rows and columns in the open rowset property for the Excel source. I get the exact mappings. However, I am not able to preview the data. The package runs successfully(everything turns green), but there is no data in my destination. The error I receive while I try to preview is: > > There was an error displaying the preview. > > > Additional Information: > > > Index and Length must refer to a location within the string. Parameter > name: Length(mscorlib) > > > Please let me know if I am doing anything wrong or I am missing any settings. The links I have referred to: [Skipping rows when importing Excel into SQL using SSIS 2008](https://stackoverflow.com/questions/2417724/skipping-rows-when-importing-excel-into-sql-using-ssis-2008) <https://connect.microsoft.com/SQLServer/feedback/details/557049/ssis-fails-to-preview-excel-source-connector-due-to-incompatible-sheet-name> Thanks
2014/12/11
[ "https://Stackoverflow.com/questions/27431195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760136/" ]
I cracked it with the help of one of my friend . > > In the properties of the Excel Source >> Custom Properties >> Open Rowset >> > **SheetName$A12:J** > > > It means skip the rows till A12. And the data is taken into account from A12 though end of J column. Problem solved.
After trying all the other answers with no luck, I renamed the spreadsheet. In the Excel connection manager, I browsed to the renamed spreadsheet and unchecked first row contains column names. I was then able to view the data in the preview window.
27,431,195
I am using SQL Server 2008 BIDS. I am trying to read in an Excel file, having multiple sheets. The names are mostly alphabetical( and few with special char '&'). The data starts at row 8. I have skipped the blank rows by setting the rows and columns in the open rowset property for the Excel source. I get the exact mappings. However, I am not able to preview the data. The package runs successfully(everything turns green), but there is no data in my destination. The error I receive while I try to preview is: > > There was an error displaying the preview. > > > Additional Information: > > > Index and Length must refer to a location within the string. Parameter > name: Length(mscorlib) > > > Please let me know if I am doing anything wrong or I am missing any settings. The links I have referred to: [Skipping rows when importing Excel into SQL using SSIS 2008](https://stackoverflow.com/questions/2417724/skipping-rows-when-importing-excel-into-sql-using-ssis-2008) <https://connect.microsoft.com/SQLServer/feedback/details/557049/ssis-fails-to-preview-excel-source-connector-due-to-incompatible-sheet-name> Thanks
2014/12/11
[ "https://Stackoverflow.com/questions/27431195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760136/" ]
The way to solve this is to use q SQL command in the data access mode. ``` Select * FROM [Sheet1$A20:K] ``` This will read the data correctly and no preview errors will occur.
I was getting this same error trying to import a .xlsx file into SSIS 2008. I first saved the file as .xls (Excel 97-2003). I was still getting the above error and couldn't preview the data with the new file. In case this link breaks in the future: <https://connect.microsoft.com/SQLServer/feedback/details/557049/ssis-fails-to-preview-excel-source-connector-due-to-incompatible-sheet-name> Once I removed the space from the Sheet name, I was able to preview the data. The tab was originally called Time Data; I changed it to TimeData. Some other potential problems with the sheet name, according to the above site: * Sheets named with all numbers (ex: 4385) * Sheet names beginning with a number
27,431,195
I am using SQL Server 2008 BIDS. I am trying to read in an Excel file, having multiple sheets. The names are mostly alphabetical( and few with special char '&'). The data starts at row 8. I have skipped the blank rows by setting the rows and columns in the open rowset property for the Excel source. I get the exact mappings. However, I am not able to preview the data. The package runs successfully(everything turns green), but there is no data in my destination. The error I receive while I try to preview is: > > There was an error displaying the preview. > > > Additional Information: > > > Index and Length must refer to a location within the string. Parameter > name: Length(mscorlib) > > > Please let me know if I am doing anything wrong or I am missing any settings. The links I have referred to: [Skipping rows when importing Excel into SQL using SSIS 2008](https://stackoverflow.com/questions/2417724/skipping-rows-when-importing-excel-into-sql-using-ssis-2008) <https://connect.microsoft.com/SQLServer/feedback/details/557049/ssis-fails-to-preview-excel-source-connector-due-to-incompatible-sheet-name> Thanks
2014/12/11
[ "https://Stackoverflow.com/questions/27431195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760136/" ]
The way to solve this is to use q SQL command in the data access mode. ``` Select * FROM [Sheet1$A20:K] ``` This will read the data correctly and no preview errors will occur.
In my case I was trying to export from SQL into an Excel file and receiving "Index and Length must refer to a location within the string" while trying to preview the destination data. Removing the space from the Excel Sheet in the Excel Destination Editor fixed it for me.
27,431,195
I am using SQL Server 2008 BIDS. I am trying to read in an Excel file, having multiple sheets. The names are mostly alphabetical( and few with special char '&'). The data starts at row 8. I have skipped the blank rows by setting the rows and columns in the open rowset property for the Excel source. I get the exact mappings. However, I am not able to preview the data. The package runs successfully(everything turns green), but there is no data in my destination. The error I receive while I try to preview is: > > There was an error displaying the preview. > > > Additional Information: > > > Index and Length must refer to a location within the string. Parameter > name: Length(mscorlib) > > > Please let me know if I am doing anything wrong or I am missing any settings. The links I have referred to: [Skipping rows when importing Excel into SQL using SSIS 2008](https://stackoverflow.com/questions/2417724/skipping-rows-when-importing-excel-into-sql-using-ssis-2008) <https://connect.microsoft.com/SQLServer/feedback/details/557049/ssis-fails-to-preview-excel-source-connector-due-to-incompatible-sheet-name> Thanks
2014/12/11
[ "https://Stackoverflow.com/questions/27431195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/760136/" ]
The way to solve this is to use q SQL command in the data access mode. ``` Select * FROM [Sheet1$A20:K] ``` This will read the data correctly and no preview errors will occur.
After trying all the other answers with no luck, I renamed the spreadsheet. In the Excel connection manager, I browsed to the renamed spreadsheet and unchecked first row contains column names. I was then able to view the data in the preview window.
7,116,040
This really bugs me - a lot. After wading through google maps v3 generated client side code in firebug, I'm about ready to drive down the street and give some of these engineers a piece of my mind... arrrgh :P The infowWindow class produces HTML that personally I would think is simply nuts. maybe someone can help me make sense of it. The infowWindow HTML structure is like this: ``` #map_canvas > div > div > div > div > div // 5 levels of elements, no big deal here, ok... > div // top left corner div // top right corner div // bottom left corner div // bottom right corner // now comes fun stuff for the speech bubble arrow: div div div div div div div div div div // the 10 divs above are stacked diagonally with odd sizes to make this arrow. i'm sorry but WHY?!? is it done like that? I suppose they wanted the user to be able to grab the map even right next to the arrow. Think about this: do users really need to be able to not grab the arrow? if grabbing the arrow causes map pan, as is the case for the shadow images, would that really be a problem? div // bottom middle for image background border or something div // top middle div // middle div // bottom middle, again div // entire block of the infoWindow, probably the container > img // close box div // center block with the contents of the infoWindow div // text content container ``` **WOW - thats nuts!** notice there is no real semantic structure, and - gosh, dare I have such an assumption - no class names anywhere, nothing. I figured maybe they have some kind of 9-slice box going on and then produce the arrow separately; I mean, the image sprite in iw3.png sure isn't going to be the problem here. I dearly hope someone who has an effect on this api comes across this and hopefully google will eventually find a way to solve this such that custom infoWindow visuals are as straightforward as markers. Thanks for tuning in! happy commenting. meanwhile I shall use a hack to get to these crazy divs and make them do my bidding. --- earlier I commented on some other post and I think it shouldn't be too much to ask for a method in the API that lets you use custom UI without resorting to a near-duplication of the whole window object as is currently necessary (see google extension classes v3). ``` google.maps.infoWindow.setStyle({ 'topleft' : { 'background' : 'url(images/windowsprite.png) 0 0 no-repeat', 'width' : '10px', 'height' : '10px' }, 'topRight' : { ...etc... } ...etc... }) ```
2011/08/19
[ "https://Stackoverflow.com/questions/7116040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/836028/" ]
Have you tried InfoBox? <http://googlegeodevelopers.blogspot.com/2010/04/infobox-10-highly-customizable.html> or InfoBubble? <http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/examples/example.html/> They both give you a bit more control over the appearance of infowindows, while still abstracting some of the complicated parts. The lack of classes on elements is a (good) design decision for an API. It eliminates the potential for clashes with user defined classes.
You try styling with CSS? The below example shows this. This is the most straight forward way to change the UI. <http://code.google.com/apis/maps/documentation/javascript/overlays.html#InfoWindows>
7,116,040
This really bugs me - a lot. After wading through google maps v3 generated client side code in firebug, I'm about ready to drive down the street and give some of these engineers a piece of my mind... arrrgh :P The infowWindow class produces HTML that personally I would think is simply nuts. maybe someone can help me make sense of it. The infowWindow HTML structure is like this: ``` #map_canvas > div > div > div > div > div // 5 levels of elements, no big deal here, ok... > div // top left corner div // top right corner div // bottom left corner div // bottom right corner // now comes fun stuff for the speech bubble arrow: div div div div div div div div div div // the 10 divs above are stacked diagonally with odd sizes to make this arrow. i'm sorry but WHY?!? is it done like that? I suppose they wanted the user to be able to grab the map even right next to the arrow. Think about this: do users really need to be able to not grab the arrow? if grabbing the arrow causes map pan, as is the case for the shadow images, would that really be a problem? div // bottom middle for image background border or something div // top middle div // middle div // bottom middle, again div // entire block of the infoWindow, probably the container > img // close box div // center block with the contents of the infoWindow div // text content container ``` **WOW - thats nuts!** notice there is no real semantic structure, and - gosh, dare I have such an assumption - no class names anywhere, nothing. I figured maybe they have some kind of 9-slice box going on and then produce the arrow separately; I mean, the image sprite in iw3.png sure isn't going to be the problem here. I dearly hope someone who has an effect on this api comes across this and hopefully google will eventually find a way to solve this such that custom infoWindow visuals are as straightforward as markers. Thanks for tuning in! happy commenting. meanwhile I shall use a hack to get to these crazy divs and make them do my bidding. --- earlier I commented on some other post and I think it shouldn't be too much to ask for a method in the API that lets you use custom UI without resorting to a near-duplication of the whole window object as is currently necessary (see google extension classes v3). ``` google.maps.infoWindow.setStyle({ 'topleft' : { 'background' : 'url(images/windowsprite.png) 0 0 no-repeat', 'width' : '10px', 'height' : '10px' }, 'topRight' : { ...etc... } ...etc... }) ```
2011/08/19
[ "https://Stackoverflow.com/questions/7116040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/836028/" ]
After much trial and eror I decided the best way to resolve this is to use OverlayView class and simply custom build a container. Well, "simply" is an understatement, but it works. And now I have full control over layout and functionality.
You try styling with CSS? The below example shows this. This is the most straight forward way to change the UI. <http://code.google.com/apis/maps/documentation/javascript/overlays.html#InfoWindows>
21,248,263
I have the following two XPath selectors working individually, but am unable to combine them to return the same element as a result: ``` //*[@customAttribute="banana"]//*[contains(@style,'width:100px')] //*[@customAttribute="banana"]//*[contains(label,'Name')] ``` The source around the element being targeted is as such: ``` <label id="randomID_1234" for="randomID_1234" class="class1 class2 class3" style="width:100px;margin-right:5px;" unselectable="on"> Name </label> ``` Why not just return the element by label name? I must assert that the element is conforming to a certain style also. Is this possible to do with a one-liner?
2014/01/21
[ "https://Stackoverflow.com/questions/21248263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1668057/" ]
This one should do the trick: ``` //*[@customAttribute="banana"]//*[contains(label,'Name')][contains(@style,'width:100px')] ```
This ended up doing the trick: ``` (//*[@customAttribute="banana"]//*[contains(label,'Name')])//*[contains(@style,'width:100px')] ```
28,412,559
I have the following problem: I have set up that the branch I currently reside in, is shown in my command prompt like this: **"[Current\_working\_dir] (master)"** however every time I switch branch I get the following error and the branch isn't refreshed: ``` [work_environment] (master) git checkout test M bash/bashrc Switched to branch 'test' [work_environment] (master) ``` My .bashrc looks like the following: ``` export PATH="$HOME/.rbenv/bin:$PATH" eval "$(rbenv init -)" export PATH="$HOME/.rbenv/bin:$PATH" eval "$(rbenv init -)" export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH" # Bash git completion source /etc/bash_completion.d/git-prompt #Colored command prompt + minimum view export PS1="\[\e[0;34m\][\[\e[1;34m\]\W\\[\e[0;34m\]]\[\e[0m\]\[\e[0;32m\]$(__git_ps1)\[\e[0m\] " ``` could anyone enlighten me about what i'm doing wrong? I cannot seem to find anything regarding this error
2015/02/09
[ "https://Stackoverflow.com/questions/28412559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1213904/" ]
Your problem is the double quotes on this line: ``` export PS1="\[\e[0;34m\][\[\e[1;34m\]\W\\[\e[0;34m\]]\[\e[0m\]\[\e[0;32m\]$(__git_ps1)\[\e[0m\] " ``` That line is being evaluated *immediately* and `__git_ps1` is being called only once. Try `echo "$PS1"` to see what I mean. You want single quotes there. The value of `PS1` is evaluated before it is used so the function will get called correctly at that point (and see the current branch/etc.). ``` export PS1='\[\e[0;34m\][\[\e[1;34m\]\W\\[\e[0;34m\]]\[\e[0m\]\[\e[0;32m\]$(__git_ps1)\[\e[0m\] ' ```
Use single quotes around your PS1 declaration rather than double quotes. At the moment the variables are evaluated and then set to PS1. You want them to be evaluated everytime PS1 is used.
26,995,762
I am trying use gtest with ndk, the ndk-build finds the dependences, but I have a sintax error on internal gtest file gtest-printers.h ``` external/gtest/include/gtest/gtest-printers.h:170:9: error: ambiguous overload for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char, std::char_traits<char> >}' and 'const BiggestInt {aka const long long int}') *os << kBigInt; ^ ``` follows my Android.mk ``` LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := my_module GTEST_DIR := $(LOCAL_PATH)/../../external/gtest LOCAL_CPP_EXTENSION := .cxx .cpp .cc LOCAL_CFLAGS := -D_STLP_USE_NEWALLOC LOCAL_CPPFLAGS += -std=c++11 LOCAL_SRC_FILES := \ ... LOCAL_C_INCLUDES := \ ... LOCAL_C_INCLUDES += ${NDK_ROOT}/sources/cxx-stl/stlport/stlport LOCAL_C_INCLUDES += ${GTEST_DIR}/include LOCAL_LDLIBS += -llog LOCAL_LDLIBS += -landroid LOCAL_LDLIBS += -lstdc++ LOCAL_STATIC_LIBRARIES := $(GTEST_DIR)/lib/libgtest.a include $(BUILD_EXECUTABLE) ```
2014/11/18
[ "https://Stackoverflow.com/questions/26995762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2999490/" ]
My problem was try to call static gtest lib directly, instead of, I had to do it before: ``` include $(CLEAR_VARS) GTEST_DIR := ${NDK_ROOT}/sources/third_party/googletest/googletest LOCAL_MODULE := gtest # flag for c++11 LOCAL_CPPFLAGS += -std=c++11 LOCAL_C_INCLUDES += ${NDK_ROOT}/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi/include LOCAL_C_INCLUDES += ${NDK_ROOT}/sources/cxx-stl/gnu-libstdc++/4.9/include/ LOCAL_C_INCLUDES += ${GTEST_DIR}/include/ LOCAL_C_INCLUDES += ${GTEST_DIR}/ LOCAL_SRC_FILES := ${GTEST_DIR}/src/gtest-all.cc \ ${GTEST_DIR}/src/gtest.cc \ ${GTEST_DIR}/src/gtest-death-test.cc \ ${GTEST_DIR}/src/gtest-filepath.cc \ ${GTEST_DIR}/src/gtest_main.cc \ ${GTEST_DIR}/src/gtest-port.cc \ ${GTEST_DIR}/src/gtest-printers.cc \ ${GTEST_DIR}/src/gtest-test-part.cc \ ${GTEST_DIR}/src/gtest-typed-test.cc LOCAL_STATIC_LIBRARIES += ${NDK_ROOT}/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi/thumb/libgnustl_static.a include $(BUILD_STATIC_LIBRARY) ```
It looks like C++11 + stlport is the bad combination for gtest. This isn't terribly surprising, given that stlport doesn't actually have any support for C++11 (some parts of it will work, others apparently won't). If this only causes problems when *building* gtest, you could just not use C++11 when building gtest, but still for your code. If you can't use it from C++11 either, you're probably out of luck for now (there should be a better option available as soon as I find time).
26,995,762
I am trying use gtest with ndk, the ndk-build finds the dependences, but I have a sintax error on internal gtest file gtest-printers.h ``` external/gtest/include/gtest/gtest-printers.h:170:9: error: ambiguous overload for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char, std::char_traits<char> >}' and 'const BiggestInt {aka const long long int}') *os << kBigInt; ^ ``` follows my Android.mk ``` LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := my_module GTEST_DIR := $(LOCAL_PATH)/../../external/gtest LOCAL_CPP_EXTENSION := .cxx .cpp .cc LOCAL_CFLAGS := -D_STLP_USE_NEWALLOC LOCAL_CPPFLAGS += -std=c++11 LOCAL_SRC_FILES := \ ... LOCAL_C_INCLUDES := \ ... LOCAL_C_INCLUDES += ${NDK_ROOT}/sources/cxx-stl/stlport/stlport LOCAL_C_INCLUDES += ${GTEST_DIR}/include LOCAL_LDLIBS += -llog LOCAL_LDLIBS += -landroid LOCAL_LDLIBS += -lstdc++ LOCAL_STATIC_LIBRARIES := $(GTEST_DIR)/lib/libgtest.a include $(BUILD_EXECUTABLE) ```
2014/11/18
[ "https://Stackoverflow.com/questions/26995762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2999490/" ]
We have encountered the same issue, and working solution was to use: ``` LOCAL_CPPFLAGS += -std=gnu++11 ``` instead of `LOCAL_CPPFLAGS+=-std=c++11`. It must have set some different mappings of `long long int` in `stlport`.
It looks like C++11 + stlport is the bad combination for gtest. This isn't terribly surprising, given that stlport doesn't actually have any support for C++11 (some parts of it will work, others apparently won't). If this only causes problems when *building* gtest, you could just not use C++11 when building gtest, but still for your code. If you can't use it from C++11 either, you're probably out of luck for now (there should be a better option available as soon as I find time).
26,995,762
I am trying use gtest with ndk, the ndk-build finds the dependences, but I have a sintax error on internal gtest file gtest-printers.h ``` external/gtest/include/gtest/gtest-printers.h:170:9: error: ambiguous overload for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char, std::char_traits<char> >}' and 'const BiggestInt {aka const long long int}') *os << kBigInt; ^ ``` follows my Android.mk ``` LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := my_module GTEST_DIR := $(LOCAL_PATH)/../../external/gtest LOCAL_CPP_EXTENSION := .cxx .cpp .cc LOCAL_CFLAGS := -D_STLP_USE_NEWALLOC LOCAL_CPPFLAGS += -std=c++11 LOCAL_SRC_FILES := \ ... LOCAL_C_INCLUDES := \ ... LOCAL_C_INCLUDES += ${NDK_ROOT}/sources/cxx-stl/stlport/stlport LOCAL_C_INCLUDES += ${GTEST_DIR}/include LOCAL_LDLIBS += -llog LOCAL_LDLIBS += -landroid LOCAL_LDLIBS += -lstdc++ LOCAL_STATIC_LIBRARIES := $(GTEST_DIR)/lib/libgtest.a include $(BUILD_EXECUTABLE) ```
2014/11/18
[ "https://Stackoverflow.com/questions/26995762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2999490/" ]
My problem was try to call static gtest lib directly, instead of, I had to do it before: ``` include $(CLEAR_VARS) GTEST_DIR := ${NDK_ROOT}/sources/third_party/googletest/googletest LOCAL_MODULE := gtest # flag for c++11 LOCAL_CPPFLAGS += -std=c++11 LOCAL_C_INCLUDES += ${NDK_ROOT}/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi/include LOCAL_C_INCLUDES += ${NDK_ROOT}/sources/cxx-stl/gnu-libstdc++/4.9/include/ LOCAL_C_INCLUDES += ${GTEST_DIR}/include/ LOCAL_C_INCLUDES += ${GTEST_DIR}/ LOCAL_SRC_FILES := ${GTEST_DIR}/src/gtest-all.cc \ ${GTEST_DIR}/src/gtest.cc \ ${GTEST_DIR}/src/gtest-death-test.cc \ ${GTEST_DIR}/src/gtest-filepath.cc \ ${GTEST_DIR}/src/gtest_main.cc \ ${GTEST_DIR}/src/gtest-port.cc \ ${GTEST_DIR}/src/gtest-printers.cc \ ${GTEST_DIR}/src/gtest-test-part.cc \ ${GTEST_DIR}/src/gtest-typed-test.cc LOCAL_STATIC_LIBRARIES += ${NDK_ROOT}/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi/thumb/libgnustl_static.a include $(BUILD_STATIC_LIBRARY) ```
We have encountered the same issue, and working solution was to use: ``` LOCAL_CPPFLAGS += -std=gnu++11 ``` instead of `LOCAL_CPPFLAGS+=-std=c++11`. It must have set some different mappings of `long long int` in `stlport`.
43,616,399
I need some assistance from the database people here. I need to be able to store sports statistics for games that a sports player plays and then display that data sequentially in a timeline (sort of the player's sports career). A player can play one or more sports. Here are two schemas I came up with, but both have issues: **Idea #1:** Directly link each statistic to a player. [![enter image description here](https://i.stack.imgur.com/zYLhJ.jpg)](https://i.stack.imgur.com/zYLhJ.jpg) **Benefits to this idea:** It uses relational theory and properly links the tables with relationships. **Problems with this idea:** Seems like there could be some issues with working with data from a lot of different Statistics tables like this. --- **Idea #2:** Use an intermediary table to link the Player with their statistics. [![enter image description here](https://i.stack.imgur.com/YsWVL.jpg)](https://i.stack.imgur.com/YsWVL.jpg) **Benefits to this idea:** It would be very easy to query the PlayerStatistic table and get an ordered list of games that the player played. The sport for each row would be very easy to identify due to the table's name being in the row. **Problems with this idea:** no relationship can between the PlayerStatistic table and its child statistic tables (i.e. BaseballStatistic, FootballStatistic). This kind of throws relational theory out the window. --- Which idea would you use? Or is there an even better way to accomplish this goal? --- If it matters, I am using SQL Server 2014 --- Edit: this idea was suggested. What do you think? [![enter image description here](https://i.stack.imgur.com/14Eis.jpg)](https://i.stack.imgur.com/14Eis.jpg)
2017/04/25
[ "https://Stackoverflow.com/questions/43616399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7560542/" ]
You used regex atoms `\1` and `\2` (match what the first or second capture captured) outside of a regex pattern. You meant to use `$1` and `$2` (as you did in another spot). Further more, dollar signs inside double-quoted strings have meaning to your shell. It's best to use single quotes around your program[1]. ``` echo abcd | perl -pe's/(ab)(cd)?/defined($2)?$1.$2:""/e' ``` Simpler: ``` echo abcd | perl -pe's/(ab(cd)?)/defined($2)?$1:""/e' ``` Simpler: ``` echo abcd | perl -pe's/ab(?!cd)//' ``` --- 1. Either avoid single-quotes in your program[2], or use `'\''` to "escape" them. 2. You can usually use `q{}` instead of single-quotes. You can also switch to using double-quotes. Inside of double-quotes, you can use `\x27` for an apostrophe.
Why torture yourself, just use a branch reset. Find `(?|(abcd)|ab())` Replace `$1`
43,616,399
I need some assistance from the database people here. I need to be able to store sports statistics for games that a sports player plays and then display that data sequentially in a timeline (sort of the player's sports career). A player can play one or more sports. Here are two schemas I came up with, but both have issues: **Idea #1:** Directly link each statistic to a player. [![enter image description here](https://i.stack.imgur.com/zYLhJ.jpg)](https://i.stack.imgur.com/zYLhJ.jpg) **Benefits to this idea:** It uses relational theory and properly links the tables with relationships. **Problems with this idea:** Seems like there could be some issues with working with data from a lot of different Statistics tables like this. --- **Idea #2:** Use an intermediary table to link the Player with their statistics. [![enter image description here](https://i.stack.imgur.com/YsWVL.jpg)](https://i.stack.imgur.com/YsWVL.jpg) **Benefits to this idea:** It would be very easy to query the PlayerStatistic table and get an ordered list of games that the player played. The sport for each row would be very easy to identify due to the table's name being in the row. **Problems with this idea:** no relationship can between the PlayerStatistic table and its child statistic tables (i.e. BaseballStatistic, FootballStatistic). This kind of throws relational theory out the window. --- Which idea would you use? Or is there an even better way to accomplish this goal? --- If it matters, I am using SQL Server 2014 --- Edit: this idea was suggested. What do you think? [![enter image description here](https://i.stack.imgur.com/14Eis.jpg)](https://i.stack.imgur.com/14Eis.jpg)
2017/04/25
[ "https://Stackoverflow.com/questions/43616399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7560542/" ]
You used regex atoms `\1` and `\2` (match what the first or second capture captured) outside of a regex pattern. You meant to use `$1` and `$2` (as you did in another spot). Further more, dollar signs inside double-quoted strings have meaning to your shell. It's best to use single quotes around your program[1]. ``` echo abcd | perl -pe's/(ab)(cd)?/defined($2)?$1.$2:""/e' ``` Simpler: ``` echo abcd | perl -pe's/(ab(cd)?)/defined($2)?$1:""/e' ``` Simpler: ``` echo abcd | perl -pe's/ab(?!cd)//' ``` --- 1. Either avoid single-quotes in your program[2], or use `'\''` to "escape" them. 2. You can usually use `q{}` instead of single-quotes. You can also switch to using double-quotes. Inside of double-quotes, you can use `\x27` for an apostrophe.
And a couple of even better ways Find `abcd(*SKIP)(*FAIL)|ab` Replace `""` Find `(?:abcd)*\Kab` Replace `""` These use regex wisely. There is really no need nowadays to have to use the *eval* form of the regex substitution construct `s///e` in conjunction with defined(). This is especially true when using the perl command line. Good luck...
381,216
Does the functional spec help or hinder your expectations? Do programmers who practice the waterfall methodology, are they open to functional specs? I'm a web designer/developer working with a team of 5 programmers and would like to write a functional spec to explain what we need, so that when I begin my work - I know we are working towards the same goal.
2008/12/19
[ "https://Stackoverflow.com/questions/381216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28454/" ]
Another way to accomplish this is using [user stories](http://en.wikipedia.org/wiki/User_story)
Whether you call them functional specs, business requirements, or user stories, they are all very beneficial to the development process. The issue with them comes when they are chiseled in stone and used as a device to pass blame around when the system utimately doesn't fit with the user's real needs. I prefer to use the functionals or requirements as a starting point for an iterative process not as the bible for exactly how the system will look when it is complete. Things change, and users typically don't have an understanding of what they want until they have something (a working prototype possibly) in their hands that they can work with instead of conceptualizing on a piece of paper how it will function in the real world. The most successful projects I've implemented were ones where the development team and the users were closely aligned and were able to rapidly turn around changes instead of holding people to what they wanted on a piece of paper six months ago. Of course this process wouldn't work if you were in a fixed-bid type of situation as one of the earlier answers pointed out.
381,216
Does the functional spec help or hinder your expectations? Do programmers who practice the waterfall methodology, are they open to functional specs? I'm a web designer/developer working with a team of 5 programmers and would like to write a functional spec to explain what we need, so that when I begin my work - I know we are working towards the same goal.
2008/12/19
[ "https://Stackoverflow.com/questions/381216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28454/" ]
It took me more than 10 years to get it beat into my head to write a functional spec before doing any code. Now I will write one for anything taking more than a day to write. The level of detail, and level of assumptions should be as much as needed to clearly define what needs to be done and communicate it to others (or remind yourself), anything beyond that is a waste. Others prefer User Stories ... which is fine too, as long as you do some kind of planning.
I'll second [Codeslave's](https://stackoverflow.com/users/685/codeslave) reference to [Painless Functional Specification.](http://www.joelonsoftware.com/articles/fog0000000036.html) It's a good series of articles on specifications. See also [this Stackoverflow post](https://stackoverflow.com/questions/379371/what-makes-a-good-spec#379519) for a discussion on what content to put into functional specs. I've done a few large projects, including one with some hundereds of person-years of total effort. As a project team gets larger the number of informal communication channels goes up with a quadratic upper bound. Without a spec this informal communication mechanism is the only way things can get communicated. With a spec, the communication channels approach a hub-and-spokes, making the growth more like a linear function of the project team size. A spec is really the only scalable way to to get the team 'singing off the same hymn sheet'. There should be some review and negotiation about the spec, but ultimately someone has to take ownership of this to avoid the project becoming a free-for-all.
381,216
Does the functional spec help or hinder your expectations? Do programmers who practice the waterfall methodology, are they open to functional specs? I'm a web designer/developer working with a team of 5 programmers and would like to write a functional spec to explain what we need, so that when I begin my work - I know we are working towards the same goal.
2008/12/19
[ "https://Stackoverflow.com/questions/381216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28454/" ]
I find well-written functional specs very useful. A well organized functional specification can also help organize your tests (many-to-many mapping from individual requirements to test cases). `<p style="tongue: in-cheek">`They also prove useful for finger-pointing in larger organizations (The requirements were inaccurate! The implementation didn't follow the requirement! QA didn't properly test this requirement! etc.)`</p>`
One interesting substitute for a func spec or user stories that I have seen advocated is to write a user manual for the software first. Even if this is only notional (i.e. if you do not intend to ship any manual - which you probably shouldn't as nobody will read it), it can be a useful and reasonably lightweight way to reach a common understanding of what the software will do and look like. And it forces you to do the design up front.
381,216
Does the functional spec help or hinder your expectations? Do programmers who practice the waterfall methodology, are they open to functional specs? I'm a web designer/developer working with a team of 5 programmers and would like to write a functional spec to explain what we need, so that when I begin my work - I know we are working towards the same goal.
2008/12/19
[ "https://Stackoverflow.com/questions/381216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28454/" ]
Another way to accomplish this is using [user stories](http://en.wikipedia.org/wiki/User_story)
I have seen and written many specs, some were very good, most weren't. The main thing that they all had in common is that they were never followed. They all had cobwebs on them by the 3rd day of coding. Write the spec if you want, the best time to do it is at the end of the project. It will be useless for developers to follow but it will at least be an accurate representation of what was done (I know- not really a spec). But don't expect the spec to get the code written for you. That is the real job. If you don't know what to write talk to your stakeholders and users and get some good user stories and then get on with it.
381,216
Does the functional spec help or hinder your expectations? Do programmers who practice the waterfall methodology, are they open to functional specs? I'm a web designer/developer working with a team of 5 programmers and would like to write a functional spec to explain what we need, so that when I begin my work - I know we are working towards the same goal.
2008/12/19
[ "https://Stackoverflow.com/questions/381216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28454/" ]
Frankly, the Functional Specifications should already be part of your Big-M (Waterfall) methodology. Your functional specification is WHAT you are going to build; not necessarily how you are going to build it (which would be your detailed design/specification and the next step in the waterfall). If you haven't written one yet, stop what you are doing and write one. You are just waste time if you do otherwise. You can start [here with Joel's article](http://www.joelonsoftware.com/articles/fog0000000036.html).
I think they're a lovely idea, and should be tried.
381,216
Does the functional spec help or hinder your expectations? Do programmers who practice the waterfall methodology, are they open to functional specs? I'm a web designer/developer working with a team of 5 programmers and would like to write a functional spec to explain what we need, so that when I begin my work - I know we are working towards the same goal.
2008/12/19
[ "https://Stackoverflow.com/questions/381216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28454/" ]
I work with mostly the Waterfall model, and solely with functional specs. When working on my own (where I can set my own model and program any way I want) I start by writing up functional specs and then implementing them. It gives me a much better idea of the size and scope of the work, helps me estimate the time involved, and helps ensure that I don't miss anything. Also, you can pass this document to: 1. Users so that they can make their requirements clear 2. Developers to create the functionality 3. Testers to make sure they are testing the right thing 4. Architects so that they can analyze the requirements Using functional requirements over user stories is a matter of preference and the scope of the project. If you have a small user base, then you may be able to get away with user stories (which outline various event sequences the user might do), but for larger projects, you should use functional requirements as they have more detail and lead to fewer misunderstandings. Think of them as a means of communication with all people involved in the project.
It took me more than 10 years to get it beat into my head to write a functional spec before doing any code. Now I will write one for anything taking more than a day to write. The level of detail, and level of assumptions should be as much as needed to clearly define what needs to be done and communicate it to others (or remind yourself), anything beyond that is a waste. Others prefer User Stories ... which is fine too, as long as you do some kind of planning.
381,216
Does the functional spec help or hinder your expectations? Do programmers who practice the waterfall methodology, are they open to functional specs? I'm a web designer/developer working with a team of 5 programmers and would like to write a functional spec to explain what we need, so that when I begin my work - I know we are working towards the same goal.
2008/12/19
[ "https://Stackoverflow.com/questions/381216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28454/" ]
I work with mostly the Waterfall model, and solely with functional specs. When working on my own (where I can set my own model and program any way I want) I start by writing up functional specs and then implementing them. It gives me a much better idea of the size and scope of the work, helps me estimate the time involved, and helps ensure that I don't miss anything. Also, you can pass this document to: 1. Users so that they can make their requirements clear 2. Developers to create the functionality 3. Testers to make sure they are testing the right thing 4. Architects so that they can analyze the requirements Using functional requirements over user stories is a matter of preference and the scope of the project. If you have a small user base, then you may be able to get away with user stories (which outline various event sequences the user might do), but for larger projects, you should use functional requirements as they have more detail and lead to fewer misunderstandings. Think of them as a means of communication with all people involved in the project.
In my experience, functional specs have a fine line between not saying enough and saying too much. If they don't say enough, then they leave areas open to misunderstanding. If they say too much, they don't leave enough "wiggle room" to improve the solution. And they should **always** be open to a process of revision.
381,216
Does the functional spec help or hinder your expectations? Do programmers who practice the waterfall methodology, are they open to functional specs? I'm a web designer/developer working with a team of 5 programmers and would like to write a functional spec to explain what we need, so that when I begin my work - I know we are working towards the same goal.
2008/12/19
[ "https://Stackoverflow.com/questions/381216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28454/" ]
I'll second [Codeslave's](https://stackoverflow.com/users/685/codeslave) reference to [Painless Functional Specification.](http://www.joelonsoftware.com/articles/fog0000000036.html) It's a good series of articles on specifications. See also [this Stackoverflow post](https://stackoverflow.com/questions/379371/what-makes-a-good-spec#379519) for a discussion on what content to put into functional specs. I've done a few large projects, including one with some hundereds of person-years of total effort. As a project team gets larger the number of informal communication channels goes up with a quadratic upper bound. Without a spec this informal communication mechanism is the only way things can get communicated. With a spec, the communication channels approach a hub-and-spokes, making the growth more like a linear function of the project team size. A spec is really the only scalable way to to get the team 'singing off the same hymn sheet'. There should be some review and negotiation about the spec, but ultimately someone has to take ownership of this to avoid the project becoming a free-for-all.
One interesting substitute for a func spec or user stories that I have seen advocated is to write a user manual for the software first. Even if this is only notional (i.e. if you do not intend to ship any manual - which you probably shouldn't as nobody will read it), it can be a useful and reasonably lightweight way to reach a common understanding of what the software will do and look like. And it forces you to do the design up front.
381,216
Does the functional spec help or hinder your expectations? Do programmers who practice the waterfall methodology, are they open to functional specs? I'm a web designer/developer working with a team of 5 programmers and would like to write a functional spec to explain what we need, so that when I begin my work - I know we are working towards the same goal.
2008/12/19
[ "https://Stackoverflow.com/questions/381216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28454/" ]
In my experience, functional specs have a fine line between not saying enough and saying too much. If they don't say enough, then they leave areas open to misunderstanding. If they say too much, they don't leave enough "wiggle room" to improve the solution. And they should **always** be open to a process of revision.
One interesting substitute for a func spec or user stories that I have seen advocated is to write a user manual for the software first. Even if this is only notional (i.e. if you do not intend to ship any manual - which you probably shouldn't as nobody will read it), it can be a useful and reasonably lightweight way to reach a common understanding of what the software will do and look like. And it forces you to do the design up front.
381,216
Does the functional spec help or hinder your expectations? Do programmers who practice the waterfall methodology, are they open to functional specs? I'm a web designer/developer working with a team of 5 programmers and would like to write a functional spec to explain what we need, so that when I begin my work - I know we are working towards the same goal.
2008/12/19
[ "https://Stackoverflow.com/questions/381216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28454/" ]
I work with mostly the Waterfall model, and solely with functional specs. When working on my own (where I can set my own model and program any way I want) I start by writing up functional specs and then implementing them. It gives me a much better idea of the size and scope of the work, helps me estimate the time involved, and helps ensure that I don't miss anything. Also, you can pass this document to: 1. Users so that they can make their requirements clear 2. Developers to create the functionality 3. Testers to make sure they are testing the right thing 4. Architects so that they can analyze the requirements Using functional requirements over user stories is a matter of preference and the scope of the project. If you have a small user base, then you may be able to get away with user stories (which outline various event sequences the user might do), but for larger projects, you should use functional requirements as they have more detail and lead to fewer misunderstandings. Think of them as a means of communication with all people involved in the project.
I think they're a lovely idea, and should be tried.
4,592,838
I wrote my own custom post-merge hook, now I added a "hooks" directory to my main project folder (since git doesn't track changes in .git/hooks), somewhere I read that I can make a symbolic link from hooks to .git/hooks so I don't have to copy the file from one folder to the other every time someone changes it so I tried: `ln -s -f hooks/post-merge .git/hooks/post-merge` But it doesn't seem to work, any ideas why? "ln hooks/post-merge .git/hooks/post-merge" works fine but making a hard link is the same as copyin I guess....
2011/01/04
[ "https://Stackoverflow.com/questions/4592838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217019/" ]
The path calculation is done relative to the symlink. Let's understand using an example, `ln -s path/to/file symlink/file` Here, the path to the file should actually be the relative path from the symlink path. The system actually calculates the file path as `symlink/path/path/to/file` The above command should be re-written as `ln -s ../path/to/file symlink/path` The folder structure being, > > /code > > ------ symlink/file > > ------ path/to/file > > >
why not just cp ./hooks/\* .git/hooks/ this worked for me in Mac OS
4,592,838
I wrote my own custom post-merge hook, now I added a "hooks" directory to my main project folder (since git doesn't track changes in .git/hooks), somewhere I read that I can make a symbolic link from hooks to .git/hooks so I don't have to copy the file from one folder to the other every time someone changes it so I tried: `ln -s -f hooks/post-merge .git/hooks/post-merge` But it doesn't seem to work, any ideas why? "ln hooks/post-merge .git/hooks/post-merge" works fine but making a hard link is the same as copyin I guess....
2011/01/04
[ "https://Stackoverflow.com/questions/4592838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217019/" ]
you just used wrong path, it should be: ``` ln -s -f ../../hooks/post-merge .git/hooks/post-merge ```
Utilizing Michael Cihar's comment, here is an example of a bash script I wrote to simply create these symlinks. This script is located in git\_hooks/ dir which is at the project root. My .git/ folder is also in the same directory level. ``` #!/usr/bin/env bash pwd=$(pwd); # Script is designed to be ran from git_hooks/ dir if [[ "$pwd" == *"git_hooks"* ]]; then files=$(ls | grep -v -e '.*\.'); while read -r file; do ln -s ../../git_hooks/$file ../.git/hooks/ echo "Linked $file -> ../.git/hooks/$file" done <<< "$files"; else echo ""; echo "ERROR: "; echo "You must be within the git_hooks/ dir to run this command"; exit 1; fi ``` My script must be ran from within the actual git\_hooks/ directory. You can modify it to behave differently, if you'd like. This script will symlink any file that is not suffixed with a file extension within the git\_hooks/ directory. I have a README.txt in this directory + this script (named symlink.sh). All the actual git hooks are named 'pre-commit', 'pre-push', etc. so they will be symlinked.
4,592,838
I wrote my own custom post-merge hook, now I added a "hooks" directory to my main project folder (since git doesn't track changes in .git/hooks), somewhere I read that I can make a symbolic link from hooks to .git/hooks so I don't have to copy the file from one folder to the other every time someone changes it so I tried: `ln -s -f hooks/post-merge .git/hooks/post-merge` But it doesn't seem to work, any ideas why? "ln hooks/post-merge .git/hooks/post-merge" works fine but making a hard link is the same as copyin I guess....
2011/01/04
[ "https://Stackoverflow.com/questions/4592838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217019/" ]
you just used wrong path, it should be: ``` ln -s -f ../../hooks/post-merge .git/hooks/post-merge ```
The path calculation is done relative to the symlink. Let's understand using an example, `ln -s path/to/file symlink/file` Here, the path to the file should actually be the relative path from the symlink path. The system actually calculates the file path as `symlink/path/path/to/file` The above command should be re-written as `ln -s ../path/to/file symlink/path` The folder structure being, > > /code > > ------ symlink/file > > ------ path/to/file > > >
4,592,838
I wrote my own custom post-merge hook, now I added a "hooks" directory to my main project folder (since git doesn't track changes in .git/hooks), somewhere I read that I can make a symbolic link from hooks to .git/hooks so I don't have to copy the file from one folder to the other every time someone changes it so I tried: `ln -s -f hooks/post-merge .git/hooks/post-merge` But it doesn't seem to work, any ideas why? "ln hooks/post-merge .git/hooks/post-merge" works fine but making a hard link is the same as copyin I guess....
2011/01/04
[ "https://Stackoverflow.com/questions/4592838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217019/" ]
While you can use symbolic links, you can also change the hooks folder for your project in your git settings with : ``` git config core.hooksPath hooks/ ``` Which is local by default so it won't ruin git hooks for your other projects. It works for all hook in this repository, so it's especially useful if you have more than one hook. If you already have custom hooks in `.git/hooks/` that you do not want to share with your team you can add them in hooks/ and add a `.gitignore` so they're not shared.
why not just cp ./hooks/\* .git/hooks/ this worked for me in Mac OS
4,592,838
I wrote my own custom post-merge hook, now I added a "hooks" directory to my main project folder (since git doesn't track changes in .git/hooks), somewhere I read that I can make a symbolic link from hooks to .git/hooks so I don't have to copy the file from one folder to the other every time someone changes it so I tried: `ln -s -f hooks/post-merge .git/hooks/post-merge` But it doesn't seem to work, any ideas why? "ln hooks/post-merge .git/hooks/post-merge" works fine but making a hard link is the same as copyin I guess....
2011/01/04
[ "https://Stackoverflow.com/questions/4592838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217019/" ]
you just used wrong path, it should be: ``` ln -s -f ../../hooks/post-merge .git/hooks/post-merge ```
Changing directory before linking ``` cd /path/to/project-repo/.git/hooks ln -s -f ../../hooks/post-merge ./post-merge ```
4,592,838
I wrote my own custom post-merge hook, now I added a "hooks" directory to my main project folder (since git doesn't track changes in .git/hooks), somewhere I read that I can make a symbolic link from hooks to .git/hooks so I don't have to copy the file from one folder to the other every time someone changes it so I tried: `ln -s -f hooks/post-merge .git/hooks/post-merge` But it doesn't seem to work, any ideas why? "ln hooks/post-merge .git/hooks/post-merge" works fine but making a hard link is the same as copyin I guess....
2011/01/04
[ "https://Stackoverflow.com/questions/4592838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217019/" ]
While you can use symbolic links, you can also change the hooks folder for your project in your git settings with : ``` git config core.hooksPath hooks/ ``` Which is local by default so it won't ruin git hooks for your other projects. It works for all hook in this repository, so it's especially useful if you have more than one hook. If you already have custom hooks in `.git/hooks/` that you do not want to share with your team you can add them in hooks/ and add a `.gitignore` so they're not shared.
Changing directory before linking ``` cd /path/to/project-repo/.git/hooks ln -s -f ../../hooks/post-merge ./post-merge ```
4,592,838
I wrote my own custom post-merge hook, now I added a "hooks" directory to my main project folder (since git doesn't track changes in .git/hooks), somewhere I read that I can make a symbolic link from hooks to .git/hooks so I don't have to copy the file from one folder to the other every time someone changes it so I tried: `ln -s -f hooks/post-merge .git/hooks/post-merge` But it doesn't seem to work, any ideas why? "ln hooks/post-merge .git/hooks/post-merge" works fine but making a hard link is the same as copyin I guess....
2011/01/04
[ "https://Stackoverflow.com/questions/4592838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217019/" ]
While you can use symbolic links, you can also change the hooks folder for your project in your git settings with : ``` git config core.hooksPath hooks/ ``` Which is local by default so it won't ruin git hooks for your other projects. It works for all hook in this repository, so it's especially useful if you have more than one hook. If you already have custom hooks in `.git/hooks/` that you do not want to share with your team you can add them in hooks/ and add a `.gitignore` so they're not shared.
Utilizing Michael Cihar's comment, here is an example of a bash script I wrote to simply create these symlinks. This script is located in git\_hooks/ dir which is at the project root. My .git/ folder is also in the same directory level. ``` #!/usr/bin/env bash pwd=$(pwd); # Script is designed to be ran from git_hooks/ dir if [[ "$pwd" == *"git_hooks"* ]]; then files=$(ls | grep -v -e '.*\.'); while read -r file; do ln -s ../../git_hooks/$file ../.git/hooks/ echo "Linked $file -> ../.git/hooks/$file" done <<< "$files"; else echo ""; echo "ERROR: "; echo "You must be within the git_hooks/ dir to run this command"; exit 1; fi ``` My script must be ran from within the actual git\_hooks/ directory. You can modify it to behave differently, if you'd like. This script will symlink any file that is not suffixed with a file extension within the git\_hooks/ directory. I have a README.txt in this directory + this script (named symlink.sh). All the actual git hooks are named 'pre-commit', 'pre-push', etc. so they will be symlinked.
4,592,838
I wrote my own custom post-merge hook, now I added a "hooks" directory to my main project folder (since git doesn't track changes in .git/hooks), somewhere I read that I can make a symbolic link from hooks to .git/hooks so I don't have to copy the file from one folder to the other every time someone changes it so I tried: `ln -s -f hooks/post-merge .git/hooks/post-merge` But it doesn't seem to work, any ideas why? "ln hooks/post-merge .git/hooks/post-merge" works fine but making a hard link is the same as copyin I guess....
2011/01/04
[ "https://Stackoverflow.com/questions/4592838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217019/" ]
Changing directory before linking ``` cd /path/to/project-repo/.git/hooks ln -s -f ../../hooks/post-merge ./post-merge ```
Utilizing Michael Cihar's comment, here is an example of a bash script I wrote to simply create these symlinks. This script is located in git\_hooks/ dir which is at the project root. My .git/ folder is also in the same directory level. ``` #!/usr/bin/env bash pwd=$(pwd); # Script is designed to be ran from git_hooks/ dir if [[ "$pwd" == *"git_hooks"* ]]; then files=$(ls | grep -v -e '.*\.'); while read -r file; do ln -s ../../git_hooks/$file ../.git/hooks/ echo "Linked $file -> ../.git/hooks/$file" done <<< "$files"; else echo ""; echo "ERROR: "; echo "You must be within the git_hooks/ dir to run this command"; exit 1; fi ``` My script must be ran from within the actual git\_hooks/ directory. You can modify it to behave differently, if you'd like. This script will symlink any file that is not suffixed with a file extension within the git\_hooks/ directory. I have a README.txt in this directory + this script (named symlink.sh). All the actual git hooks are named 'pre-commit', 'pre-push', etc. so they will be symlinked.
4,592,838
I wrote my own custom post-merge hook, now I added a "hooks" directory to my main project folder (since git doesn't track changes in .git/hooks), somewhere I read that I can make a symbolic link from hooks to .git/hooks so I don't have to copy the file from one folder to the other every time someone changes it so I tried: `ln -s -f hooks/post-merge .git/hooks/post-merge` But it doesn't seem to work, any ideas why? "ln hooks/post-merge .git/hooks/post-merge" works fine but making a hard link is the same as copyin I guess....
2011/01/04
[ "https://Stackoverflow.com/questions/4592838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217019/" ]
Changing directory before linking ``` cd /path/to/project-repo/.git/hooks ln -s -f ../../hooks/post-merge ./post-merge ```
why not just cp ./hooks/\* .git/hooks/ this worked for me in Mac OS
4,592,838
I wrote my own custom post-merge hook, now I added a "hooks" directory to my main project folder (since git doesn't track changes in .git/hooks), somewhere I read that I can make a symbolic link from hooks to .git/hooks so I don't have to copy the file from one folder to the other every time someone changes it so I tried: `ln -s -f hooks/post-merge .git/hooks/post-merge` But it doesn't seem to work, any ideas why? "ln hooks/post-merge .git/hooks/post-merge" works fine but making a hard link is the same as copyin I guess....
2011/01/04
[ "https://Stackoverflow.com/questions/4592838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217019/" ]
Utilizing Michael Cihar's comment, here is an example of a bash script I wrote to simply create these symlinks. This script is located in git\_hooks/ dir which is at the project root. My .git/ folder is also in the same directory level. ``` #!/usr/bin/env bash pwd=$(pwd); # Script is designed to be ran from git_hooks/ dir if [[ "$pwd" == *"git_hooks"* ]]; then files=$(ls | grep -v -e '.*\.'); while read -r file; do ln -s ../../git_hooks/$file ../.git/hooks/ echo "Linked $file -> ../.git/hooks/$file" done <<< "$files"; else echo ""; echo "ERROR: "; echo "You must be within the git_hooks/ dir to run this command"; exit 1; fi ``` My script must be ran from within the actual git\_hooks/ directory. You can modify it to behave differently, if you'd like. This script will symlink any file that is not suffixed with a file extension within the git\_hooks/ directory. I have a README.txt in this directory + this script (named symlink.sh). All the actual git hooks are named 'pre-commit', 'pre-push', etc. so they will be symlinked.
why not just cp ./hooks/\* .git/hooks/ this worked for me in Mac OS
37,565,216
I am trying to create an object which contains an array of objects in javascript ``` var alertArray = { {threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} }; ``` I dont understand what i am doing wrong, please help
2016/06/01
[ "https://Stackoverflow.com/questions/37565216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5283633/" ]
You forgot the array-part: ``` var alertArray = { someArray: [{threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'}] }; ```
If you want to use an array you should have used square brackets: ``` var alertArray = [ {threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} ]; ```
37,565,216
I am trying to create an object which contains an array of objects in javascript ``` var alertArray = { {threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} }; ``` I dont understand what i am doing wrong, please help
2016/06/01
[ "https://Stackoverflow.com/questions/37565216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5283633/" ]
You forgot the array-part: ``` var alertArray = { someArray: [{threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'}] }; ```
Array of Objects is something like `[{},{},{},...]` and Object of array of an objects is something like that `{data:[{},{},{},...]}` ``` var alertArray = { data: [{threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'}] }; ```
37,565,216
I am trying to create an object which contains an array of objects in javascript ``` var alertArray = { {threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} }; ``` I dont understand what i am doing wrong, please help
2016/06/01
[ "https://Stackoverflow.com/questions/37565216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5283633/" ]
JS objects must have keys. **You could switch to an array of objects:** ``` var alertArray = [ {threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} ]; ``` **or give the sub-objects keys:** (making an object of objects) ``` var alertArray = { o1:{threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, o2:{threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, o3:{threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, o4:{threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} }; ``` or if you REALLY DO want an object which contains an array of objects: ``` var alertArray = { myObjects: [ {threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} ] }; ```
If you want to use an array you should have used square brackets: ``` var alertArray = [ {threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} ]; ```
37,565,216
I am trying to create an object which contains an array of objects in javascript ``` var alertArray = { {threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} }; ``` I dont understand what i am doing wrong, please help
2016/06/01
[ "https://Stackoverflow.com/questions/37565216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5283633/" ]
JS objects must have keys. **You could switch to an array of objects:** ``` var alertArray = [ {threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} ]; ``` **or give the sub-objects keys:** (making an object of objects) ``` var alertArray = { o1:{threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, o2:{threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, o3:{threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, o4:{threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} }; ``` or if you REALLY DO want an object which contains an array of objects: ``` var alertArray = { myObjects: [ {threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} ] }; ```
Array of Objects is something like `[{},{},{},...]` and Object of array of an objects is something like that `{data:[{},{},{},...]}` ``` var alertArray = { data: [{threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'}] }; ```
37,565,216
I am trying to create an object which contains an array of objects in javascript ``` var alertArray = { {threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} }; ``` I dont understand what i am doing wrong, please help
2016/06/01
[ "https://Stackoverflow.com/questions/37565216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5283633/" ]
If you want to use an array you should have used square brackets: ``` var alertArray = [ {threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'} ]; ```
Array of Objects is something like `[{},{},{},...]` and Object of array of an objects is something like that `{data:[{},{},{},...]}` ``` var alertArray = { data: [{threshold: 'critical', deviceName: 'Device Agg-02-01', text: 'CPU exceeding policy threshold of 80%', time: '7:00 PM'}, {threshold: 'critical', deviceName: 'Device Leaf-12-22', text: 'Memory utilization exceeding 40%', time: '6:34 PM'}, {threshold: 'warning', deviceName: 'Leaf10-12', text: 'New Software available for upgrade on device', time: '5:10 PM'}, {threshold: 'warning', deviceName: 'Leaf10-11', text: 'New Software available for upgrade on device', time: '4:32 PM'}] }; ```
4,240,984
i'm coming into C++ from Java/AS3-land, and i'm used to the package-cum-folder structure for my classes. and i like it. i understand the very basics of namespaces in c++, and i'm happy to leave it at just the basics. but, as my project gets more complex, i'd like to keep my folder structure organized in a way i can keep in my head. i.e. something similar to Java/AS3. 1) is there any reason to *not* have a folder structure like: ``` src/ model/ view/ controller/ ``` possibly with subfolders? (this is just an MVC example, the folder structure could be whatever depending on the project's needs.) it just seems unruly to have a src/ folder with a huge pile of header and source files within. 2) if the answer to 1) could be "go ahead and do what you want", would it be unwise/unnecessary to create a namespace for each folder, similar to Java/AS3's way of creating a package for each folder? my understanding is that namespaces are not usually used like this, nested deeply and folder-related.
2010/11/21
[ "https://Stackoverflow.com/questions/4240984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222356/" ]
You may want to have a look at John Lakos `Large-Scale C++ Software Design`. Basically, you can do that, but your packages should (as in Java) have an acyclic dependency graph. Also, it may be opportune for each package to document which headers are exported and which aren't, maybe like so: ``` src/ |- package1/ |- exported_symbols_1.hh |- exported_symbols_2.hh |- src/ |- impl_1.hh |- impl_1.cc |- package2/ |- sub_package_2_1/ |- exported.hh |- src/ ... |- src/ ... ``` Each package is only allowed to #include the top-level headers of another package, never ones in `src/` directories. Also, when you want to use `Autotools` in a large project and intend to distribute headers, it may prove to be prudent to call the top-level directory not `src/` but by the `PACKAGE_TARNAME` of that project. This makes installing headers with the help of the `Autotools` easier. (And, of course, the actual file names do not look as silly as illustrated above.)
You can arrange your files however you like; you'll just need to adjust your build tools' include paths and source paths to match. Giving each directory it's own namespace is overkill and probably a bad idea, as it will make for confusing code. I'd recommend one namespace per project at most, or even just one namespace per company (since presumably within your company you have the power to rename things if necessary to resolve name collisions. Namespaces' main purpose is to handle the case where two codebases under the control of two different organizations both use the same name, and you as a third party want to use them both in the same project, but don't have the ability to modify either codebase).
4,240,984
i'm coming into C++ from Java/AS3-land, and i'm used to the package-cum-folder structure for my classes. and i like it. i understand the very basics of namespaces in c++, and i'm happy to leave it at just the basics. but, as my project gets more complex, i'd like to keep my folder structure organized in a way i can keep in my head. i.e. something similar to Java/AS3. 1) is there any reason to *not* have a folder structure like: ``` src/ model/ view/ controller/ ``` possibly with subfolders? (this is just an MVC example, the folder structure could be whatever depending on the project's needs.) it just seems unruly to have a src/ folder with a huge pile of header and source files within. 2) if the answer to 1) could be "go ahead and do what you want", would it be unwise/unnecessary to create a namespace for each folder, similar to Java/AS3's way of creating a package for each folder? my understanding is that namespaces are not usually used like this, nested deeply and folder-related.
2010/11/21
[ "https://Stackoverflow.com/questions/4240984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222356/" ]
There's no reason not to and will really help people reading your code. Some things to watch out for: 1. Don't **over**-nest folders, this can be confusing for readers of your code. 2. Be consistent in the organization of your code, e.g. don't put **any** view code in the controllers sub-directory, or vice-versa. 3. Keep the layout clean.
You can arrange your files however you like; you'll just need to adjust your build tools' include paths and source paths to match. Giving each directory it's own namespace is overkill and probably a bad idea, as it will make for confusing code. I'd recommend one namespace per project at most, or even just one namespace per company (since presumably within your company you have the power to rename things if necessary to resolve name collisions. Namespaces' main purpose is to handle the case where two codebases under the control of two different organizations both use the same name, and you as a third party want to use them both in the same project, but don't have the ability to modify either codebase).
4,240,984
i'm coming into C++ from Java/AS3-land, and i'm used to the package-cum-folder structure for my classes. and i like it. i understand the very basics of namespaces in c++, and i'm happy to leave it at just the basics. but, as my project gets more complex, i'd like to keep my folder structure organized in a way i can keep in my head. i.e. something similar to Java/AS3. 1) is there any reason to *not* have a folder structure like: ``` src/ model/ view/ controller/ ``` possibly with subfolders? (this is just an MVC example, the folder structure could be whatever depending on the project's needs.) it just seems unruly to have a src/ folder with a huge pile of header and source files within. 2) if the answer to 1) could be "go ahead and do what you want", would it be unwise/unnecessary to create a namespace for each folder, similar to Java/AS3's way of creating a package for each folder? my understanding is that namespaces are not usually used like this, nested deeply and folder-related.
2010/11/21
[ "https://Stackoverflow.com/questions/4240984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222356/" ]
I've always liked the namespace for each folder. Mostly because when I have to maintain somebody else's code, the namespace helps me find where the class was originally defined. Well named header files can also help with this though. I also wouldn't suggest going more than 2-3 namespaces, as then it just becomes obnoxious. You'll find yourself using "using namespace blah;" a lot which I always find to be a red flag for C++ code. And you can't use "using namespace" inside a header file without some severe problems occurring. It's all completely optional though in C++.
There's no reason not to divide your source code into different directories; it makes sense if there are many files and clear logical groupings. It is not necessary to create a distinct file for each small class though - in large projects, that tends to slow compilation (as the implementation files often have to include a lot of the same headers just to compile their couple dozen lines). As well as the use of namespaces for reflecting the logical divisions in the code, the exact thresholds at which code is subdivided into further namespaces tends to be driven by some other forces, for example: * factors suggesting use of more namespaces + very volatile code (often edited, constant additional/changed identifier use, often short and/or common words) + more developers * factors reducing the need for namespaces + tight coordination by a central body + planned formal releases with thorough checks for conflicts Namespaces can also be used as a way to allow easy switching between alternative implementations (e.g. different versions of a protocol, thread-safe versus unsafe support functions, OS-specific implementations), so sometimes catering for such needs involves use of distinct namespaces. It can definitely be painful digging through unintuitive and/or deeply nested namespaces to reach the variables you want, and "using namespace" is less effective if you're likely to need to use several that define the same identifiers anyway, but can suit more modal code that tends to use one or the other namespace more heavily at a time. So, you may want to consider these factors when deciding whether to put each folder's code (or some other logically distinct group) into distinct namespaces.
4,240,984
i'm coming into C++ from Java/AS3-land, and i'm used to the package-cum-folder structure for my classes. and i like it. i understand the very basics of namespaces in c++, and i'm happy to leave it at just the basics. but, as my project gets more complex, i'd like to keep my folder structure organized in a way i can keep in my head. i.e. something similar to Java/AS3. 1) is there any reason to *not* have a folder structure like: ``` src/ model/ view/ controller/ ``` possibly with subfolders? (this is just an MVC example, the folder structure could be whatever depending on the project's needs.) it just seems unruly to have a src/ folder with a huge pile of header and source files within. 2) if the answer to 1) could be "go ahead and do what you want", would it be unwise/unnecessary to create a namespace for each folder, similar to Java/AS3's way of creating a package for each folder? my understanding is that namespaces are not usually used like this, nested deeply and folder-related.
2010/11/21
[ "https://Stackoverflow.com/questions/4240984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222356/" ]
You may want to have a look at John Lakos `Large-Scale C++ Software Design`. Basically, you can do that, but your packages should (as in Java) have an acyclic dependency graph. Also, it may be opportune for each package to document which headers are exported and which aren't, maybe like so: ``` src/ |- package1/ |- exported_symbols_1.hh |- exported_symbols_2.hh |- src/ |- impl_1.hh |- impl_1.cc |- package2/ |- sub_package_2_1/ |- exported.hh |- src/ ... |- src/ ... ``` Each package is only allowed to #include the top-level headers of another package, never ones in `src/` directories. Also, when you want to use `Autotools` in a large project and intend to distribute headers, it may prove to be prudent to call the top-level directory not `src/` but by the `PACKAGE_TARNAME` of that project. This makes installing headers with the help of the `Autotools` easier. (And, of course, the actual file names do not look as silly as illustrated above.)
There's no reason not to and will really help people reading your code. Some things to watch out for: 1. Don't **over**-nest folders, this can be confusing for readers of your code. 2. Be consistent in the organization of your code, e.g. don't put **any** view code in the controllers sub-directory, or vice-versa. 3. Keep the layout clean.
4,240,984
i'm coming into C++ from Java/AS3-land, and i'm used to the package-cum-folder structure for my classes. and i like it. i understand the very basics of namespaces in c++, and i'm happy to leave it at just the basics. but, as my project gets more complex, i'd like to keep my folder structure organized in a way i can keep in my head. i.e. something similar to Java/AS3. 1) is there any reason to *not* have a folder structure like: ``` src/ model/ view/ controller/ ``` possibly with subfolders? (this is just an MVC example, the folder structure could be whatever depending on the project's needs.) it just seems unruly to have a src/ folder with a huge pile of header and source files within. 2) if the answer to 1) could be "go ahead and do what you want", would it be unwise/unnecessary to create a namespace for each folder, similar to Java/AS3's way of creating a package for each folder? my understanding is that namespaces are not usually used like this, nested deeply and folder-related.
2010/11/21
[ "https://Stackoverflow.com/questions/4240984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222356/" ]
There's no reason not to divide your source code into different directories; it makes sense if there are many files and clear logical groupings. It is not necessary to create a distinct file for each small class though - in large projects, that tends to slow compilation (as the implementation files often have to include a lot of the same headers just to compile their couple dozen lines). As well as the use of namespaces for reflecting the logical divisions in the code, the exact thresholds at which code is subdivided into further namespaces tends to be driven by some other forces, for example: * factors suggesting use of more namespaces + very volatile code (often edited, constant additional/changed identifier use, often short and/or common words) + more developers * factors reducing the need for namespaces + tight coordination by a central body + planned formal releases with thorough checks for conflicts Namespaces can also be used as a way to allow easy switching between alternative implementations (e.g. different versions of a protocol, thread-safe versus unsafe support functions, OS-specific implementations), so sometimes catering for such needs involves use of distinct namespaces. It can definitely be painful digging through unintuitive and/or deeply nested namespaces to reach the variables you want, and "using namespace" is less effective if you're likely to need to use several that define the same identifiers anyway, but can suit more modal code that tends to use one or the other namespace more heavily at a time. So, you may want to consider these factors when deciding whether to put each folder's code (or some other logically distinct group) into distinct namespaces.
There's no reason not to and will really help people reading your code. Some things to watch out for: 1. Don't **over**-nest folders, this can be confusing for readers of your code. 2. Be consistent in the organization of your code, e.g. don't put **any** view code in the controllers sub-directory, or vice-versa. 3. Keep the layout clean.
4,240,984
i'm coming into C++ from Java/AS3-land, and i'm used to the package-cum-folder structure for my classes. and i like it. i understand the very basics of namespaces in c++, and i'm happy to leave it at just the basics. but, as my project gets more complex, i'd like to keep my folder structure organized in a way i can keep in my head. i.e. something similar to Java/AS3. 1) is there any reason to *not* have a folder structure like: ``` src/ model/ view/ controller/ ``` possibly with subfolders? (this is just an MVC example, the folder structure could be whatever depending on the project's needs.) it just seems unruly to have a src/ folder with a huge pile of header and source files within. 2) if the answer to 1) could be "go ahead and do what you want", would it be unwise/unnecessary to create a namespace for each folder, similar to Java/AS3's way of creating a package for each folder? my understanding is that namespaces are not usually used like this, nested deeply and folder-related.
2010/11/21
[ "https://Stackoverflow.com/questions/4240984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222356/" ]
I've always liked the namespace for each folder. Mostly because when I have to maintain somebody else's code, the namespace helps me find where the class was originally defined. Well named header files can also help with this though. I also wouldn't suggest going more than 2-3 namespaces, as then it just becomes obnoxious. You'll find yourself using "using namespace blah;" a lot which I always find to be a red flag for C++ code. And you can't use "using namespace" inside a header file without some severe problems occurring. It's all completely optional though in C++.
The src/ is a common place there c/c++ programmers put their sources within the project root. For example: ``` doc/ <- documentation libs/ <- additional libraries po/ <- gettext translations src/ <- sources ``` it common to create subdirectories underneath src/ if you've got a lot of sources files but there are no limitations how to organize this substructure. Keep in mind that a directory structure in completely optional in c++. That is no connection between c++ namespaces and the directory structure.
4,240,984
i'm coming into C++ from Java/AS3-land, and i'm used to the package-cum-folder structure for my classes. and i like it. i understand the very basics of namespaces in c++, and i'm happy to leave it at just the basics. but, as my project gets more complex, i'd like to keep my folder structure organized in a way i can keep in my head. i.e. something similar to Java/AS3. 1) is there any reason to *not* have a folder structure like: ``` src/ model/ view/ controller/ ``` possibly with subfolders? (this is just an MVC example, the folder structure could be whatever depending on the project's needs.) it just seems unruly to have a src/ folder with a huge pile of header and source files within. 2) if the answer to 1) could be "go ahead and do what you want", would it be unwise/unnecessary to create a namespace for each folder, similar to Java/AS3's way of creating a package for each folder? my understanding is that namespaces are not usually used like this, nested deeply and folder-related.
2010/11/21
[ "https://Stackoverflow.com/questions/4240984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222356/" ]
You may want to have a look at John Lakos `Large-Scale C++ Software Design`. Basically, you can do that, but your packages should (as in Java) have an acyclic dependency graph. Also, it may be opportune for each package to document which headers are exported and which aren't, maybe like so: ``` src/ |- package1/ |- exported_symbols_1.hh |- exported_symbols_2.hh |- src/ |- impl_1.hh |- impl_1.cc |- package2/ |- sub_package_2_1/ |- exported.hh |- src/ ... |- src/ ... ``` Each package is only allowed to #include the top-level headers of another package, never ones in `src/` directories. Also, when you want to use `Autotools` in a large project and intend to distribute headers, it may prove to be prudent to call the top-level directory not `src/` but by the `PACKAGE_TARNAME` of that project. This makes installing headers with the help of the `Autotools` easier. (And, of course, the actual file names do not look as silly as illustrated above.)
The src/ is a common place there c/c++ programmers put their sources within the project root. For example: ``` doc/ <- documentation libs/ <- additional libraries po/ <- gettext translations src/ <- sources ``` it common to create subdirectories underneath src/ if you've got a lot of sources files but there are no limitations how to organize this substructure. Keep in mind that a directory structure in completely optional in c++. That is no connection between c++ namespaces and the directory structure.
4,240,984
i'm coming into C++ from Java/AS3-land, and i'm used to the package-cum-folder structure for my classes. and i like it. i understand the very basics of namespaces in c++, and i'm happy to leave it at just the basics. but, as my project gets more complex, i'd like to keep my folder structure organized in a way i can keep in my head. i.e. something similar to Java/AS3. 1) is there any reason to *not* have a folder structure like: ``` src/ model/ view/ controller/ ``` possibly with subfolders? (this is just an MVC example, the folder structure could be whatever depending on the project's needs.) it just seems unruly to have a src/ folder with a huge pile of header and source files within. 2) if the answer to 1) could be "go ahead and do what you want", would it be unwise/unnecessary to create a namespace for each folder, similar to Java/AS3's way of creating a package for each folder? my understanding is that namespaces are not usually used like this, nested deeply and folder-related.
2010/11/21
[ "https://Stackoverflow.com/questions/4240984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222356/" ]
There's no reason not to divide your source code into different directories; it makes sense if there are many files and clear logical groupings. It is not necessary to create a distinct file for each small class though - in large projects, that tends to slow compilation (as the implementation files often have to include a lot of the same headers just to compile their couple dozen lines). As well as the use of namespaces for reflecting the logical divisions in the code, the exact thresholds at which code is subdivided into further namespaces tends to be driven by some other forces, for example: * factors suggesting use of more namespaces + very volatile code (often edited, constant additional/changed identifier use, often short and/or common words) + more developers * factors reducing the need for namespaces + tight coordination by a central body + planned formal releases with thorough checks for conflicts Namespaces can also be used as a way to allow easy switching between alternative implementations (e.g. different versions of a protocol, thread-safe versus unsafe support functions, OS-specific implementations), so sometimes catering for such needs involves use of distinct namespaces. It can definitely be painful digging through unintuitive and/or deeply nested namespaces to reach the variables you want, and "using namespace" is less effective if you're likely to need to use several that define the same identifiers anyway, but can suit more modal code that tends to use one or the other namespace more heavily at a time. So, you may want to consider these factors when deciding whether to put each folder's code (or some other logically distinct group) into distinct namespaces.
You can arrange your files however you like; you'll just need to adjust your build tools' include paths and source paths to match. Giving each directory it's own namespace is overkill and probably a bad idea, as it will make for confusing code. I'd recommend one namespace per project at most, or even just one namespace per company (since presumably within your company you have the power to rename things if necessary to resolve name collisions. Namespaces' main purpose is to handle the case where two codebases under the control of two different organizations both use the same name, and you as a third party want to use them both in the same project, but don't have the ability to modify either codebase).
4,240,984
i'm coming into C++ from Java/AS3-land, and i'm used to the package-cum-folder structure for my classes. and i like it. i understand the very basics of namespaces in c++, and i'm happy to leave it at just the basics. but, as my project gets more complex, i'd like to keep my folder structure organized in a way i can keep in my head. i.e. something similar to Java/AS3. 1) is there any reason to *not* have a folder structure like: ``` src/ model/ view/ controller/ ``` possibly with subfolders? (this is just an MVC example, the folder structure could be whatever depending on the project's needs.) it just seems unruly to have a src/ folder with a huge pile of header and source files within. 2) if the answer to 1) could be "go ahead and do what you want", would it be unwise/unnecessary to create a namespace for each folder, similar to Java/AS3's way of creating a package for each folder? my understanding is that namespaces are not usually used like this, nested deeply and folder-related.
2010/11/21
[ "https://Stackoverflow.com/questions/4240984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222356/" ]
The src/ is a common place there c/c++ programmers put their sources within the project root. For example: ``` doc/ <- documentation libs/ <- additional libraries po/ <- gettext translations src/ <- sources ``` it common to create subdirectories underneath src/ if you've got a lot of sources files but there are no limitations how to organize this substructure. Keep in mind that a directory structure in completely optional in c++. That is no connection between c++ namespaces and the directory structure.
You can arrange your files however you like; you'll just need to adjust your build tools' include paths and source paths to match. Giving each directory it's own namespace is overkill and probably a bad idea, as it will make for confusing code. I'd recommend one namespace per project at most, or even just one namespace per company (since presumably within your company you have the power to rename things if necessary to resolve name collisions. Namespaces' main purpose is to handle the case where two codebases under the control of two different organizations both use the same name, and you as a third party want to use them both in the same project, but don't have the ability to modify either codebase).
4,240,984
i'm coming into C++ from Java/AS3-land, and i'm used to the package-cum-folder structure for my classes. and i like it. i understand the very basics of namespaces in c++, and i'm happy to leave it at just the basics. but, as my project gets more complex, i'd like to keep my folder structure organized in a way i can keep in my head. i.e. something similar to Java/AS3. 1) is there any reason to *not* have a folder structure like: ``` src/ model/ view/ controller/ ``` possibly with subfolders? (this is just an MVC example, the folder structure could be whatever depending on the project's needs.) it just seems unruly to have a src/ folder with a huge pile of header and source files within. 2) if the answer to 1) could be "go ahead and do what you want", would it be unwise/unnecessary to create a namespace for each folder, similar to Java/AS3's way of creating a package for each folder? my understanding is that namespaces are not usually used like this, nested deeply and folder-related.
2010/11/21
[ "https://Stackoverflow.com/questions/4240984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/222356/" ]
There's no reason not to divide your source code into different directories; it makes sense if there are many files and clear logical groupings. It is not necessary to create a distinct file for each small class though - in large projects, that tends to slow compilation (as the implementation files often have to include a lot of the same headers just to compile their couple dozen lines). As well as the use of namespaces for reflecting the logical divisions in the code, the exact thresholds at which code is subdivided into further namespaces tends to be driven by some other forces, for example: * factors suggesting use of more namespaces + very volatile code (often edited, constant additional/changed identifier use, often short and/or common words) + more developers * factors reducing the need for namespaces + tight coordination by a central body + planned formal releases with thorough checks for conflicts Namespaces can also be used as a way to allow easy switching between alternative implementations (e.g. different versions of a protocol, thread-safe versus unsafe support functions, OS-specific implementations), so sometimes catering for such needs involves use of distinct namespaces. It can definitely be painful digging through unintuitive and/or deeply nested namespaces to reach the variables you want, and "using namespace" is less effective if you're likely to need to use several that define the same identifiers anyway, but can suit more modal code that tends to use one or the other namespace more heavily at a time. So, you may want to consider these factors when deciding whether to put each folder's code (or some other logically distinct group) into distinct namespaces.
The src/ is a common place there c/c++ programmers put their sources within the project root. For example: ``` doc/ <- documentation libs/ <- additional libraries po/ <- gettext translations src/ <- sources ``` it common to create subdirectories underneath src/ if you've got a lot of sources files but there are no limitations how to organize this substructure. Keep in mind that a directory structure in completely optional in c++. That is no connection between c++ namespaces and the directory structure.
72,308
The Hill's [Pope blasts Russia’s ‘infantile’ war](https://thehill.com/news/wire/3257104-pope-blasts-russias-infantile-war/) says: > > Francis has to date avoided referring to Russia or Putin by name. But Saturday’s personalization of the powerful figure responsible marked a new level of outrage for the pope. > > > “Once again, some potentate, sadly caught up in anachronistic claims of nationalist interest, is provoking and fomenting conflicts, whereas ordinary people sense the need to build a future that will either be shared or not be at all,” he said. > > > The Vatican tends to not call out aggressors in hopes of keeping open options for dialogue. **The Vatican, which in recent years has forged unprecedented new relations with the Putin-allied Russian Orthodox Church, had offered itself as a potential mediator but to date has been largely left on the diplomatic sidelines.** > > > Francis told reporters en route to Malta that a possible visit to Kyiv was “on the table,” but no dates have been set or trip confirmed. The mayor of the Ukrainian capital had invited Francis to come as a messenger of peace along with other religious figures. > > > I originally wanted to ask if the Russian Orthodox Church has articulated any anti-war message with regard to the [Russo-Ukrainian War](https://en.wikipedia.org/wiki/Russo-Ukrainian_War) since it started in 2014, but it is possible that one can guess an approximate answer from The Hill's use of "Putin-allied Russian Orthodox Church". Nonetheless I would like to ask: **Question:** How politically aligned with Moscow has the [Russian Orthodox Church](https://en.wikipedia.org/wiki/Russian_Orthodox_Church)'s position on the [Russo-Ukrainian War](https://en.wikipedia.org/wiki/Russo-Ukrainian_War) been since it started in 2014? One extreme would be that they are completely aligned and no light can be seen between the two, the other extreme *might be* for example more like that of the Pope that the substantial loss of life and destruction of a country can not be justified. What do the facts tell us?
2022/04/02
[ "https://politics.stackexchange.com/questions/72308", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/16047/" ]
Patriarch Kiril [referred to the war in Ukraine as a "metaphysical" struggle against a godless international order.](https://theweek.com/russo-ukrainian-war/1011020/war-in-ukraine-is-a-metaphysical-battle-against-a-civilization-built-on) That sounds like a strong support, doesn't it? On the other hand [some other priests and deacons disagree with the patriarch.](https://www.aljazeera.com/news/2022/3/28/patriarch-kirill-putin-ally-faces-backlash) > > We respect the God-given freedom of man, and we believe that the people of Ukraine should make their choice on their own, not at gunpoint, without pressure from the West or the East > > > Still, the official stance of Russian Orthodox Church is the patriarch's one, this is not a democracy. This was about 2022 war. As for annexation of Crimea [Patriach Kirill has adopted a neutral stance](https://www.osw.waw.pl/en/publikacje/osw-commentary/2014-08-14/patriarch-kirills-game-over-ukraine#_ftn13) > > Members of our Church in Ukraine hold different political views and beliefs and are standing today on the different sides of the barricade. The Church does not take sides in the political struggle. Its task is to take care of all those who have been exposed to violence > > >
In 2014, the largest church in Ukraine was УПЦ (МП), that is Ukrainian Orthdox Church of Moscow Patriarchate, a subdivision of Russian Orthdox Church. Since their Ukrainian branch was a sizable share of their whole operation, the Moscow Patriarchate was actually reluctant to do anything which would look unfriendly to Ukrainian state, which was tricky given the whole Crimea and Donbass affair. They did not move Crimea over from Ukrainian to Russian church - I think it remains a part of Ukrainian church to this day, with the same Ukrainian top clergy who ran it before 2014. Russian Orthdox Church was also reluctant to support pro-Russian rebels in Donbass, to the extent that Strelkov had to ask the overseas branch of Russian Orthdox Church to bless his military banners. Overseas branch of Russian Orthdox Church, called РПЦ(з) is still fairly autonomous since the times when Soviet rule tried to eradricate Russian Orthdox Church after the revolution. In spite of that, Ukraine still did not consider УПЦ (МП) loyal enough, and under both Poroshenko and Zelensky the Ukrainian state would repeatedly try to hinder УПЦ (МП) in favour of other, smaller Ukrainian churches. This follows the same pattern of Russian, post-USSR institutions having significant predisposition towards Ukraine which is slowly drained following diplomatic crises between Russia and Ukraine.
30,823,681
I have this batch to kill some process typed of course by the user and it works 5/5 when the user for example typed **Calc.exe** with the extension, but my issue now is to improve this batch in order to add automatically with this program if the user has omitted to add extension **.exe** like **Calc** without extension **.exe** will not work. ``` @Echo off & cls Mode con cols=72 lines=7 Set TmpFile=TmpFile.txt Set Resultat=KillResult.txt If Exist %TmpFile% Del %TmpFile% If Exist %Resultat% Del %Resultat% ::******************************************************************************************** :Main Title Process Killer by Hackoo 2015 cls & color 0B echo. echo Quel(s) processus voulez-vous fermer ? echo. set/p "process=Entrer le(s) nom(s) de(s) processus> " cls & color 0C Title Killing "%process%" ... echo. echo Killing "%process%" ... echo. echo %date% *** %time% >> %TmpFile% For %%a in (%process%) Do Call :KillProcess %%a Cmd /U /C Type %TmpFile% > %Resultat% Start %Resultat% echo. Goto :Main ::********************************************************************************************* :KillProcess Taskkill /IM "%~1" /F >> %TmpFile% 2>&1 echo ***************************************************************************** >> %TmpFile% ::********************************************************************************************* ``` So i'm focusing on this piece of code but no success ! this my little try : ``` :KillProcess Set str=%~1 set str=%str:~-4% echo.%str% pause if %str%==".exe" (Taskkill /IM "%~1" /F >> %TmpFile% 2>&1) || (Taskkill /IM "%~1.exe" /F >> %TmpFile% 2>&1) ``` So how to do that in batch ? Thank you !
2015/06/13
[ "https://Stackoverflow.com/questions/30823681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3080770/" ]
If your files have never any other extension than `.exe`, you can use `"%~n1.exe"` to get the filename with `.exe`. `%~n1` is just the filename without extension. Than add `.exe`, and put quotes around it in case the filename contains a space. But this will fail if your executable is `example.program.exe`, and the user entered `example.program`. In this case the result of `"%~n1.exe"` will be `"example.exe"`. To avoid that, you have to check if the extension is `.exe`. You can use `%~x1` to get just the extension. See also [Command Line arguments (Parameters)](http://ss64.com/nt/syntax-args.html) for more information.
Something like ``` :loopMain set /p "process=Entrer le(s) nom(s) de(s) processus> " if "%process:.exe=%"=="%process%" goto :loopMain ``` or ``` :loopMain set /p "process=Entrer le(s) nom(s) de(s) processus> " if /I not "%process:~-4%"==".exe" goto :loopMain ``` or `set "process=%process%.exe"` instead of `goto :loopMain`. Similar approach in case of multiple names typed in: check an correct user's input in a simple `for %%a in (%process%) do ...` loop.
30,823,681
I have this batch to kill some process typed of course by the user and it works 5/5 when the user for example typed **Calc.exe** with the extension, but my issue now is to improve this batch in order to add automatically with this program if the user has omitted to add extension **.exe** like **Calc** without extension **.exe** will not work. ``` @Echo off & cls Mode con cols=72 lines=7 Set TmpFile=TmpFile.txt Set Resultat=KillResult.txt If Exist %TmpFile% Del %TmpFile% If Exist %Resultat% Del %Resultat% ::******************************************************************************************** :Main Title Process Killer by Hackoo 2015 cls & color 0B echo. echo Quel(s) processus voulez-vous fermer ? echo. set/p "process=Entrer le(s) nom(s) de(s) processus> " cls & color 0C Title Killing "%process%" ... echo. echo Killing "%process%" ... echo. echo %date% *** %time% >> %TmpFile% For %%a in (%process%) Do Call :KillProcess %%a Cmd /U /C Type %TmpFile% > %Resultat% Start %Resultat% echo. Goto :Main ::********************************************************************************************* :KillProcess Taskkill /IM "%~1" /F >> %TmpFile% 2>&1 echo ***************************************************************************** >> %TmpFile% ::********************************************************************************************* ``` So i'm focusing on this piece of code but no success ! this my little try : ``` :KillProcess Set str=%~1 set str=%str:~-4% echo.%str% pause if %str%==".exe" (Taskkill /IM "%~1" /F >> %TmpFile% 2>&1) || (Taskkill /IM "%~1.exe" /F >> %TmpFile% 2>&1) ``` So how to do that in batch ? Thank you !
2015/06/13
[ "https://Stackoverflow.com/questions/30823681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3080770/" ]
Just i want to share with you the hole script with a dynamic menu, perhaps it would be helpful for other people and thank you for all your contributions ;) (Translated some french words to english) ``` @Echo off & cls & color 0B Mode con cols=72 lines=10 Set TmpFile=TmpFile.txt Set Resultat=KillResult.txt If Exist %TmpFile% Del %TmpFile% If Exist %Resultat% Del %Resultat% :menuLOOP Cls & color 0B Title Process Starter and Killer by Hackoo 2015 echo. echo. ==========================Menu============================ echo. for /f "tokens=1,2,* delims=_ " %%A in ('"findstr /b /c:":menu_" "%~f0""') do echo. %%B %%C echo. echo. ========================================================== set choice= echo. & set /p choice=Make a choice or hit ENTER to quit: || GOTO :EOF echo. & call :menu_[%choice%] GOTO:menuLOOP ::******************************************************************************************** :menu_[1] Start a Process cls & color 0B echo. Set /p "MyProcess=Enter the process name to start it> " echo. echo Le processus %MyProcess% est lance ... Start %MyProcess% GOTO :menuLOOP ::******************************************************************************************** :menu_[2] Kill a Process or Multi Processes Title Process Killer by Hackoo 2015 cls & color 0B echo. echo What process do you want to kill ? echo. set/p "process=Enter the process name or processes names separated by a space> " cls & color 0C Title Killing "%process%" ... echo. echo Killing "%process%" ... echo. echo %date% *** %time% >> %TmpFile% For %%a in (%process%) Do Call :KillMyProcess %%a Cmd /U /C Type %TmpFile% > %Resultat% Start %Resultat% GOTO :menuLOOP ::********************************************************************************************* :KillMyProcess Taskkill /IM "%~n1.exe" /F >> %TmpFile% 2>&1 echo ***************************************************************************** >> %TmpFile% exit /b ::********************************************************************************************* :EOF EXIT ``` **EDIT 15/06/2015 : New Version** : Adding **Search for files** using the command **Where** ``` @Echo off & cls & color 0B Mode con cols=72 lines=11 Set TmpFile=TmpFile.txt Set Resultat=KillResult.txt If Exist %TmpFile% Del %TmpFile% If Exist %Resultat% Del %Resultat% :menuLOOP Mode con cols=72 lines=11 Cls & color 0B Title Process Starter and Killer by Hackoo 2015 echo( echo( ==========================Menu============================ echo( ::Suggestion de Walid : optimisation au niveau du parseur : utiliser deux tokens au lieu de trois for /f "tokens=2* delims=_ " %%A in ('"findstr /b /c:":menu_" "%~f0""') do echo( %%A %%B ::for /f "tokens=1,2,* delims=_ " %%A in ('"findstr /b /c:":menu_" "%~f0""') do echo( %%B %%C echo( echo( ========================================================== set choice= echo( & set /p choice=Make a choice or hit ENTER to quit: || GOTO :EOF echo( & call :menu_[%choice%] GOTO:menuLOOP ::******************************************************************************************** :menu_[1] Start a Process cls & color 0B echo( Set /p "MyProcess=Enter the process name to start it> " echo( echo Le processus %MyProcess% est lance ... Start %MyProcess% GOTO :menuLOOP ::******************************************************************************************** :menu_[2] Kill a Process or Multi Processes Title Process Killer by Hackoo 2015 cls & color 0B echo( echo What process(es) do you want to kill ? echo( set /p "process=Enter the process name or processes names separated by a space> " cls & color 0C Title Killing "%process%" ... echo( echo Killing "%process%" ... echo( echo %date% *** %time% >> %TmpFile% For %%a in (%process%) Do Call :KillMyProcess %%a Cmd /U /C Type %TmpFile% > %Resultat% Start %Resultat% GOTO :menuLOOP ::******************************************************************************************** :menu_[3] Search for files cls & color 0A echo( Set /p "Location=Enter the folder location where do you want to serach> " cls & echo( echo You chose this location "%Location%" echo( Set /p "FileName=Enter the file name to looking for> " Mode con cols=90 lines=11 Set Tmp=Tmp.txt Set SearchResult=SearchResult.txt echo( & cls echo( & echo Please Wait for moment .... Searching for "%FileName%" on "%Location%" where /r "%Location%" "%FileName%" > %Tmp% ::Pour lire la liste en Unicode (Arabe) Cmd /U /C Type %Tmp% > %SearchResult% Del %Tmp% Start %SearchResult% GOTO :menuLOOP ::********************************************************************************************* :KillMyProcess Taskkill /IM "%~n1.exe" /F >> %TmpFile% 2>&1 echo ***************************************************************************** >> %TmpFile% exit /b ::********************************************************************************************* :EOF EXIT ```
Something like ``` :loopMain set /p "process=Entrer le(s) nom(s) de(s) processus> " if "%process:.exe=%"=="%process%" goto :loopMain ``` or ``` :loopMain set /p "process=Entrer le(s) nom(s) de(s) processus> " if /I not "%process:~-4%"==".exe" goto :loopMain ``` or `set "process=%process%.exe"` instead of `goto :loopMain`. Similar approach in case of multiple names typed in: check an correct user's input in a simple `for %%a in (%process%) do ...` loop.
30,823,681
I have this batch to kill some process typed of course by the user and it works 5/5 when the user for example typed **Calc.exe** with the extension, but my issue now is to improve this batch in order to add automatically with this program if the user has omitted to add extension **.exe** like **Calc** without extension **.exe** will not work. ``` @Echo off & cls Mode con cols=72 lines=7 Set TmpFile=TmpFile.txt Set Resultat=KillResult.txt If Exist %TmpFile% Del %TmpFile% If Exist %Resultat% Del %Resultat% ::******************************************************************************************** :Main Title Process Killer by Hackoo 2015 cls & color 0B echo. echo Quel(s) processus voulez-vous fermer ? echo. set/p "process=Entrer le(s) nom(s) de(s) processus> " cls & color 0C Title Killing "%process%" ... echo. echo Killing "%process%" ... echo. echo %date% *** %time% >> %TmpFile% For %%a in (%process%) Do Call :KillProcess %%a Cmd /U /C Type %TmpFile% > %Resultat% Start %Resultat% echo. Goto :Main ::********************************************************************************************* :KillProcess Taskkill /IM "%~1" /F >> %TmpFile% 2>&1 echo ***************************************************************************** >> %TmpFile% ::********************************************************************************************* ``` So i'm focusing on this piece of code but no success ! this my little try : ``` :KillProcess Set str=%~1 set str=%str:~-4% echo.%str% pause if %str%==".exe" (Taskkill /IM "%~1" /F >> %TmpFile% 2>&1) || (Taskkill /IM "%~1.exe" /F >> %TmpFile% 2>&1) ``` So how to do that in batch ? Thank you !
2015/06/13
[ "https://Stackoverflow.com/questions/30823681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3080770/" ]
If your files have never any other extension than `.exe`, you can use `"%~n1.exe"` to get the filename with `.exe`. `%~n1` is just the filename without extension. Than add `.exe`, and put quotes around it in case the filename contains a space. But this will fail if your executable is `example.program.exe`, and the user entered `example.program`. In this case the result of `"%~n1.exe"` will be `"example.exe"`. To avoid that, you have to check if the extension is `.exe`. You can use `%~x1` to get just the extension. See also [Command Line arguments (Parameters)](http://ss64.com/nt/syntax-args.html) for more information.
Just i want to share with you the hole script with a dynamic menu, perhaps it would be helpful for other people and thank you for all your contributions ;) (Translated some french words to english) ``` @Echo off & cls & color 0B Mode con cols=72 lines=10 Set TmpFile=TmpFile.txt Set Resultat=KillResult.txt If Exist %TmpFile% Del %TmpFile% If Exist %Resultat% Del %Resultat% :menuLOOP Cls & color 0B Title Process Starter and Killer by Hackoo 2015 echo. echo. ==========================Menu============================ echo. for /f "tokens=1,2,* delims=_ " %%A in ('"findstr /b /c:":menu_" "%~f0""') do echo. %%B %%C echo. echo. ========================================================== set choice= echo. & set /p choice=Make a choice or hit ENTER to quit: || GOTO :EOF echo. & call :menu_[%choice%] GOTO:menuLOOP ::******************************************************************************************** :menu_[1] Start a Process cls & color 0B echo. Set /p "MyProcess=Enter the process name to start it> " echo. echo Le processus %MyProcess% est lance ... Start %MyProcess% GOTO :menuLOOP ::******************************************************************************************** :menu_[2] Kill a Process or Multi Processes Title Process Killer by Hackoo 2015 cls & color 0B echo. echo What process do you want to kill ? echo. set/p "process=Enter the process name or processes names separated by a space> " cls & color 0C Title Killing "%process%" ... echo. echo Killing "%process%" ... echo. echo %date% *** %time% >> %TmpFile% For %%a in (%process%) Do Call :KillMyProcess %%a Cmd /U /C Type %TmpFile% > %Resultat% Start %Resultat% GOTO :menuLOOP ::********************************************************************************************* :KillMyProcess Taskkill /IM "%~n1.exe" /F >> %TmpFile% 2>&1 echo ***************************************************************************** >> %TmpFile% exit /b ::********************************************************************************************* :EOF EXIT ``` **EDIT 15/06/2015 : New Version** : Adding **Search for files** using the command **Where** ``` @Echo off & cls & color 0B Mode con cols=72 lines=11 Set TmpFile=TmpFile.txt Set Resultat=KillResult.txt If Exist %TmpFile% Del %TmpFile% If Exist %Resultat% Del %Resultat% :menuLOOP Mode con cols=72 lines=11 Cls & color 0B Title Process Starter and Killer by Hackoo 2015 echo( echo( ==========================Menu============================ echo( ::Suggestion de Walid : optimisation au niveau du parseur : utiliser deux tokens au lieu de trois for /f "tokens=2* delims=_ " %%A in ('"findstr /b /c:":menu_" "%~f0""') do echo( %%A %%B ::for /f "tokens=1,2,* delims=_ " %%A in ('"findstr /b /c:":menu_" "%~f0""') do echo( %%B %%C echo( echo( ========================================================== set choice= echo( & set /p choice=Make a choice or hit ENTER to quit: || GOTO :EOF echo( & call :menu_[%choice%] GOTO:menuLOOP ::******************************************************************************************** :menu_[1] Start a Process cls & color 0B echo( Set /p "MyProcess=Enter the process name to start it> " echo( echo Le processus %MyProcess% est lance ... Start %MyProcess% GOTO :menuLOOP ::******************************************************************************************** :menu_[2] Kill a Process or Multi Processes Title Process Killer by Hackoo 2015 cls & color 0B echo( echo What process(es) do you want to kill ? echo( set /p "process=Enter the process name or processes names separated by a space> " cls & color 0C Title Killing "%process%" ... echo( echo Killing "%process%" ... echo( echo %date% *** %time% >> %TmpFile% For %%a in (%process%) Do Call :KillMyProcess %%a Cmd /U /C Type %TmpFile% > %Resultat% Start %Resultat% GOTO :menuLOOP ::******************************************************************************************** :menu_[3] Search for files cls & color 0A echo( Set /p "Location=Enter the folder location where do you want to serach> " cls & echo( echo You chose this location "%Location%" echo( Set /p "FileName=Enter the file name to looking for> " Mode con cols=90 lines=11 Set Tmp=Tmp.txt Set SearchResult=SearchResult.txt echo( & cls echo( & echo Please Wait for moment .... Searching for "%FileName%" on "%Location%" where /r "%Location%" "%FileName%" > %Tmp% ::Pour lire la liste en Unicode (Arabe) Cmd /U /C Type %Tmp% > %SearchResult% Del %Tmp% Start %SearchResult% GOTO :menuLOOP ::********************************************************************************************* :KillMyProcess Taskkill /IM "%~n1.exe" /F >> %TmpFile% 2>&1 echo ***************************************************************************** >> %TmpFile% exit /b ::********************************************************************************************* :EOF EXIT ```
68,218,385
While deploying mule application in Anypoint studio getting below error : ``` org.mule.runtime.core.api.retry.policy.ConnectNotifier: Failed to connect/reconnect: Message Source Reconnection. Root Exception was: An error occurred while executing the operation: AUTHORIZE AGAINST BROKER. Cause: Can not login into broker - 429 - Too Many Requests ({ "status" : "failure", "statusMessage" : "Rate limit exceeded" }).. Type: class com.mulesoft.mq.restclient.api.exception.RestException ``` On queue in Anypoint platform at MQ option, we have used below configurations. ``` Message TTL - Default 7 Days so we kept as is Default Acknowledgement Timeout - Default 2 Minutes so we kept as is ```
2021/07/02
[ "https://Stackoverflow.com/questions/68218385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11053410/" ]
This issue is related to the fact that there maybe a client app which is using wrong authentification. Trying to authenticate several times with a wrong client id/ client secret blocks all request for the organisation for AMQ.
It usually means that there are too many concurrent operations from clients using the same credentials. It could be one application or more than one. Just in case also ensure that the application is using the [last release of the Anypoint MQ connector](https://docs.qax.mulesoft.com/release-notes/connector/anypoint-mq-connector-release-notes-mule-4).
53,737,159
In flutter app i am using Url\_launcher dependency to open phone application with content to dial using following function Url\_launcher.launch("tel:\\*5\*250#" ). It does open the application but # symbol is not dialed in there else everything works ok ... Any workaround to include # ???
2018/12/12
[ "https://Stackoverflow.com/questions/53737159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10761101/" ]
An HTTP stream wrapper does not support seeking. You have to download the bucket to a temporary file or variable. A simple `file_get_contents()` should do it: ``` $fileContent = file_get_contents('https://path/to/s3/file','rb'); // ... $pdf->setSourceFile(StreamReader::createByString($fileContent)); ```
For those who try to load the file from the same server (not apply to this case but could help others solve this error): change *<http://example.com/path/file.pdf>* to a local path like this */home/user/public\_html/path/file.pdf*
36,107,070
My goal is to put div with width=100vw, after that div there should be second div with width for example 300px (so that second div should be out of screen). I tried many things with float, display inline and so on, now I don't have any more ideas. ``` <div id="div1"></div> <div id="div2"></div> ``` Here is fiddle with example code <https://jsfiddle.net/kg5ea4sc/5/>
2016/03/19
[ "https://Stackoverflow.com/questions/36107070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3752988/" ]
This is really very straightforward using the [`Text::CSV`](https://p3rl.org/Text::CSV) to handle the nastiness of CSV data Here's an example, which works fine with the sample data you have shown. As long as your input file is plain ASCII and the rows are about the size you have shown it should work fine It prints its output to STDOUT, so you'll want to use a command-line redirect to put it into the file you want ``` use strict; use warnings 'all'; use Text::CSV; my $csv_file = 'DEM_Export.csv'; open my $in_fh, '<', $csv_file or die qq{Unable to open "$csv_file" for input: $!}; my $csv = Text::CSV->new({ eol => "\n" }); print "EASTING,NORTHING,ELEVATION\n"; while ( my $row = $csv->getline($in_fh) ) { $csv->print(\*STDOUT, [ map tr/,//dr, @$row[-2,-1,-3] ] ); } ``` ### output ``` 1455503.936,5173996.331,1058.83 ```
I guess I should have been braver and had a crack with Text::CSV to start with rather than asking a question. Many thanks to Сухой27 and choroba for pointing me in the right direction. Here is the code I ended up with. Probably not the tidiest. ``` use strict; use warnings; use Text::CSV; my $file = "DEM_Export.csv"; my $file2 = "DEM_ExportProcessed.csv"; open (FH2, '>', $file2) or die "Can't open file $file2: $!"; print FH2 "EASTING, NORTHING, ELEVATION,\n"; print "Starting file processing...\n"; my $csv = Text::CSV->new ({ binary => 1, eol => $/ }); open my $io, "<", $file or die "$file: $!"; while (my $row = $csv->getline ($io)) { my @fields = @$row; s/,//g for @fields[3..5]; my $string = sprintf("%.3f,%.3f,%.3f\n", $fields[4],$fields[5],$fields[3]); print FH2 $string; } print "Finished!"; close FH2; ``` Worked a treat! Thank you.
64,790,393
I am setting up a remote SSH interpreter in PyCharm, but when I try to select the interpreter's location on the remote machine, I get the following error: ``` Indicated packet length 1952805748 too large ``` How can I fix this? [![Screenshot of the error message](https://i.stack.imgur.com/jcRoN.png)](https://i.stack.imgur.com/jcRoN.png)
2020/11/11
[ "https://Stackoverflow.com/questions/64790393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2305095/" ]
I got this error because my `.bashrc` file printed to stdout. `.bashrc` is sourced when PyCharm connects to a remote interpreter's machine over SFTP. It has to be silent, otherwise it interferes with the SFTP protocol. The solution is to exit `.bashrc` early when not running interactively by putting this line at the top: ``` # If not running interactively, return early [[ $- == *i* ]] || return ``` Further reading: * [Indicated packet length 1953461345 too large (JetBrains forum)](https://intellij-support.jetbrains.com/hc/en-us/community/posts/360007648499-Indicated-packet-length-1953461345-too-large) * [SSHException: Indicated packet length 1097295214 too large (PyCharm issue tracker)](https://youtrack.jetbrains.com/issue/PY-38929)
I got a similar issues. I was pip updating a bunch of software in the cluster each time I logged in. So if pycharm runs the bashrc in the cluster each time it pushes and for some reason it processes it's output then this is an issue. I removed all lines that print in my bashrc in the remote/cluster.
64,790,393
I am setting up a remote SSH interpreter in PyCharm, but when I try to select the interpreter's location on the remote machine, I get the following error: ``` Indicated packet length 1952805748 too large ``` How can I fix this? [![Screenshot of the error message](https://i.stack.imgur.com/jcRoN.png)](https://i.stack.imgur.com/jcRoN.png)
2020/11/11
[ "https://Stackoverflow.com/questions/64790393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2305095/" ]
I got this error because my `.bashrc` file printed to stdout. `.bashrc` is sourced when PyCharm connects to a remote interpreter's machine over SFTP. It has to be silent, otherwise it interferes with the SFTP protocol. The solution is to exit `.bashrc` early when not running interactively by putting this line at the top: ``` # If not running interactively, return early [[ $- == *i* ]] || return ``` Further reading: * [Indicated packet length 1953461345 too large (JetBrains forum)](https://intellij-support.jetbrains.com/hc/en-us/community/posts/360007648499-Indicated-packet-length-1953461345-too-large) * [SSHException: Indicated packet length 1097295214 too large (PyCharm issue tracker)](https://youtrack.jetbrains.com/issue/PY-38929)
After a little bit check, I found the final solution for this problem. It is not a problem about `pycharm` or `intellij` actually. The underlying working principle of `sync` files to the remote server is using `sftp` to upload files and download files from a remote server. Maybe you have noticed that it works when using the `root` user to sync. For different people, they use different `sftp` utils like `putty`, `Linux client`, `Windows cmd`, `Power shell`, `xshell`, and so on. By using the command `sftp root@host` or `sftp user@host` (where the user is what you logged) in `xshell`. `xshell` will ask you to type in a password with a dialog. Both these commands will work. But when you use `windows cmd` by the same commands, here messages will jump out. ``` Received message too long 1399157792 Ensure the remote shell produces no output for non-interactive sessions. ``` And you will see, `pycharm` just forward this information. Here is a related question about the long message, [sftp gives an error: "Received message too long" and what is the reason?](https://unix.stackexchange.com/questions/61580/sftp-gives-an-error-received-message-too-long-and-what-is-the-reason) So, we need to change the `sftp server` configuration to `non-interactive` mode. By editing `/etc/ssh/sshd_config`, need you to have `root permission` or ask the server administrator to do. ```sh #Subsystem sftp /usr/lib/openssh/sftp-server Subsystem sftp internal-sftp ``` And restart the `sshd` service, by `systemctl restart sshd`
64,790,393
I am setting up a remote SSH interpreter in PyCharm, but when I try to select the interpreter's location on the remote machine, I get the following error: ``` Indicated packet length 1952805748 too large ``` How can I fix this? [![Screenshot of the error message](https://i.stack.imgur.com/jcRoN.png)](https://i.stack.imgur.com/jcRoN.png)
2020/11/11
[ "https://Stackoverflow.com/questions/64790393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2305095/" ]
After a little bit check, I found the final solution for this problem. It is not a problem about `pycharm` or `intellij` actually. The underlying working principle of `sync` files to the remote server is using `sftp` to upload files and download files from a remote server. Maybe you have noticed that it works when using the `root` user to sync. For different people, they use different `sftp` utils like `putty`, `Linux client`, `Windows cmd`, `Power shell`, `xshell`, and so on. By using the command `sftp root@host` or `sftp user@host` (where the user is what you logged) in `xshell`. `xshell` will ask you to type in a password with a dialog. Both these commands will work. But when you use `windows cmd` by the same commands, here messages will jump out. ``` Received message too long 1399157792 Ensure the remote shell produces no output for non-interactive sessions. ``` And you will see, `pycharm` just forward this information. Here is a related question about the long message, [sftp gives an error: "Received message too long" and what is the reason?](https://unix.stackexchange.com/questions/61580/sftp-gives-an-error-received-message-too-long-and-what-is-the-reason) So, we need to change the `sftp server` configuration to `non-interactive` mode. By editing `/etc/ssh/sshd_config`, need you to have `root permission` or ask the server administrator to do. ```sh #Subsystem sftp /usr/lib/openssh/sftp-server Subsystem sftp internal-sftp ``` And restart the `sshd` service, by `systemctl restart sshd`
I got a similar issues. I was pip updating a bunch of software in the cluster each time I logged in. So if pycharm runs the bashrc in the cluster each time it pushes and for some reason it processes it's output then this is an issue. I removed all lines that print in my bashrc in the remote/cluster.
317,671
Which phrase is the most common for a person who was born in Britain of the parents who were also born in Britain to identify his nationality? 1. "I am a citizen of Britain"? 2. "I am a subject of the British crown"? 3. "I am a British national"? And is there a better alternative?
2022/06/22
[ "https://ell.stackexchange.com/questions/317671", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/650/" ]
The first of your suggestions is best, but I would like to suggest a better alternative: > > I am a British citizen > > >
We need to be careful here. It may be better to ask this question on the Law site. There are actually six forms of British nationality - with different names. And the mere fact that a person is born in Britain, even if both parents were born in Britain does not necessarily, I feel sure, make them British, under any of the six categories. [This British government website tells you about the six categories, and what they are called.](https://www.gov.uk/types-of-british-nationality/british-citizenship) **However if it is simply a linguistic question - a person born in Britain of parents who were British citizens is "a British citizen". At least that's the form of words used in my passport.**
12,177
My Due is interfaces with a DAC which I need to update with freq 1MHz. The nice solution seems to be a timer interrupt. I found a thread here called "Arduino Due - creating an 8Mhz clock signal". I tried the following code to see if I can get 4MHz on P41. No luck. Any help will be greatly appreciated. Thanks. ``` volatile boolean l = false; void TC6_Handler() { TC_GetStatus(TC2, 0); digitalWrite(41, l = !l); } void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) { pmc_set_writeprotect(false); pmc_enable_periph_clk((uint32_t)irq); TC_Configure(tc, channel, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1| TC_CMR_ACPA_TOGGLE ); // RC compare TOGGLES TIOA); TC_SetRA(tc, channel, 1); //50% high, 50% low TC_SetRC(tc, channel, 1); PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); TC_Start(tc, channel); } void setup(){ pinMode(41,OUTPUT); startTimer(TC2, 0, TC6_IRQn); } void loop(){ } ```
2015/05/27
[ "https://arduino.stackexchange.com/questions/12177", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/10310/" ]
I'm not 100% certain without my Due in front of me to test this, but as far as I can see, you are configuring your clock to run at 42MHz with "TC\_CMR\_TCCLKS\_TIMER\_CLOCK1" and are getting the timer to trigger when the count is "1" with "TC\_SetRC(tc, channel, 1);", which would give you 42MHz, not 4MHz. Since the clock timer still increments during the TC6\_Handler() function, I'm guessing that the interrupt triggers a second time before it has exited the function the first time causing a hang. Try changing your code to "TC\_SetRC(tc, channel, 42000000 / 4000000);" to see if that works. Your interrupt will still be triggered every 10 ticks of the timer which will only give you 20 ticks of the CPU clock to do your work and exit. I suspect this may still be too little time to exit before the next interrupt is triggered. If you still don't get the result you want, try reducing the frequency considerably to see if your timer is actually getting configured correctly. I don't think you can get exactly 4MHz as the Due timer frequencies are not divisible by 4000000, unless my brain is a little fuzzy this morning and I'm missing something obvious... If you do need to optimise the code inside your handler so it can run faster, let me know and I'll post some ideas when I can get near my Due and my source code for reference. You could always check out this link that I used when I needed to understand how to set up a timer for my own projects: <http://2manyprojects.net/timer-interrupts> Should that link go dead before you have a chance to read up, this is the example source from that page I modified for my own purposes: ``` // These are the clock frequencies available to the timers /2,/8,/32,/128 // 84Mhz/2 = 42.000 MHz // 84Mhz/8 = 10.500 MHz // 84Mhz/32 = 2.625 MHz // 84Mhz/128 = 656.250 KHz // // 42Mhz/44.1Khz = 952.38 // 10.5Mhz/44.1Khz = 238.09 // 2.625Hmz/44.1Khz = 59.5 // 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds) // 84Mhz/44.1Khz = 1904 instructions per tick const int led_pin = 13; int state = false; int interruptCtr = 1; int S = 0; void setup() { pinMode(led_pin, OUTPUT); /* turn on the timer clock in the power management controller */ pmc_set_writeprotect(false); // disable write protection for pmc registers pmc_enable_periph_clk(ID_TC7); // enable peripheral clock TC7 /* we want wavesel 01 with RC */ TC_Configure(/* clock */TC2,/* channel */1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4); TC_SetRC(TC2, 1, 131200); TC_Start(TC2, 1); // enable timer interrupts on the timer TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS; // IER = interrupt enable register TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS; // IDR = interrupt disable register /* Enable the interrupt in the nested vector interrupt controller */ /* TC4_IRQn where 4 is the timer number * timer channels (3) + the channel number (=(1*3)+1) for timer1 channel1 */ NVIC_EnableIRQ(TC7_IRQn); } void loop() { // do nothing timer interrupts will handle the blinking; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // INTERRUPT HANDLERS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void TC7_Handler() { // We need to get the status to clear it and allow the interrupt to fire again TC_GetStatus(TC2, 1); state = !state; digitalWrite(led_pin, state); if( interruptCtr++ >= 6 ) { interruptCtr = 1; S = !S; // are we flashing S or O if( S ) // set time till next interrupt TC_SetRC(TC2, 1, 131200); // 131200 / 656000 = .2 seconds else TC_SetRC(TC2, 1, 656000); // 656000/ 656000 = 1 second } } ```
When I'm working with timers on my Due I always keep my code low level so my solution for your problem would be: ``` // These are the clock frequencies available to the timers /2,/8,/32,/128 // 84Mhz/2 = 42.000 MHz // 84Mhz/8 = 10.500 MHz // 84Mhz/32 = 2.625 MHz // 84Mhz/128 = 656.250 KHz // // 42Mhz/44.1Khz = 952.38 // 10.5Mhz/44.1Khz = 238.09 // 2.625Hmz/44.1Khz = 59.5 // 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds) #define SPEED(x) 42 * x // 84Mhz/44.1Khz = 1904 instructions per tick const int led_pin = 13; //PB27 int interruptCtr = 1; int S = 0; void setup() { pmc_set_writeprotect(false); // disable write protection for pmc registers /**always the first thing to do*/ // Enable pin 13 with direct port manipulation REG_PIOB_PER = 1<<27; REG_PIOB_OER = 1<<27; REG_PIOB_OWER = 1<<27; /* turn on the timer clock in the power management controller */ pmc_enable_periph_clk(ID_TC0); // enable peripheral clock TC0 //Enable interrupt in NVIC before starting interrupt NVIC_EnableIRQ(TC0_IRQn); //Wavesel on rising edge with timer clock1 (42MHz) REG_TC0_CMR0 = TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1; //Enabel RC compare interrupt REG_TC0_IER0 = TC_IER_CPCS; //Set the timer register c REG_TC0_RC0 = SPEED(200000); //SPEED() converts us to clock ticks //Start timer REG_TC0_CCR0 = TC_CCR_SWTRG | TC_CCR_CLKEN; } void loop() { // do nothing timer interrupts will handle the blinking; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // INTERRUPT HANDLERS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void TC0_Handler() { // We need to get the status to clear it and allow the interrupt to fire again REG_TC0_SR0; //get curretn pin state (REG_PIOB_ODSR & PIO_PB27) and invert it. AND this result with the pin bit to only set pin 27 to high/low REG_PIOB_ODSR = (~(REG_PIOB_ODSR & PIO_PB27)) & PIO_PB27; if( interruptCtr++ >= 6 ) { interruptCtr = 1; S = !S; // are we flashing S or O if( S ) // set time till next interrupt REG_TC0_RC0 = SPEED(200000); //0.2 seconds else REG_TC0_RC0 = SPEED(1000000); //1 second } } ``` With this code you should be able to increase the switching frequency to theoretically 42MHz. But due to the time the interrupt needs to run it will be reduced to something about 10MHz or less but even this is much higher than your 334KHz.
12,177
My Due is interfaces with a DAC which I need to update with freq 1MHz. The nice solution seems to be a timer interrupt. I found a thread here called "Arduino Due - creating an 8Mhz clock signal". I tried the following code to see if I can get 4MHz on P41. No luck. Any help will be greatly appreciated. Thanks. ``` volatile boolean l = false; void TC6_Handler() { TC_GetStatus(TC2, 0); digitalWrite(41, l = !l); } void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) { pmc_set_writeprotect(false); pmc_enable_periph_clk((uint32_t)irq); TC_Configure(tc, channel, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1| TC_CMR_ACPA_TOGGLE ); // RC compare TOGGLES TIOA); TC_SetRA(tc, channel, 1); //50% high, 50% low TC_SetRC(tc, channel, 1); PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); TC_Start(tc, channel); } void setup(){ pinMode(41,OUTPUT); startTimer(TC2, 0, TC6_IRQn); } void loop(){ } ```
2015/05/27
[ "https://arduino.stackexchange.com/questions/12177", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/10310/" ]
I'm not 100% certain without my Due in front of me to test this, but as far as I can see, you are configuring your clock to run at 42MHz with "TC\_CMR\_TCCLKS\_TIMER\_CLOCK1" and are getting the timer to trigger when the count is "1" with "TC\_SetRC(tc, channel, 1);", which would give you 42MHz, not 4MHz. Since the clock timer still increments during the TC6\_Handler() function, I'm guessing that the interrupt triggers a second time before it has exited the function the first time causing a hang. Try changing your code to "TC\_SetRC(tc, channel, 42000000 / 4000000);" to see if that works. Your interrupt will still be triggered every 10 ticks of the timer which will only give you 20 ticks of the CPU clock to do your work and exit. I suspect this may still be too little time to exit before the next interrupt is triggered. If you still don't get the result you want, try reducing the frequency considerably to see if your timer is actually getting configured correctly. I don't think you can get exactly 4MHz as the Due timer frequencies are not divisible by 4000000, unless my brain is a little fuzzy this morning and I'm missing something obvious... If you do need to optimise the code inside your handler so it can run faster, let me know and I'll post some ideas when I can get near my Due and my source code for reference. You could always check out this link that I used when I needed to understand how to set up a timer for my own projects: <http://2manyprojects.net/timer-interrupts> Should that link go dead before you have a chance to read up, this is the example source from that page I modified for my own purposes: ``` // These are the clock frequencies available to the timers /2,/8,/32,/128 // 84Mhz/2 = 42.000 MHz // 84Mhz/8 = 10.500 MHz // 84Mhz/32 = 2.625 MHz // 84Mhz/128 = 656.250 KHz // // 42Mhz/44.1Khz = 952.38 // 10.5Mhz/44.1Khz = 238.09 // 2.625Hmz/44.1Khz = 59.5 // 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds) // 84Mhz/44.1Khz = 1904 instructions per tick const int led_pin = 13; int state = false; int interruptCtr = 1; int S = 0; void setup() { pinMode(led_pin, OUTPUT); /* turn on the timer clock in the power management controller */ pmc_set_writeprotect(false); // disable write protection for pmc registers pmc_enable_periph_clk(ID_TC7); // enable peripheral clock TC7 /* we want wavesel 01 with RC */ TC_Configure(/* clock */TC2,/* channel */1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4); TC_SetRC(TC2, 1, 131200); TC_Start(TC2, 1); // enable timer interrupts on the timer TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS; // IER = interrupt enable register TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS; // IDR = interrupt disable register /* Enable the interrupt in the nested vector interrupt controller */ /* TC4_IRQn where 4 is the timer number * timer channels (3) + the channel number (=(1*3)+1) for timer1 channel1 */ NVIC_EnableIRQ(TC7_IRQn); } void loop() { // do nothing timer interrupts will handle the blinking; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // INTERRUPT HANDLERS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void TC7_Handler() { // We need to get the status to clear it and allow the interrupt to fire again TC_GetStatus(TC2, 1); state = !state; digitalWrite(led_pin, state); if( interruptCtr++ >= 6 ) { interruptCtr = 1; S = !S; // are we flashing S or O if( S ) // set time till next interrupt TC_SetRC(TC2, 1, 131200); // 131200 / 656000 = .2 seconds else TC_SetRC(TC2, 1, 656000); // 656000/ 656000 = 1 second } } ```
This works ``` int unsigned A[2500]; int unsigned S; void setup() { Serial.begin(9600); //pinMode(30, OUTPUT); REG_PIOB_OWER = 0xFFFFFFFF; // Enable PORT B REG_PIOB_OER = 0xFFFFFFFF; // Set PORT B as output port REG_PIOD_OWER = 0xFFFFFFFF; // Enable PORT D REG_PIOD_OER = 0xFFFFFFFF; // Set PORT D as output port REG_PIOC_OWER = 0xFFFFFFFF; // Enable PORT C REG_PIOC_OER = 0xFFFFFFFF; // Set PORT C as output port /* turn on the timer clock in the power management controller */ pmc_set_writeprotect(false); // disable write protection for pmc registers pmc_enable_periph_clk(ID_TC7); // enable peripheral clock TC7 /* we want wavesel 01 with RC */ TC_Configure(/* clock */TC2,/* channel */1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1); TC_SetRC(TC2, 1, 42);// 1 MHz TC_Start(TC2, 1); // enable timer interrupts on the timer TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS; // IER = interrupt enable register TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS; // IDR = interrupt disable register /* Enable the interrupt in the nested vector interrupt controller */ /* TC4_IRQn where 4 is the timer number * timer channels (3) + the channel number (=(1*3)+1) for timer1 channel1 */ //NVIC_EnableIRQ(TC7_IRQn); } void loop() { int unsigned MSBs = 0; int unsigned LSBs = 0; int unsigned C = 0; int unsigned B = 0; int unsigned i = 0; //int unsigned long B1 = 0; //int unsigned B2 = 0; int unsigned MSBMask = B11111111; MSBMask << 8; //Serial.println(base, DEC); //delay(100); //Serial.println(ratio, DEC); //delay(100); for(i=0; i<2500; i++) { //C = 20000/2*sin(2*PI*(90000/0.0025*i+10000)*i); C = 20000*sin(2*PI*i); // A[i] = sin(2*PI*(10+90/25*i)*1/1000); //A[1] = sin(2*PI*(10+90/25*i)*1/1000); MSBs = C >> 8; LSBs = C & MSBMask; //Serial.println(C, BIN); //Serial.println(MSBs, BIN); // Serial.println(LSBs, BIN); MSBs = MSBs << 12; LSBs = LSBs << 1; B = MSBs+LSBs; A[i] = B; //Serial.println(B, BIN); //Serial.println(A[i], BIN); //delay(100); } NVIC_EnableIRQ(TC7_IRQn); while(1){} } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // INTERRUPT HANDLERS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void TC7_Handler() { TC_GetStatus(TC2, 1);// We need to get the status to clear it and allow the interrupt to fire again //int i=0; REG_PIOD_CODR = 0x1 << 9;// clear pin 30 on due // REG_PIOD_CODR = 0x1 << 10;// clear pin 32 on due REG_PIOC_ODSR = A[S];//set outout pins to array entry REG_PIOD_SODR = 0x1 << 9;// set pin 30 on due, commanding DAC to take commended Analog output, S++; if(S>2500){S=0;} } ```
12,177
My Due is interfaces with a DAC which I need to update with freq 1MHz. The nice solution seems to be a timer interrupt. I found a thread here called "Arduino Due - creating an 8Mhz clock signal". I tried the following code to see if I can get 4MHz on P41. No luck. Any help will be greatly appreciated. Thanks. ``` volatile boolean l = false; void TC6_Handler() { TC_GetStatus(TC2, 0); digitalWrite(41, l = !l); } void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) { pmc_set_writeprotect(false); pmc_enable_periph_clk((uint32_t)irq); TC_Configure(tc, channel, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1| TC_CMR_ACPA_TOGGLE ); // RC compare TOGGLES TIOA); TC_SetRA(tc, channel, 1); //50% high, 50% low TC_SetRC(tc, channel, 1); PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); TC_Start(tc, channel); } void setup(){ pinMode(41,OUTPUT); startTimer(TC2, 0, TC6_IRQn); } void loop(){ } ```
2015/05/27
[ "https://arduino.stackexchange.com/questions/12177", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/10310/" ]
I'm not 100% certain without my Due in front of me to test this, but as far as I can see, you are configuring your clock to run at 42MHz with "TC\_CMR\_TCCLKS\_TIMER\_CLOCK1" and are getting the timer to trigger when the count is "1" with "TC\_SetRC(tc, channel, 1);", which would give you 42MHz, not 4MHz. Since the clock timer still increments during the TC6\_Handler() function, I'm guessing that the interrupt triggers a second time before it has exited the function the first time causing a hang. Try changing your code to "TC\_SetRC(tc, channel, 42000000 / 4000000);" to see if that works. Your interrupt will still be triggered every 10 ticks of the timer which will only give you 20 ticks of the CPU clock to do your work and exit. I suspect this may still be too little time to exit before the next interrupt is triggered. If you still don't get the result you want, try reducing the frequency considerably to see if your timer is actually getting configured correctly. I don't think you can get exactly 4MHz as the Due timer frequencies are not divisible by 4000000, unless my brain is a little fuzzy this morning and I'm missing something obvious... If you do need to optimise the code inside your handler so it can run faster, let me know and I'll post some ideas when I can get near my Due and my source code for reference. You could always check out this link that I used when I needed to understand how to set up a timer for my own projects: <http://2manyprojects.net/timer-interrupts> Should that link go dead before you have a chance to read up, this is the example source from that page I modified for my own purposes: ``` // These are the clock frequencies available to the timers /2,/8,/32,/128 // 84Mhz/2 = 42.000 MHz // 84Mhz/8 = 10.500 MHz // 84Mhz/32 = 2.625 MHz // 84Mhz/128 = 656.250 KHz // // 42Mhz/44.1Khz = 952.38 // 10.5Mhz/44.1Khz = 238.09 // 2.625Hmz/44.1Khz = 59.5 // 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds) // 84Mhz/44.1Khz = 1904 instructions per tick const int led_pin = 13; int state = false; int interruptCtr = 1; int S = 0; void setup() { pinMode(led_pin, OUTPUT); /* turn on the timer clock in the power management controller */ pmc_set_writeprotect(false); // disable write protection for pmc registers pmc_enable_periph_clk(ID_TC7); // enable peripheral clock TC7 /* we want wavesel 01 with RC */ TC_Configure(/* clock */TC2,/* channel */1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4); TC_SetRC(TC2, 1, 131200); TC_Start(TC2, 1); // enable timer interrupts on the timer TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS; // IER = interrupt enable register TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS; // IDR = interrupt disable register /* Enable the interrupt in the nested vector interrupt controller */ /* TC4_IRQn where 4 is the timer number * timer channels (3) + the channel number (=(1*3)+1) for timer1 channel1 */ NVIC_EnableIRQ(TC7_IRQn); } void loop() { // do nothing timer interrupts will handle the blinking; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // INTERRUPT HANDLERS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void TC7_Handler() { // We need to get the status to clear it and allow the interrupt to fire again TC_GetStatus(TC2, 1); state = !state; digitalWrite(led_pin, state); if( interruptCtr++ >= 6 ) { interruptCtr = 1; S = !S; // are we flashing S or O if( S ) // set time till next interrupt TC_SetRC(TC2, 1, 131200); // 131200 / 656000 = .2 seconds else TC_SetRC(TC2, 1, 656000); // 656000/ 656000 = 1 second } } ```
> > I need to update with freq 1MHz. ...No luck. > > > no kidding. think about interrupt overhead. and how much it takes away the processing power if you interrupt at 1 million times a second. think DMA if available on your chip. If not, think a faster chip or compromise on your 1Mhz expectation.
12,177
My Due is interfaces with a DAC which I need to update with freq 1MHz. The nice solution seems to be a timer interrupt. I found a thread here called "Arduino Due - creating an 8Mhz clock signal". I tried the following code to see if I can get 4MHz on P41. No luck. Any help will be greatly appreciated. Thanks. ``` volatile boolean l = false; void TC6_Handler() { TC_GetStatus(TC2, 0); digitalWrite(41, l = !l); } void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) { pmc_set_writeprotect(false); pmc_enable_periph_clk((uint32_t)irq); TC_Configure(tc, channel, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1| TC_CMR_ACPA_TOGGLE ); // RC compare TOGGLES TIOA); TC_SetRA(tc, channel, 1); //50% high, 50% low TC_SetRC(tc, channel, 1); PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); TC_Start(tc, channel); } void setup(){ pinMode(41,OUTPUT); startTimer(TC2, 0, TC6_IRQn); } void loop(){ } ```
2015/05/27
[ "https://arduino.stackexchange.com/questions/12177", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/10310/" ]
When I'm working with timers on my Due I always keep my code low level so my solution for your problem would be: ``` // These are the clock frequencies available to the timers /2,/8,/32,/128 // 84Mhz/2 = 42.000 MHz // 84Mhz/8 = 10.500 MHz // 84Mhz/32 = 2.625 MHz // 84Mhz/128 = 656.250 KHz // // 42Mhz/44.1Khz = 952.38 // 10.5Mhz/44.1Khz = 238.09 // 2.625Hmz/44.1Khz = 59.5 // 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds) #define SPEED(x) 42 * x // 84Mhz/44.1Khz = 1904 instructions per tick const int led_pin = 13; //PB27 int interruptCtr = 1; int S = 0; void setup() { pmc_set_writeprotect(false); // disable write protection for pmc registers /**always the first thing to do*/ // Enable pin 13 with direct port manipulation REG_PIOB_PER = 1<<27; REG_PIOB_OER = 1<<27; REG_PIOB_OWER = 1<<27; /* turn on the timer clock in the power management controller */ pmc_enable_periph_clk(ID_TC0); // enable peripheral clock TC0 //Enable interrupt in NVIC before starting interrupt NVIC_EnableIRQ(TC0_IRQn); //Wavesel on rising edge with timer clock1 (42MHz) REG_TC0_CMR0 = TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1; //Enabel RC compare interrupt REG_TC0_IER0 = TC_IER_CPCS; //Set the timer register c REG_TC0_RC0 = SPEED(200000); //SPEED() converts us to clock ticks //Start timer REG_TC0_CCR0 = TC_CCR_SWTRG | TC_CCR_CLKEN; } void loop() { // do nothing timer interrupts will handle the blinking; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // INTERRUPT HANDLERS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void TC0_Handler() { // We need to get the status to clear it and allow the interrupt to fire again REG_TC0_SR0; //get curretn pin state (REG_PIOB_ODSR & PIO_PB27) and invert it. AND this result with the pin bit to only set pin 27 to high/low REG_PIOB_ODSR = (~(REG_PIOB_ODSR & PIO_PB27)) & PIO_PB27; if( interruptCtr++ >= 6 ) { interruptCtr = 1; S = !S; // are we flashing S or O if( S ) // set time till next interrupt REG_TC0_RC0 = SPEED(200000); //0.2 seconds else REG_TC0_RC0 = SPEED(1000000); //1 second } } ``` With this code you should be able to increase the switching frequency to theoretically 42MHz. But due to the time the interrupt needs to run it will be reduced to something about 10MHz or less but even this is much higher than your 334KHz.
This works ``` int unsigned A[2500]; int unsigned S; void setup() { Serial.begin(9600); //pinMode(30, OUTPUT); REG_PIOB_OWER = 0xFFFFFFFF; // Enable PORT B REG_PIOB_OER = 0xFFFFFFFF; // Set PORT B as output port REG_PIOD_OWER = 0xFFFFFFFF; // Enable PORT D REG_PIOD_OER = 0xFFFFFFFF; // Set PORT D as output port REG_PIOC_OWER = 0xFFFFFFFF; // Enable PORT C REG_PIOC_OER = 0xFFFFFFFF; // Set PORT C as output port /* turn on the timer clock in the power management controller */ pmc_set_writeprotect(false); // disable write protection for pmc registers pmc_enable_periph_clk(ID_TC7); // enable peripheral clock TC7 /* we want wavesel 01 with RC */ TC_Configure(/* clock */TC2,/* channel */1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1); TC_SetRC(TC2, 1, 42);// 1 MHz TC_Start(TC2, 1); // enable timer interrupts on the timer TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS; // IER = interrupt enable register TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS; // IDR = interrupt disable register /* Enable the interrupt in the nested vector interrupt controller */ /* TC4_IRQn where 4 is the timer number * timer channels (3) + the channel number (=(1*3)+1) for timer1 channel1 */ //NVIC_EnableIRQ(TC7_IRQn); } void loop() { int unsigned MSBs = 0; int unsigned LSBs = 0; int unsigned C = 0; int unsigned B = 0; int unsigned i = 0; //int unsigned long B1 = 0; //int unsigned B2 = 0; int unsigned MSBMask = B11111111; MSBMask << 8; //Serial.println(base, DEC); //delay(100); //Serial.println(ratio, DEC); //delay(100); for(i=0; i<2500; i++) { //C = 20000/2*sin(2*PI*(90000/0.0025*i+10000)*i); C = 20000*sin(2*PI*i); // A[i] = sin(2*PI*(10+90/25*i)*1/1000); //A[1] = sin(2*PI*(10+90/25*i)*1/1000); MSBs = C >> 8; LSBs = C & MSBMask; //Serial.println(C, BIN); //Serial.println(MSBs, BIN); // Serial.println(LSBs, BIN); MSBs = MSBs << 12; LSBs = LSBs << 1; B = MSBs+LSBs; A[i] = B; //Serial.println(B, BIN); //Serial.println(A[i], BIN); //delay(100); } NVIC_EnableIRQ(TC7_IRQn); while(1){} } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // INTERRUPT HANDLERS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void TC7_Handler() { TC_GetStatus(TC2, 1);// We need to get the status to clear it and allow the interrupt to fire again //int i=0; REG_PIOD_CODR = 0x1 << 9;// clear pin 30 on due // REG_PIOD_CODR = 0x1 << 10;// clear pin 32 on due REG_PIOC_ODSR = A[S];//set outout pins to array entry REG_PIOD_SODR = 0x1 << 9;// set pin 30 on due, commanding DAC to take commended Analog output, S++; if(S>2500){S=0;} } ```
12,177
My Due is interfaces with a DAC which I need to update with freq 1MHz. The nice solution seems to be a timer interrupt. I found a thread here called "Arduino Due - creating an 8Mhz clock signal". I tried the following code to see if I can get 4MHz on P41. No luck. Any help will be greatly appreciated. Thanks. ``` volatile boolean l = false; void TC6_Handler() { TC_GetStatus(TC2, 0); digitalWrite(41, l = !l); } void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) { pmc_set_writeprotect(false); pmc_enable_periph_clk((uint32_t)irq); TC_Configure(tc, channel, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1| TC_CMR_ACPA_TOGGLE ); // RC compare TOGGLES TIOA); TC_SetRA(tc, channel, 1); //50% high, 50% low TC_SetRC(tc, channel, 1); PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); TC_Start(tc, channel); } void setup(){ pinMode(41,OUTPUT); startTimer(TC2, 0, TC6_IRQn); } void loop(){ } ```
2015/05/27
[ "https://arduino.stackexchange.com/questions/12177", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/10310/" ]
When I'm working with timers on my Due I always keep my code low level so my solution for your problem would be: ``` // These are the clock frequencies available to the timers /2,/8,/32,/128 // 84Mhz/2 = 42.000 MHz // 84Mhz/8 = 10.500 MHz // 84Mhz/32 = 2.625 MHz // 84Mhz/128 = 656.250 KHz // // 42Mhz/44.1Khz = 952.38 // 10.5Mhz/44.1Khz = 238.09 // 2.625Hmz/44.1Khz = 59.5 // 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds) #define SPEED(x) 42 * x // 84Mhz/44.1Khz = 1904 instructions per tick const int led_pin = 13; //PB27 int interruptCtr = 1; int S = 0; void setup() { pmc_set_writeprotect(false); // disable write protection for pmc registers /**always the first thing to do*/ // Enable pin 13 with direct port manipulation REG_PIOB_PER = 1<<27; REG_PIOB_OER = 1<<27; REG_PIOB_OWER = 1<<27; /* turn on the timer clock in the power management controller */ pmc_enable_periph_clk(ID_TC0); // enable peripheral clock TC0 //Enable interrupt in NVIC before starting interrupt NVIC_EnableIRQ(TC0_IRQn); //Wavesel on rising edge with timer clock1 (42MHz) REG_TC0_CMR0 = TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1; //Enabel RC compare interrupt REG_TC0_IER0 = TC_IER_CPCS; //Set the timer register c REG_TC0_RC0 = SPEED(200000); //SPEED() converts us to clock ticks //Start timer REG_TC0_CCR0 = TC_CCR_SWTRG | TC_CCR_CLKEN; } void loop() { // do nothing timer interrupts will handle the blinking; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // INTERRUPT HANDLERS //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void TC0_Handler() { // We need to get the status to clear it and allow the interrupt to fire again REG_TC0_SR0; //get curretn pin state (REG_PIOB_ODSR & PIO_PB27) and invert it. AND this result with the pin bit to only set pin 27 to high/low REG_PIOB_ODSR = (~(REG_PIOB_ODSR & PIO_PB27)) & PIO_PB27; if( interruptCtr++ >= 6 ) { interruptCtr = 1; S = !S; // are we flashing S or O if( S ) // set time till next interrupt REG_TC0_RC0 = SPEED(200000); //0.2 seconds else REG_TC0_RC0 = SPEED(1000000); //1 second } } ``` With this code you should be able to increase the switching frequency to theoretically 42MHz. But due to the time the interrupt needs to run it will be reduced to something about 10MHz or less but even this is much higher than your 334KHz.
> > I need to update with freq 1MHz. ...No luck. > > > no kidding. think about interrupt overhead. and how much it takes away the processing power if you interrupt at 1 million times a second. think DMA if available on your chip. If not, think a faster chip or compromise on your 1Mhz expectation.
18,578,718
I'm trying to create a link from mysql results: ``` while($row = $result->fetch_assoc()){ echo "<a class=post_link href=http://localhost:8888/search.php?loc=".$row['loc']."&lt=".$row['lt']."&lg=".$row['lg'].">".$row['loc'].": ".$row['lt'].", ".$row['lg']."</a><br>" ; } ``` The problem is, when 'loc' row contains more than one word. Is it possible to detect when it has two or more words and insert '%' between them, or I need to use different technique?
2013/09/02
[ "https://Stackoverflow.com/questions/18578718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2699508/" ]
Use the PHP function `urlencode()`. This function is convenient when encoding a string to be used in a query part of a URL. More information: <http://php.net/manual/en/function.urlencode.php> ``` while($row = $result->fetch_assoc()){ echo "<a class=post_link href=http://localhost:8888/search.php?loc=".urlencode($row['loc'])."&lt=".$row['lt']."&lg=".$row['lg'].">".$row['loc'].": ".$row['lt'].", ".$row['lg']."</a><br>" ; } ```
Or you can use ereg\_replace, since urlencode (supposedly, no personal experience) sometimes acts a bit weird: ``` while($row = $result->fetch_assoc()){ $loc = ereg_replace("[ \t\n\r]+", "%", $row['loc']); echo "<a class=post_link href=http://localhost:8888/search.php?loc=".$loc."&lt=".$row['lt']."&lg=".$row['lg'].">".$row['loc'].": ".$row['lt'].", ".$row['lg']."</a><br>" ; } ``` This also replaces new line and tab characters.
68,997,651
I'm using the `getifaddrs` Linux function to get information about network interfaces on a Linux machine running Debian Jessie kernel 3.16.0. Among the info I want to know is network statistics (packets dropped, sent, etc.) which, as the manpage for getifaddrs states, is contained in a `rtnl_link_stats` structure pointed to by `ifaddrs::ifa_addr::ifa_data` when `ifaddrs::if_addr::sa_family` is set to `AF_PACKET`. This works well for ethernet interfaces, but does not work for CAN interfaces on the machine, because `ifaddrs::ifa_addr` is NULL and thus `AF_PACKET` is never returned for any CAN interface. The following C++ code... ``` #include <ifaddrs.h> #include <linux/if_link.h> #include <net/if.h> #include <sys/socket.h> #include <sys/types.h> #include <cstdio> #include <cstdlib> int main() { ifaddrs *addrs; if (getifaddrs(&addrs) == -1) { perror("getifaddrs"); return EXIT_FAILURE; } printf("AF_PACKET: %d\n\n", (int)AF_PACKET); for (auto addr = addrs; addr != NULL; addr = addr->ifa_next) { if (addr->ifa_addr != nullptr) { printf("%s: family: %d\n", addr->ifa_name, (int)addr->ifa_addr->sa_family); } else { printf("%s: family: none\n", addr->ifa_name); } } freeifaddrs(addrs); return EXIT_SUCCESS; } ``` ...prints out ``` AF_PACKET: 17 lo: family: 17 eth0: family: 17 eth1: family: 17 can0: family: none can1: family: none lo: family: 2 eth1: family: 2 lo: family: 10 eth1: family: 10 ``` which means that neither of the CAN interfaces have any family set. The `ifconfig` command has no problem showing the information, though: ``` can0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 UP RUNNING NOARP MTU:16 Metric:1 RX packets:28481588 errors:0 dropped:8729866 overruns:0 frame:0 TX packets:8168599 errors:2292404 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:10 RX bytes:211108099 (201.3 MiB) TX bytes:64828340 (61.8 MiB) Interrupt:17 can1 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 UP RUNNING NOARP MTU:16 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:10 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) Interrupt:17 ``` (note I included only the output for CAN interfaces, not the rest) What am I doing wrong? What is the correct way to retrieve packet stats for CAN interfaces?
2021/08/31
[ "https://Stackoverflow.com/questions/68997651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13083573/" ]
Thanks to @sawdust for pointing me to the answer. The problem was that I'm running an ubuntu docker container in Manjaro (Arch) OS, and on Arch ttyUSB is owned by uucp (group id 987), while on ubuntu it's owned by dialout (group id 20). So when mounting /dev/ttyUSB0 into the docker container, it's still owned by gid 987, but in the ubuntu environment this group id is not dialout, so even when adding the user to dialout, the user has no permission to open the serial port. A quickfix would be to create a group with the correct gid and add your user to it: ``` docker exec -it --user 0 test sh -c "groupadd -g 987 ttyusb && usermod -a -G ttyusb user" ``` but it's not a complete solution, as this will only make it work for your combination of host OS and docker OS, and not necessarily for other user with different environments.
If it is still relevant, the following solution did work for me: ``` docker run --gpus all -it --privileged --name [container_name] \ -v "$(pwd)/..":/home/app \ -v /dev/bus/usb:/dev/bus/usb \ -v /dev/ttyACM0:/dev/ttyACM0 \ [image_container_name] bash ``` Note that you might not need in your application the "gpu" so you can remove that flag "--gpus all"
68,997,651
I'm using the `getifaddrs` Linux function to get information about network interfaces on a Linux machine running Debian Jessie kernel 3.16.0. Among the info I want to know is network statistics (packets dropped, sent, etc.) which, as the manpage for getifaddrs states, is contained in a `rtnl_link_stats` structure pointed to by `ifaddrs::ifa_addr::ifa_data` when `ifaddrs::if_addr::sa_family` is set to `AF_PACKET`. This works well for ethernet interfaces, but does not work for CAN interfaces on the machine, because `ifaddrs::ifa_addr` is NULL and thus `AF_PACKET` is never returned for any CAN interface. The following C++ code... ``` #include <ifaddrs.h> #include <linux/if_link.h> #include <net/if.h> #include <sys/socket.h> #include <sys/types.h> #include <cstdio> #include <cstdlib> int main() { ifaddrs *addrs; if (getifaddrs(&addrs) == -1) { perror("getifaddrs"); return EXIT_FAILURE; } printf("AF_PACKET: %d\n\n", (int)AF_PACKET); for (auto addr = addrs; addr != NULL; addr = addr->ifa_next) { if (addr->ifa_addr != nullptr) { printf("%s: family: %d\n", addr->ifa_name, (int)addr->ifa_addr->sa_family); } else { printf("%s: family: none\n", addr->ifa_name); } } freeifaddrs(addrs); return EXIT_SUCCESS; } ``` ...prints out ``` AF_PACKET: 17 lo: family: 17 eth0: family: 17 eth1: family: 17 can0: family: none can1: family: none lo: family: 2 eth1: family: 2 lo: family: 10 eth1: family: 10 ``` which means that neither of the CAN interfaces have any family set. The `ifconfig` command has no problem showing the information, though: ``` can0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 UP RUNNING NOARP MTU:16 Metric:1 RX packets:28481588 errors:0 dropped:8729866 overruns:0 frame:0 TX packets:8168599 errors:2292404 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:10 RX bytes:211108099 (201.3 MiB) TX bytes:64828340 (61.8 MiB) Interrupt:17 can1 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 UP RUNNING NOARP MTU:16 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:10 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B) Interrupt:17 ``` (note I included only the output for CAN interfaces, not the rest) What am I doing wrong? What is the correct way to retrieve packet stats for CAN interfaces?
2021/08/31
[ "https://Stackoverflow.com/questions/68997651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13083573/" ]
Thanks to @sawdust for pointing me to the answer. The problem was that I'm running an ubuntu docker container in Manjaro (Arch) OS, and on Arch ttyUSB is owned by uucp (group id 987), while on ubuntu it's owned by dialout (group id 20). So when mounting /dev/ttyUSB0 into the docker container, it's still owned by gid 987, but in the ubuntu environment this group id is not dialout, so even when adding the user to dialout, the user has no permission to open the serial port. A quickfix would be to create a group with the correct gid and add your user to it: ``` docker exec -it --user 0 test sh -c "groupadd -g 987 ttyusb && usermod -a -G ttyusb user" ``` but it's not a complete solution, as this will only make it work for your combination of host OS and docker OS, and not necessarily for other user with different environments.
using "docker run --rm --group-add 986 -it --privileged ... " resolves. if you call groups, show error but works. $ groups dcuser dialout staff groups: cannot find name for group ID 986 986
35,321,078
I have a tab-separated text file that has 4 columns of data: ``` StudentId Student Name GPA Major ``` I have to write a shell command that will stores the student names that are CS majors to another file. I used `grep cs students.txt` which works to display just students that are `cs`, but I do not know how to then take just the student's names and save them to a file.
2016/02/10
[ "https://Stackoverflow.com/questions/35321078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4774214/" ]
Assuming that your input file is tab-separated (so you can have spaces in names): ``` awk -F'\t' '$4 == "cs" { print $2 }' <infile >outfile ``` This matches column 4 (major) against "cs", and prints column 2 when it is an exact match.
Got it: ``` grep cs students.txt | cut -f2 >file1 ```
536,439
When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". `std::vector` was definitely an advanced topic, something you could learn about if you *really* wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory. Today, everywhere I look I see RAII and [SFINAE](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error) and STL and Boost and, well, Modern C++. Even people who are just getting started with the language seem to be taught these concepts almost from day 1. My question is, is this simply because I'm only seeing the "best", that is, the questions here on SO, and on other programming sites that tend to attract beginners (gamedev.net), or is this actually representative of the C++ community as a whole? Is modern C++ really becoming the default? Rather than being some fancy thing the experts write about, is it becoming "the way C++ just is"? Or am I just unable to see the thousands of people who still learn "C with classes" and write their own dynamic arrays instead of using `std::vector`, and do memory management by manually calling new/delete from their top-level code? As much as I want to believe it, it seems incredible if the C++ community as a whole has evolved so much in basically a few years. What are your experiences and impressions? (disclaimer: Someone not familiar with C++ might misinterpret the title as asking whether C++ is gaining popularity versus other languages. That's not my question. "Modern C++" is a common name for a dialect or programming style within C++, named after the book "[Modern C++ Design: Generic Programming and Design Patterns Applied](https://rads.stackoverflow.com/amzn/click/com/0201704315)", and I'm solely interested in this versus "old C++". So no need to tell me that C++'s time is past, and we should all use Python ;))
2009/02/11
[ "https://Stackoverflow.com/questions/536439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33213/" ]
I am one of these guys who learned how to work with the STL and heard a lot about RAII and good C++ programming practices from day 1. Looks like some of the most recommended books for learning C++ today (like Accelerated C++ and the Effective C++ series) focus on using STL tools instead of rolling up your own stuff, and also give lots of "rules" for effective (or "modern") programming. But talking with friends I also noted some companies still work with "C with Classes", not "Modern C++". Maybe the culture proposed by the authors and users of the "Modern C++" will prevail someday :)
In my experience it vastly depends on the age of the software product/project. Most new projects that I am aware of do use modern C++ (RAII, STL, Boost). However, there are many C++ projects that are more than 10 years old, and you don't see modern C++ there. Also, keep in mind that some of the most popular STL implementations were pretty much broken until maybe 5 years ago (MSVC < 7.0 and GNU < 3.00)
536,439
When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". `std::vector` was definitely an advanced topic, something you could learn about if you *really* wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory. Today, everywhere I look I see RAII and [SFINAE](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error) and STL and Boost and, well, Modern C++. Even people who are just getting started with the language seem to be taught these concepts almost from day 1. My question is, is this simply because I'm only seeing the "best", that is, the questions here on SO, and on other programming sites that tend to attract beginners (gamedev.net), or is this actually representative of the C++ community as a whole? Is modern C++ really becoming the default? Rather than being some fancy thing the experts write about, is it becoming "the way C++ just is"? Or am I just unable to see the thousands of people who still learn "C with classes" and write their own dynamic arrays instead of using `std::vector`, and do memory management by manually calling new/delete from their top-level code? As much as I want to believe it, it seems incredible if the C++ community as a whole has evolved so much in basically a few years. What are your experiences and impressions? (disclaimer: Someone not familiar with C++ might misinterpret the title as asking whether C++ is gaining popularity versus other languages. That's not my question. "Modern C++" is a common name for a dialect or programming style within C++, named after the book "[Modern C++ Design: Generic Programming and Design Patterns Applied](https://rads.stackoverflow.com/amzn/click/com/0201704315)", and I'm solely interested in this versus "old C++". So no need to tell me that C++'s time is past, and we should all use Python ;))
2009/02/11
[ "https://Stackoverflow.com/questions/536439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33213/" ]
In my C++ jobs, I've found the modern features to be increasingly used, and more people asked me about them in phone screenings and interviews. As far as I can tell, they're catching on. I learned C++ originally as something like C with Classes; although the language had advanced far beyond that, the books I read and people I worked with were firmly stuck on "old C++". RAII something people would think about, rather than automatically do, and I remember reading some of the early articles on the problems of exception safety. As pointed out, there's new books out now. Many of the old ones are still relevant, but they increasingly seem to be full of explaining why obviously bad ideas are bad. (Similarly, it's hard for modern readers to understand how revolutionary Freud's ideas of an unconscious mind were, since it's now conventional wisdom.) Stroustrup just came out with a textbook, *Programming: Principles and Practice Using C++*. I bought it because I haven't yet failed to learn good stuff from a book of Stroustrup's, but haven't gotten past the first few chapters. So far, all I can say is that I approve of the way he's starting out, and it's at least a good introduction to how C++ should be used.
I think the biggest barrier I've encountered is toolchain support, especially on cross-platform projects. Until a few years ago, it was common to see build notes saying "x platform needs STLport to work because their compiler is borked". Even now, I see issues with people trying to use multiple third-party dependencies tied to different versions of BOOST. This makes linking impossible, meaning you have to go back and rebuild your deps from scratch. Now that just about everyone has stopped using MSVC++ 6, the STLport mess is behind us. But as soon as TR1 is out the door, we're back to "which versions of which environments support it and get it right" and once again this will slow adoption. I work on a project begun in C (not C++) in 1992. Deploying modern practices across the legacy codebase would be impossible. Likewise I work on another project that is much closer to the cutting edge of C++ language.
536,439
When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". `std::vector` was definitely an advanced topic, something you could learn about if you *really* wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory. Today, everywhere I look I see RAII and [SFINAE](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error) and STL and Boost and, well, Modern C++. Even people who are just getting started with the language seem to be taught these concepts almost from day 1. My question is, is this simply because I'm only seeing the "best", that is, the questions here on SO, and on other programming sites that tend to attract beginners (gamedev.net), or is this actually representative of the C++ community as a whole? Is modern C++ really becoming the default? Rather than being some fancy thing the experts write about, is it becoming "the way C++ just is"? Or am I just unable to see the thousands of people who still learn "C with classes" and write their own dynamic arrays instead of using `std::vector`, and do memory management by manually calling new/delete from their top-level code? As much as I want to believe it, it seems incredible if the C++ community as a whole has evolved so much in basically a few years. What are your experiences and impressions? (disclaimer: Someone not familiar with C++ might misinterpret the title as asking whether C++ is gaining popularity versus other languages. That's not my question. "Modern C++" is a common name for a dialect or programming style within C++, named after the book "[Modern C++ Design: Generic Programming and Design Patterns Applied](https://rads.stackoverflow.com/amzn/click/com/0201704315)", and I'm solely interested in this versus "old C++". So no need to tell me that C++'s time is past, and we should all use Python ;))
2009/02/11
[ "https://Stackoverflow.com/questions/536439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33213/" ]
In my experience it vastly depends on the age of the software product/project. Most new projects that I am aware of do use modern C++ (RAII, STL, Boost). However, there are many C++ projects that are more than 10 years old, and you don't see modern C++ there. Also, keep in mind that some of the most popular STL implementations were pretty much broken until maybe 5 years ago (MSVC < 7.0 and GNU < 3.00)
Many teams I've been on and heard about consider the big "are we using exceptions?" question. This is code for "are we using modern C++?" Once you aren't using exceptions, you are precluded from using the full power of the language and its libraries. But many older codebases are exception-less, and it is perceived to be difficult to shoehorn exceptions into a codebase that doesn't expect them, or into a team that doesn't know how to use them, so the answer in such cases is often 'no.' In my experience, modern C++ needs someone who is passionate about it on the team, who can't stand the sight of anything less, to push for it. It also needs to overcome the objections of those who want it to be more like the legacy code. While I don't think that old-C++ codebases are going away very quickly, I do believe there are more of these passionate people in the world than there were five years ago. They face the same uphill battle they faced five years ago, but they are more likely to find kindred spirits.
536,439
When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". `std::vector` was definitely an advanced topic, something you could learn about if you *really* wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory. Today, everywhere I look I see RAII and [SFINAE](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error) and STL and Boost and, well, Modern C++. Even people who are just getting started with the language seem to be taught these concepts almost from day 1. My question is, is this simply because I'm only seeing the "best", that is, the questions here on SO, and on other programming sites that tend to attract beginners (gamedev.net), or is this actually representative of the C++ community as a whole? Is modern C++ really becoming the default? Rather than being some fancy thing the experts write about, is it becoming "the way C++ just is"? Or am I just unable to see the thousands of people who still learn "C with classes" and write their own dynamic arrays instead of using `std::vector`, and do memory management by manually calling new/delete from their top-level code? As much as I want to believe it, it seems incredible if the C++ community as a whole has evolved so much in basically a few years. What are your experiences and impressions? (disclaimer: Someone not familiar with C++ might misinterpret the title as asking whether C++ is gaining popularity versus other languages. That's not my question. "Modern C++" is a common name for a dialect or programming style within C++, named after the book "[Modern C++ Design: Generic Programming and Design Patterns Applied](https://rads.stackoverflow.com/amzn/click/com/0201704315)", and I'm solely interested in this versus "old C++". So no need to tell me that C++'s time is past, and we should all use Python ;))
2009/02/11
[ "https://Stackoverflow.com/questions/536439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33213/" ]
In my experience it vastly depends on the age of the software product/project. Most new projects that I am aware of do use modern C++ (RAII, STL, Boost). However, there are many C++ projects that are more than 10 years old, and you don't see modern C++ there. Also, keep in mind that some of the most popular STL implementations were pretty much broken until maybe 5 years ago (MSVC < 7.0 and GNU < 3.00)
The best book for learning C++. "Accelerated C++" by Koenig & Moo, teaches what you describe as modern C++, so I guess most people these days are using it. For those of us that have been using C++ for quite a while (since the mid 80s in my case), modern C++ is a great relief from the tedious tasks of writing our own arrays, strings, hash tables (repeat ad nauseam).
536,439
When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". `std::vector` was definitely an advanced topic, something you could learn about if you *really* wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory. Today, everywhere I look I see RAII and [SFINAE](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error) and STL and Boost and, well, Modern C++. Even people who are just getting started with the language seem to be taught these concepts almost from day 1. My question is, is this simply because I'm only seeing the "best", that is, the questions here on SO, and on other programming sites that tend to attract beginners (gamedev.net), or is this actually representative of the C++ community as a whole? Is modern C++ really becoming the default? Rather than being some fancy thing the experts write about, is it becoming "the way C++ just is"? Or am I just unable to see the thousands of people who still learn "C with classes" and write their own dynamic arrays instead of using `std::vector`, and do memory management by manually calling new/delete from their top-level code? As much as I want to believe it, it seems incredible if the C++ community as a whole has evolved so much in basically a few years. What are your experiences and impressions? (disclaimer: Someone not familiar with C++ might misinterpret the title as asking whether C++ is gaining popularity versus other languages. That's not my question. "Modern C++" is a common name for a dialect or programming style within C++, named after the book "[Modern C++ Design: Generic Programming and Design Patterns Applied](https://rads.stackoverflow.com/amzn/click/com/0201704315)", and I'm solely interested in this versus "old C++". So no need to tell me that C++'s time is past, and we should all use Python ;))
2009/02/11
[ "https://Stackoverflow.com/questions/536439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33213/" ]
I think you just had a bad experience starting off. You need to get yourself [Scott Meyers](http://www.aristeia.com/) Effective C++ books. I started on C++ in anger in 1999, my team lead made me sit and read Effective C++ and More Effective C++ before I was allowed to check in ANY code. Most of his advice is on the lines of "Don't use this *feature*, but if you must, keep *this* in mind" If you follow his advice you'll write good or "Modern" C++. He has a book on STL now too, but that I haven't read.
While working on the project I am presently involved with, there's a lot of C++ code which has evolved over a significant period of time (over 10 years now). The evolution you speak of is clearly visible there: the older code is often "C with classes" - raw pointers, `char*` strings and use of associated C functions, arrays etc; newer code uses ATL smart pointers and such to manage resources, but still sticks to hand-coded loops most of the time, and iterator is a rare sight; and the newest one is chock-full of STL containers, algorithms, `shared_ptr` (including custom deleters to manage handles etc), heavily genericized function and class templates, and so on. Most traditional "C with classes" coding techniques, such as raw unencapsulated pointers with manual lifetime management, are very much frowned upon in code reviews these days. Judging by this, it seems that your observation is accurate. The most recent development seems to be a fad for C++0x lambdas - which has a positive side in that it also tilts the balance in favor of using standard algorithms over hand-coded loops, since now you can have all your code inline with algorithms as well.
536,439
When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". `std::vector` was definitely an advanced topic, something you could learn about if you *really* wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory. Today, everywhere I look I see RAII and [SFINAE](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error) and STL and Boost and, well, Modern C++. Even people who are just getting started with the language seem to be taught these concepts almost from day 1. My question is, is this simply because I'm only seeing the "best", that is, the questions here on SO, and on other programming sites that tend to attract beginners (gamedev.net), or is this actually representative of the C++ community as a whole? Is modern C++ really becoming the default? Rather than being some fancy thing the experts write about, is it becoming "the way C++ just is"? Or am I just unable to see the thousands of people who still learn "C with classes" and write their own dynamic arrays instead of using `std::vector`, and do memory management by manually calling new/delete from their top-level code? As much as I want to believe it, it seems incredible if the C++ community as a whole has evolved so much in basically a few years. What are your experiences and impressions? (disclaimer: Someone not familiar with C++ might misinterpret the title as asking whether C++ is gaining popularity versus other languages. That's not my question. "Modern C++" is a common name for a dialect or programming style within C++, named after the book "[Modern C++ Design: Generic Programming and Design Patterns Applied](https://rads.stackoverflow.com/amzn/click/com/0201704315)", and I'm solely interested in this versus "old C++". So no need to tell me that C++'s time is past, and we should all use Python ;))
2009/02/11
[ "https://Stackoverflow.com/questions/536439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33213/" ]
Here's how I think things have evolved. The first generation of C++ programmers were C programmers, who were in fact using C++ as C with classes. Plus, the STL wasn't in place yet, so that's what C++ essentially was. When the STL came out, that advanced things, but most of the people writing books, putting together curricula, and teaching classes had learned C first, then that extra C++ stuff, so the second generation learned from that perspective. As another answer noted, if you're comfortable writing regular for loops, changing to use `std::for_each` doesn't buy you much except the warm fuzzy feeling that you're doing things the "modern" way. Now, we have instructors and book writers who have been using the whole of C++, and getting their instructions from that perspective, such as Koenig & Moo's Accelerated C++ and Stroustrup's new textbook. So we don't learn `char*` then `std::strings`. It's an interesting lesson in how long it takes for "legacy" methods to be replaced, especially when they have a track record of effectiveness.
I think you just had a bad experience starting off. You need to get yourself [Scott Meyers](http://www.aristeia.com/) Effective C++ books. I started on C++ in anger in 1999, my team lead made me sit and read Effective C++ and More Effective C++ before I was allowed to check in ANY code. Most of his advice is on the lines of "Don't use this *feature*, but if you must, keep *this* in mind" If you follow his advice you'll write good or "Modern" C++. He has a book on STL now too, but that I haven't read.
536,439
When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". `std::vector` was definitely an advanced topic, something you could learn about if you *really* wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory. Today, everywhere I look I see RAII and [SFINAE](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error) and STL and Boost and, well, Modern C++. Even people who are just getting started with the language seem to be taught these concepts almost from day 1. My question is, is this simply because I'm only seeing the "best", that is, the questions here on SO, and on other programming sites that tend to attract beginners (gamedev.net), or is this actually representative of the C++ community as a whole? Is modern C++ really becoming the default? Rather than being some fancy thing the experts write about, is it becoming "the way C++ just is"? Or am I just unable to see the thousands of people who still learn "C with classes" and write their own dynamic arrays instead of using `std::vector`, and do memory management by manually calling new/delete from their top-level code? As much as I want to believe it, it seems incredible if the C++ community as a whole has evolved so much in basically a few years. What are your experiences and impressions? (disclaimer: Someone not familiar with C++ might misinterpret the title as asking whether C++ is gaining popularity versus other languages. That's not my question. "Modern C++" is a common name for a dialect or programming style within C++, named after the book "[Modern C++ Design: Generic Programming and Design Patterns Applied](https://rads.stackoverflow.com/amzn/click/com/0201704315)", and I'm solely interested in this versus "old C++". So no need to tell me that C++'s time is past, and we should all use Python ;))
2009/02/11
[ "https://Stackoverflow.com/questions/536439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33213/" ]
In the days of Windows 3.1, C was the standard. When C++ hit the developer market and later became ANSI standard, it was the new hotness. It popularized the OOP acronym and some of the basic design patterns using polymorphism. Now, with the greater acceptance of low-barrier-to-entry managed platforms, like C#/.NET, there's less of a reason to use C++. So much of the developer base will have a choice and let's be honest: C++ is a bear to learn for a novice. With C#, you can just run with it. That leaves really only the platforms that NEED C++ and the die-hard C++ evangelists to continue practicing the art. This is the community that needs and wants all the layers of abstraction that is considered "Modern C++". So yes, I believe "Modern C++", as you state it, is becoming more prevalent. Albeit, it's prevalent with a different audience than has used it in the past.
I have looked at [C++ Jobs on indeed](http://www.indeed.com/jobtrends?q=c%2B%2B+Qt%2C+c%2B%2B+boost%2C+c%2B%2B+stl%2C+c%2B%2B+mfc&l=) and "modern" libraries are more and more used in job descriptions, MFC which is quite an "old-style" c++ library is less used.
536,439
When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". `std::vector` was definitely an advanced topic, something you could learn about if you *really* wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory. Today, everywhere I look I see RAII and [SFINAE](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error) and STL and Boost and, well, Modern C++. Even people who are just getting started with the language seem to be taught these concepts almost from day 1. My question is, is this simply because I'm only seeing the "best", that is, the questions here on SO, and on other programming sites that tend to attract beginners (gamedev.net), or is this actually representative of the C++ community as a whole? Is modern C++ really becoming the default? Rather than being some fancy thing the experts write about, is it becoming "the way C++ just is"? Or am I just unable to see the thousands of people who still learn "C with classes" and write their own dynamic arrays instead of using `std::vector`, and do memory management by manually calling new/delete from their top-level code? As much as I want to believe it, it seems incredible if the C++ community as a whole has evolved so much in basically a few years. What are your experiences and impressions? (disclaimer: Someone not familiar with C++ might misinterpret the title as asking whether C++ is gaining popularity versus other languages. That's not my question. "Modern C++" is a common name for a dialect or programming style within C++, named after the book "[Modern C++ Design: Generic Programming and Design Patterns Applied](https://rads.stackoverflow.com/amzn/click/com/0201704315)", and I'm solely interested in this versus "old C++". So no need to tell me that C++'s time is past, and we should all use Python ;))
2009/02/11
[ "https://Stackoverflow.com/questions/536439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33213/" ]
Here's how I think things have evolved. The first generation of C++ programmers were C programmers, who were in fact using C++ as C with classes. Plus, the STL wasn't in place yet, so that's what C++ essentially was. When the STL came out, that advanced things, but most of the people writing books, putting together curricula, and teaching classes had learned C first, then that extra C++ stuff, so the second generation learned from that perspective. As another answer noted, if you're comfortable writing regular for loops, changing to use `std::for_each` doesn't buy you much except the warm fuzzy feeling that you're doing things the "modern" way. Now, we have instructors and book writers who have been using the whole of C++, and getting their instructions from that perspective, such as Koenig & Moo's Accelerated C++ and Stroustrup's new textbook. So we don't learn `char*` then `std::strings`. It's an interesting lesson in how long it takes for "legacy" methods to be replaced, especially when they have a track record of effectiveness.
I am one of these guys who learned how to work with the STL and heard a lot about RAII and good C++ programming practices from day 1. Looks like some of the most recommended books for learning C++ today (like Accelerated C++ and the Effective C++ series) focus on using STL tools instead of rolling up your own stuff, and also give lots of "rules" for effective (or "modern") programming. But talking with friends I also noted some companies still work with "C with Classes", not "Modern C++". Maybe the culture proposed by the authors and users of the "Modern C++" will prevail someday :)
536,439
When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". `std::vector` was definitely an advanced topic, something you could learn about if you *really* wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory. Today, everywhere I look I see RAII and [SFINAE](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error) and STL and Boost and, well, Modern C++. Even people who are just getting started with the language seem to be taught these concepts almost from day 1. My question is, is this simply because I'm only seeing the "best", that is, the questions here on SO, and on other programming sites that tend to attract beginners (gamedev.net), or is this actually representative of the C++ community as a whole? Is modern C++ really becoming the default? Rather than being some fancy thing the experts write about, is it becoming "the way C++ just is"? Or am I just unable to see the thousands of people who still learn "C with classes" and write their own dynamic arrays instead of using `std::vector`, and do memory management by manually calling new/delete from their top-level code? As much as I want to believe it, it seems incredible if the C++ community as a whole has evolved so much in basically a few years. What are your experiences and impressions? (disclaimer: Someone not familiar with C++ might misinterpret the title as asking whether C++ is gaining popularity versus other languages. That's not my question. "Modern C++" is a common name for a dialect or programming style within C++, named after the book "[Modern C++ Design: Generic Programming and Design Patterns Applied](https://rads.stackoverflow.com/amzn/click/com/0201704315)", and I'm solely interested in this versus "old C++". So no need to tell me that C++'s time is past, and we should all use Python ;))
2009/02/11
[ "https://Stackoverflow.com/questions/536439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33213/" ]
In my experience (Spanish University), unfortunately, the norm is to not to consider languages in itself. They use the easiest languages to teach programming (i.e. Java), because it is supposed to be easy for teachers and students, and then they use C for the OS classes and such. C++ is introduced very slightly (at any rate at any course), just to provide a C with classes. They don't get into boost or even STL. I think keeping up with all the characteristics and way of thinking of C++ is costly for both teachers and students. How many of C++ programmers here know enough of all the Boost libraries to use them to give a better solution or to design it? One has to have an interest in keeping up with all the new libraries and idioms. However, as I said, it seems that programming in general (and programming languages in particular) are not taken too seriously, as it seems to be a temporal assignment when they start a job, then forget how to program as they go up in the enterprise tree. Many enterprises here, and the University itself, have the feel that programming can be done by anybody. If you follow this philosophy, then for most people I know, C++ will always be "C with classes". Regards,
Before answering such a question, you'd have to agree on what "Modern" is. This not likely to happen, since "Modern" is a poorly defined word, and means different things to different people. The title of Alexandrescu's book (Modern C++ Design) doesn't really help either, since it is largely a book on Template Metaprogramming, which is a specific area of C++ but by no means the only one. For me, "Modern C++" != "Template Metaprogramming". I would say C++'s features on top of C would fall into these categories: * Classes (Constructors, Destructors, RAII, Dynamic Casting and RTTI) * Exceptions * References * Data Structures and Algorithms in the standard library (STL) * iostreams * Simple class and function templates * Template metaprogramming None of these are particularly modern, since they've all been around nearly 10 years or more. Most of these features are useful and will allow you to be more productive than straight C for many use cases. A good programmer should and will use all of them in a decent sized project, but one of these things is not like the other: Template Metaprogramming. The short answer to template metaprogramming is just say no. Unfortunately to some people it's synonymous to "Modern C++ programming", due to the book, but in the end it creates more problems than it solves. Unless C++ develops better generic programming mechanisms like reflection, it will be ill suited for generic programming, and higher level languages like Python will be a better fit for those use cases. For that and many other reasons, see the [C++ FQA](http://yosefk.com/c++fqa/ "C++ FQA")
536,439
When I first learned C++ 6-7 years ago, what I learned was basically "C with Classes". `std::vector` was definitely an advanced topic, something you could learn about if you *really* wanted to. And there was certainly no one telling me that destructors could be harnessed to help manage memory. Today, everywhere I look I see RAII and [SFINAE](http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error) and STL and Boost and, well, Modern C++. Even people who are just getting started with the language seem to be taught these concepts almost from day 1. My question is, is this simply because I'm only seeing the "best", that is, the questions here on SO, and on other programming sites that tend to attract beginners (gamedev.net), or is this actually representative of the C++ community as a whole? Is modern C++ really becoming the default? Rather than being some fancy thing the experts write about, is it becoming "the way C++ just is"? Or am I just unable to see the thousands of people who still learn "C with classes" and write their own dynamic arrays instead of using `std::vector`, and do memory management by manually calling new/delete from their top-level code? As much as I want to believe it, it seems incredible if the C++ community as a whole has evolved so much in basically a few years. What are your experiences and impressions? (disclaimer: Someone not familiar with C++ might misinterpret the title as asking whether C++ is gaining popularity versus other languages. That's not my question. "Modern C++" is a common name for a dialect or programming style within C++, named after the book "[Modern C++ Design: Generic Programming and Design Patterns Applied](https://rads.stackoverflow.com/amzn/click/com/0201704315)", and I'm solely interested in this versus "old C++". So no need to tell me that C++'s time is past, and we should all use Python ;))
2009/02/11
[ "https://Stackoverflow.com/questions/536439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33213/" ]
I wouldn't say that std::vector qualifies as "modern" these days. It is really basic. Generally my impression is that people have gained some experience with modern C++ style and sobered up a little. Just to take a simple example, STL for\_each was interesting but in practice it does not add a terrible lot of value over a plain C loop. It is harder to debug and sometimes does not provide the best performance. Also the constructs for functional programming in current STL are generally very cumbersome, especially if you got experience from a real functional language like ML.
Before answering such a question, you'd have to agree on what "Modern" is. This not likely to happen, since "Modern" is a poorly defined word, and means different things to different people. The title of Alexandrescu's book (Modern C++ Design) doesn't really help either, since it is largely a book on Template Metaprogramming, which is a specific area of C++ but by no means the only one. For me, "Modern C++" != "Template Metaprogramming". I would say C++'s features on top of C would fall into these categories: * Classes (Constructors, Destructors, RAII, Dynamic Casting and RTTI) * Exceptions * References * Data Structures and Algorithms in the standard library (STL) * iostreams * Simple class and function templates * Template metaprogramming None of these are particularly modern, since they've all been around nearly 10 years or more. Most of these features are useful and will allow you to be more productive than straight C for many use cases. A good programmer should and will use all of them in a decent sized project, but one of these things is not like the other: Template Metaprogramming. The short answer to template metaprogramming is just say no. Unfortunately to some people it's synonymous to "Modern C++ programming", due to the book, but in the end it creates more problems than it solves. Unless C++ develops better generic programming mechanisms like reflection, it will be ill suited for generic programming, and higher level languages like Python will be a better fit for those use cases. For that and many other reasons, see the [C++ FQA](http://yosefk.com/c++fqa/ "C++ FQA")
71,554
I just completed a haloform reaction experiment, using acetophenone and sodium hypochlorite to form benzoic acid and chloroform. My lab report has a question regarding balancing the equation of the reaction. I have been working on it for quite a while, and I can't figure out how to do it. I've tried looking up methods but too many atoms are reliant on too many molecules! Can someone help with this question and explain how to do it so I can really understand this process? [![redox reaction](https://i.stack.imgur.com/TRx1V.jpg)](https://i.stack.imgur.com/TRx1V.jpg) I need to be able to identify the limiting reactant as well, which relies on the molar ratio of the reactant to the product, so I really need to know how to do this.
2017/03/30
[ "https://chemistry.stackexchange.com/questions/71554", "https://chemistry.stackexchange.com", "https://chemistry.stackexchange.com/users/43220/" ]
As you noted, you need to find the limiting reactant. This is most of the time done by taking the one with a 1:1 ratio of educt:product. So in this case, the $\ce{ROCH\_3}$. So you take that once. Now you see immediately that you need 2 $\ce{Na}$ on the right side, so you can put a 2 in front of the $\ce{NaOH}$. You have two $\ce{X}$ on the left, but 4 on the right, so put a 2 in front of the left one. Now count all your atoms. Subtract them from each other: You have $a \* \ce{H}$ on the left and $b \* \ce{H}$ on the right. if $a-b=0$ its balanced. Do that for every reactant and you're done. There are of course more strictly formulated methods, but in my time I noticed that a straightforward approach with a little thinking can be applied most universally without having to memorize some formulas.
The coefficients should be 1 3 4 1 1 3 3, from left to right. The limiting reagent is acetophenone. Used this website to find the answer. <http://www.chem.ucalgary.ca/courses/350/Carey5th/Ch18/ch18-3-2b.html> -- a fellow owl ;)
48,335,609
In the mailer template i want to generate correct url for the path public/system/test.png Suppose in the mailer template ``` <%= link_to k, "/system/test.png" %> <br /> ``` how can i generate the full path such as ``` https://www.example.com/system/test.png ``` I appreciate any help! Thanks!
2018/01/19
[ "https://Stackoverflow.com/questions/48335609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/734861/" ]
Try this: ``` <%= link_to k, root_url + 'system/test.png' %> ```
You can add assets host in your production.rb ``` config.action_controller.asset_host = 'https://www.example.com' ``` You can fine more about assets [here](http://api.rubyonrails.org/classes/ActionView/Helpers/AssetUrlHelper.html)
48,335,609
In the mailer template i want to generate correct url for the path public/system/test.png Suppose in the mailer template ``` <%= link_to k, "/system/test.png" %> <br /> ``` how can i generate the full path such as ``` https://www.example.com/system/test.png ``` I appreciate any help! Thanks!
2018/01/19
[ "https://Stackoverflow.com/questions/48335609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/734861/" ]
Try this: ``` <%= link_to k, root_url + 'system/test.png' %> ```
You could use `<%= link_to k, "#{Rails.root}/system/test.png" %>` Hope this is what you are looking for.
48,335,609
In the mailer template i want to generate correct url for the path public/system/test.png Suppose in the mailer template ``` <%= link_to k, "/system/test.png" %> <br /> ``` how can i generate the full path such as ``` https://www.example.com/system/test.png ``` I appreciate any help! Thanks!
2018/01/19
[ "https://Stackoverflow.com/questions/48335609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/734861/" ]
Try this: ``` <%= link_to k, root_url + 'system/test.png' %> ```
``` <%= link_to k, asset_url('/public/system/test.jpeg')%> ``` this will generate link as:- ``` https://example.com/public/system/test.jpeg ``` and your html code will generate like this: -- ``` <a href="https://example.com/public/system/test.jpeg">k</a> ```
48,335,609
In the mailer template i want to generate correct url for the path public/system/test.png Suppose in the mailer template ``` <%= link_to k, "/system/test.png" %> <br /> ``` how can i generate the full path such as ``` https://www.example.com/system/test.png ``` I appreciate any help! Thanks!
2018/01/19
[ "https://Stackoverflow.com/questions/48335609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/734861/" ]
Try this: ``` <%= link_to k, root_url + 'system/test.png' %> ```
Try to the following This code is tested ``` <%= link_to image_tag("/system/test.png"), root_url %> ``` `image_tag` by default located the public folder and `root_url` will redirect to the home page after click image Or solution two ``` <a href="<%= root_url %>"> <%= image_tag "#{Rails.root}/public/system/test.png" %> </a> ```
48,335,609
In the mailer template i want to generate correct url for the path public/system/test.png Suppose in the mailer template ``` <%= link_to k, "/system/test.png" %> <br /> ``` how can i generate the full path such as ``` https://www.example.com/system/test.png ``` I appreciate any help! Thanks!
2018/01/19
[ "https://Stackoverflow.com/questions/48335609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/734861/" ]
You can add assets host in your production.rb ``` config.action_controller.asset_host = 'https://www.example.com' ``` You can fine more about assets [here](http://api.rubyonrails.org/classes/ActionView/Helpers/AssetUrlHelper.html)
You could use `<%= link_to k, "#{Rails.root}/system/test.png" %>` Hope this is what you are looking for.
48,335,609
In the mailer template i want to generate correct url for the path public/system/test.png Suppose in the mailer template ``` <%= link_to k, "/system/test.png" %> <br /> ``` how can i generate the full path such as ``` https://www.example.com/system/test.png ``` I appreciate any help! Thanks!
2018/01/19
[ "https://Stackoverflow.com/questions/48335609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/734861/" ]
You can add assets host in your production.rb ``` config.action_controller.asset_host = 'https://www.example.com' ``` You can fine more about assets [here](http://api.rubyonrails.org/classes/ActionView/Helpers/AssetUrlHelper.html)
Try to the following This code is tested ``` <%= link_to image_tag("/system/test.png"), root_url %> ``` `image_tag` by default located the public folder and `root_url` will redirect to the home page after click image Or solution two ``` <a href="<%= root_url %>"> <%= image_tag "#{Rails.root}/public/system/test.png" %> </a> ```
48,335,609
In the mailer template i want to generate correct url for the path public/system/test.png Suppose in the mailer template ``` <%= link_to k, "/system/test.png" %> <br /> ``` how can i generate the full path such as ``` https://www.example.com/system/test.png ``` I appreciate any help! Thanks!
2018/01/19
[ "https://Stackoverflow.com/questions/48335609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/734861/" ]
``` <%= link_to k, asset_url('/public/system/test.jpeg')%> ``` this will generate link as:- ``` https://example.com/public/system/test.jpeg ``` and your html code will generate like this: -- ``` <a href="https://example.com/public/system/test.jpeg">k</a> ```
You could use `<%= link_to k, "#{Rails.root}/system/test.png" %>` Hope this is what you are looking for.