qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
4,082,537
I am kind of stuck with a simple type check on a generic helper class I am writing. The idea will be clear if you take a look at the source code. It works nice for normal things, like DateTime and bool, but I got a problem with generics. How do I check for e.g. ObservableCollection < **something** > and count it. I do not want to be able to render everything (its a debug control after all), but if there is a collection, I want to know if it has elements. Tried some variations, but none worked. Can't be that hard, the search words just suck (generic, list, collection) - all not very google friendly :-) **[EDIT]** Ok, I played around a little bit, and I get closer. There is however a strange problem with the GetValue() function. If you take a look at the example class, the one string property is working fine, the one set in the constructor shows "NULL" - how can that be. Oh, btw. I am working in Windows Phone 7 - but this should not affect such basic stuff, should it? **[END EDIT]** Updated version of my function: ``` private static FrameworkElement CreateContent(System.Reflection.PropertyInfo propertyInfo, object parent) { var propValue = propertyInfo.GetValue(parent, null); // NULL if (propValue == null) return new TextBlock() { Text = "NULL" }; // Simple cases if (propertyInfo.PropertyType == typeof(int)) return new TextBlock() { Text = propValue.ToString() }; if (propertyInfo.PropertyType == typeof(DateTime)) return new TextBlock() { Text = ((DateTime)propValue).ToShortTimeString() }; if (propertyInfo.PropertyType == typeof(string)) return new TextBlock() { Text = propValue.ToString() }; // More exotic cases if (typeof(IList).IsAssignableFrom(propValue.GetType())) return new TextBlock() {Text = ((IList) propValue).Count.ToString()}; if (typeof(ICollection).IsAssignableFrom(propValue.GetType())) return new TextBlock() { Text = ((ICollection)propValue).Count.ToString() }; if (typeof(IEnumerable).IsAssignableFrom(propValue.GetType())) return new TextBlock() { Text = ((IEnumerable)propValue).Cast<object>().Count().ToString() }; // If all fails, at least tell me the type return new TextBlock() {Text = propertyInfo.PropertyType.Name}; } ``` Very very strange test case (look for StringPropertyA and B) ``` public class DebugService : ServiceBase, IDebugService { public DebugService(IUnityContainerPhone container) : base(container) { DateTimeProperty = DateTime.Now; StringEmptyProperty = ""; StringObsColl = new ObservableCollection<string>() {"A", "B", "C"}; StringList = new List<string>(){"X", "Y", "Z"}; StringPropertyB = "Will not show up"; } public override string Description { get { return "Does nothing, for debug purposes"; } } public DateTime DateTimeProperty { get; private set; } public int IntProperty { get { return 23; } } public string StringPropertyA { get {return "Is OK";} } public string StringPropertyB { get; private set; } public string StringEmptyProperty { get; private set; } public string StringNullProperty { get; private set; } public ObservableCollection<string> StringObsColl { get; private set; } public IList<string> StringList { get; private set; } } ```
2010/11/02
[ "https://Stackoverflow.com/questions/4082537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109646/" ]
Is it necessary to go this route? ``` if (parent is DateTime) return new TextBlock() { Text = ((DateTime)parent).ToShortTimeString() }; if (parent is ICollection) return new TextBlock() { Text = ((ICollection)parent).Count }; if (parent is IEnumerable) return new TextBlock() { Text = ((IEnumerable)parent).Count() }; //assumes System.Linq ... return new TextBlock() { Text = parent.ToString() }; ```
I think you have your IsAssignablefrom method call backwards. I think you need to say `typeof(IList).IsAssignableFrom(propertyInfo.PropertyType)` Regardless, I would retrieve the object directly and reflect on it, rather than reflecting on the type of the property. This way, if you have a property of type object, that returns a list, it will display properly in your debug control. ``` private static FrameworkElement CreateContent(System.Reflection.PropertyInfo propertyInfo, object parent) { object propValue = propertyInfo.GetValue(parent, null); if (propValue is ICollection) return new TextBlock() { Text = ((ICollection)propValue).Count.ToString() }; else if (propValue is ...) return new TextBlock() { Text = ... }; else return new TextBlock() { Text = propValue.ToString() }; } ```
4,082,537
I am kind of stuck with a simple type check on a generic helper class I am writing. The idea will be clear if you take a look at the source code. It works nice for normal things, like DateTime and bool, but I got a problem with generics. How do I check for e.g. ObservableCollection < **something** > and count it. I do not want to be able to render everything (its a debug control after all), but if there is a collection, I want to know if it has elements. Tried some variations, but none worked. Can't be that hard, the search words just suck (generic, list, collection) - all not very google friendly :-) **[EDIT]** Ok, I played around a little bit, and I get closer. There is however a strange problem with the GetValue() function. If you take a look at the example class, the one string property is working fine, the one set in the constructor shows "NULL" - how can that be. Oh, btw. I am working in Windows Phone 7 - but this should not affect such basic stuff, should it? **[END EDIT]** Updated version of my function: ``` private static FrameworkElement CreateContent(System.Reflection.PropertyInfo propertyInfo, object parent) { var propValue = propertyInfo.GetValue(parent, null); // NULL if (propValue == null) return new TextBlock() { Text = "NULL" }; // Simple cases if (propertyInfo.PropertyType == typeof(int)) return new TextBlock() { Text = propValue.ToString() }; if (propertyInfo.PropertyType == typeof(DateTime)) return new TextBlock() { Text = ((DateTime)propValue).ToShortTimeString() }; if (propertyInfo.PropertyType == typeof(string)) return new TextBlock() { Text = propValue.ToString() }; // More exotic cases if (typeof(IList).IsAssignableFrom(propValue.GetType())) return new TextBlock() {Text = ((IList) propValue).Count.ToString()}; if (typeof(ICollection).IsAssignableFrom(propValue.GetType())) return new TextBlock() { Text = ((ICollection)propValue).Count.ToString() }; if (typeof(IEnumerable).IsAssignableFrom(propValue.GetType())) return new TextBlock() { Text = ((IEnumerable)propValue).Cast<object>().Count().ToString() }; // If all fails, at least tell me the type return new TextBlock() {Text = propertyInfo.PropertyType.Name}; } ``` Very very strange test case (look for StringPropertyA and B) ``` public class DebugService : ServiceBase, IDebugService { public DebugService(IUnityContainerPhone container) : base(container) { DateTimeProperty = DateTime.Now; StringEmptyProperty = ""; StringObsColl = new ObservableCollection<string>() {"A", "B", "C"}; StringList = new List<string>(){"X", "Y", "Z"}; StringPropertyB = "Will not show up"; } public override string Description { get { return "Does nothing, for debug purposes"; } } public DateTime DateTimeProperty { get; private set; } public int IntProperty { get { return 23; } } public string StringPropertyA { get {return "Is OK";} } public string StringPropertyB { get; private set; } public string StringEmptyProperty { get; private set; } public string StringNullProperty { get; private set; } public ObservableCollection<string> StringObsColl { get; private set; } public IList<string> StringList { get; private set; } } ```
2010/11/02
[ "https://Stackoverflow.com/questions/4082537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109646/" ]
``` propertyInfo.PropertyType.IsAssignableFrom(typeof(IList)) ``` This is a classic mistake (I think it's so common because of the `value is IList` syntax). What you actually want is: ``` typeof(IList).IsAssignableFrom(propertyInfo.PropertyType) ``` There are other issues to consider, such as whether you want to support other types of collections (not all collections will implement IList.) If you're specifically interested in getting access to the value as a generic collection, a helpful hint is that you can use `typeof(IList<>)` to get the non-specialized generic type.
I think you have your IsAssignablefrom method call backwards. I think you need to say `typeof(IList).IsAssignableFrom(propertyInfo.PropertyType)` Regardless, I would retrieve the object directly and reflect on it, rather than reflecting on the type of the property. This way, if you have a property of type object, that returns a list, it will display properly in your debug control. ``` private static FrameworkElement CreateContent(System.Reflection.PropertyInfo propertyInfo, object parent) { object propValue = propertyInfo.GetValue(parent, null); if (propValue is ICollection) return new TextBlock() { Text = ((ICollection)propValue).Count.ToString() }; else if (propValue is ...) return new TextBlock() { Text = ... }; else return new TextBlock() { Text = propValue.ToString() }; } ```
34,876,623
I got part of a sentence in my database like : ``` beautiful house close to the beach this peaceful touristic area under a beautiful tree behind the property ``` I would like to select sentence that does not contain a list of word like 'to','a' Wanted result: ``` this peaceful touristic area behind the property ``` I figured that I had to use something like ``` SELECT ID_sentence FROM sentence WHERE semi_sentence NOT RLIKE '(.*)[^A-Za-z]to[^A-Za-z](.*)' AND semi_sentence NOT RLIKE '(.*)[^A-Za-z]a[^A-Za-z](.*)' ``` but I can't get the regex right and I should probably group the list under one regex
2016/01/19
[ "https://Stackoverflow.com/questions/34876623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5809722/" ]
You can use *word boundaries* applied to the *group* of two alternatives listed after `|` operator: ``` WHERE semi_sentence NOT RLIKE '[[:<:]](to|a)[[:>:]]' ``` See [what this regex matches](https://regex101.com/r/vA5dB1/1) (you will get those that do not match since you are using `NOT`, and `\b` is used in PCRE instead of both `[[:<:]]` (leading word boundary) and `[[:>:]]` (trailing word boundary)).
1. you can try `'.*?\sto\s.*'` and `'.*?\sa\s.*'`. 2. or add `?` after the first `.*` in you sentence. thanks.
47,724,573
I have: ``` myColCI<-function(colName){ predictorvariable <- glm(death180 ~ nepalData[,colName], data=nepalData, family="binomial") summary(predictorvariable) confint(predictorvariable) } ``` One of the names of the column is parity so when after making my function, when I put `myColCI(parity)`, it says the > > object "parity" is not found > > > Can anyone give me a pointer to what's wrong with my code.
2017/12/09
[ "https://Stackoverflow.com/questions/47724573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9075008/" ]
Your formula is wrong here, hence you are getting the error, The right hand side after tilda side shouldn't be a reference to a dataframe. It should be column names separated by plus signs : From the documentation of `?formula` > > The models fit by, e.g., the lm and glm functions are specified in a > compact symbolic form. The ~ operator is basic in the formation of > such models. An expression of the form y ~ model is interpreted as a > specification that the response y is modelled by a linear predictor > specified symbolically by model. Such a model consists of a series of > terms separated by + operators. The terms themselves consist of > variable and factor names separated by : operators. Such a term is > interpreted as the interaction of all the variables and factors > appearing in the term. > > > `dependent_variable ~ Independent_variable1 + Independent_variable2` etc From data `mtcars`, I have written a glm formula as : `glm(am ~ mpg + disp + hp, data=mtcars, family="binomial")` So, your formula should be something like this: ``` glm(death180 ~ column1 + column2 +column3, data= nepalData, family="binomial") ``` To invoke this inside a function, since you have only one dependent variable it seems you can use below (Note here that, removing the datframe reference here and adding the as.formula expression to incorporate strings, convert the expression as valid formula): ``` myColCI<-function(colName){ predictorvariable <- glm(as.formula(paste0("death180 ~", colName)), data=nepalData, family="binomial") summary(predictorvariable) confint(predictorvariable) } myColCI("parity") ```
This is what you have to do ``` myColCI("parity") ``` This should give you the answer. I don't think your code is wrong. You are trying to subset a column of a data frame using the column name. In R, when you do this, you have to pass the name as a string. eg ``` dataframe[,"column_name"] ``` For your function, if you want to have both the confidence intervals and summary output, you would have to modify a little bit. Just like this: ``` myColCI<-function(colName){ predictorvariable <- glm(death180 ~ nepalData[,colName], data=nepalData, family="binomial") return(list(summary(predictorvariable),confint(predictorvariable))) } ```
51,374,752
Trying to deal with CORS set up a simple Node / Express server like so: ``` const express = require('express'); var cors = require('cors'); const app = express(); const port = process.env.PORT || 3000; app.use(cors()); app.use(express.static('public')); app.listen(port, () => { console.log('Server active on port: ', port); }); ``` Using this cors lib: <https://www.npmjs.com/package/cors> The rest is a simple app using JQuery ajax to fetch some data... Works with the CORS chrome extension enabled but can't figure out how to set up a simple server so that I do not have to use the chrome extension...
2018/07/17
[ "https://Stackoverflow.com/questions/51374752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4750401/" ]
You may try setting the options to be passed to your `cors` package, like this, ``` const corsOptions = { origin: process.env.CORS_ALLOW_ORIGIN || '*', methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization'] }; app.use(cors(corsOptions)); ``` Hope this helps.
You can use a cors middleware like this ``` const corsMiddleware = (req: Request, res: Response, next: NextFunction) => { logger.debug(req.method + " at " + req.url); res.setHeader("Access-Control-Allow-Origin", "*"); // you can optionally replace * with your server address res.setHeader("Access-Control-Allow-Credentials", "true"); res.setHeader( "Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS" ); res.setHeader( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization" ); next(); }; ``` To use this middleware for all kinds of requests, use ``` app.all("*", corsMiddleware); ``` This will add these headers in all the requests.
264,238
I was making some changes to a remote file in vi using the terminal when I accidently pressed `Ctrl`+`S` instead of `:wq`. Now everything got hanged. I tried `Escape,:q!` and all sorts of vi commans but nothing is responding. The Terminal Screen is stuck. I can't close the Terminal session as of now as it will lead to loss of all the changes. Please suggest what should be done
2013/03/05
[ "https://askubuntu.com/questions/264238", "https://askubuntu.com", "https://askubuntu.com/users/86687/" ]
`Ctrl`+`Q` will undo `Ctrl`+`S`. These are ancient control codes to stop and resume output to a terminal. They can still be useful, for instance when you are `tailf`-ing a log file and something interesting scrolls by, but this era of unlimited scrollback buffers has really obsoleted them.
I would like to complement [zwets' accepted answer](https://askubuntu.com/a/264253/22949). You can see the meaning of special keypresses by issuing the commands `stty -a` and [`man stty`](http://manpages.ubuntu.com/manpages/bionic/en/man1/stty.1.html). `stty -a` prints all current settings of the terminal. The result in my terminal: ``` speed 38400 baud; rows 33; columns 80; line = 0; intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = M-^?; eol2 = M-^?; swtch = M-^?; ***start = ^Q; stop = ^S***; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0; -parenb -parodd cs8 hupcl -cstopb cread -clocal -crtscts -ignbrk brkint -ignpar -parmrk > -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc ixany imaxbel iutf8 opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke ``` [`man stty`](http://manpages.ubuntu.com/manpages/bionic/en/man1/stty.1.html) prints the manual of stty. The part that is relevant here: > > Special characters: > > > > ``` > start CHAR > CHAR will restart the output after stopping it > > stop CHAR > CHAR will stop the output > > ``` > >
14,085,881
I would like to implement a simple authentication in an JSF/Primefaces application. I have tried lots of different things, e.g. [Dialog - Login Demo](http://www.primefaces.org/showcase/ui/overlay/dialog/loginDemo.xhtml) makes a simple test on a dialog, but it does not login a user or? I also have taken a look at Java Security, like: ``` <security-constraint> <web-resource-collection> <web-resource-name>Protected Area</web-resource-name> <url-pattern>/protected/*</url-pattern> <http-method>PUT</http-method> <http-method>DELETE</http-method> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>REGISTERED_USER</role-name> </auth-constraint> </security-constraint> ``` With this everything under /protected is protected, but as far as i understand i need to define a realm in the server for authentication. I do not want to specify this in the server but just have a simple lookup in the database for it. Is there a way to authenticate a user without defining something in the application server? Or anonther simple solution to authenticate and protect different pages?
2012/12/29
[ "https://Stackoverflow.com/questions/14085881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1936452/" ]
> > Is there a way to authenticate a user without defining something in the application server? > > > This is a long and *very* thorny story. It often comes up as one the main points of criticism against Java EE. The core of the story is that traditionally Java EE applications are supposed to be deployed with "unresolved dependencies". Those dependencies have to be satisfied at the application server, typically by someone who is not a developer, often by using some kind of GUI or console. Security configuration is one of those unresolved dependencies. If the security configuration is done at the application server, this is by definition always not portable, e.g. it has to be done in an application server specific way. It completely rules out using application domain models (e.g. a JPA entity `User`) for this authentication. Some servers (e.g. JBoss AS) allow configuring their proprietary security mechanisms from within the application, and additionally allow for 'custom login modules' (the term is different for pretty much every server) to be loaded from the application as well. With some small hacks, this will allow the usage of application domain models and the same data source that the application itself uses for authentication. Finally, there's a relatively unknown portable way to do authentication from within an application. This is done via the **JASPIC** SPI, also known as **JASPI** or **JSR 196**. Basically, this JASPIC seems to be what you are looking for. Unfortunately, JASPIC is not perfect and even though it's a technology from Java EE 6 and we're almost at Java EE 7, at the moment support for JASPIC in various application servers is still sketchy. On top of that, even though JASPIC is standardized, application server vendors *still* somehow require proprietary configuration to actually make it work. I wrote an article about JASPIC that explains the current problems in more detail: [Implementing container authentication in Java EE with JASPIC](http://arjan-tijms.blogspot.com/2012/11/implementing-container-authentication.html)
I have found a for me suitable and easy solution by simply using Web Filters. I have added a filter to web.xml like ``` <!-- Authentication Filter --> <filter> <filter-name>AuthenticationFilter</filter-name> <filter-class>org.example.filters.AuthenticationFilter</filter-class> </filter> <filter-mapping> <filter-name>AuthenticationFilter</filter-name> <url-pattern>/protected/*</url-pattern> </filter-mapping> ``` The filter looks something like this ``` @WebFilter(filterName="AuthenticationFilter") public class AuthenticationFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { Cookie[] cookies = ((HttpServletRequest)request).getCookies(); // Try to find a valid session cookie if (cookies != null) { String sessionId = null; for (Cookie cookie : cookies) { if ("sessionId".equals(cookie.getName())) { sessionId = cookie.getValue(); } } // Check if we have a valid session UserSession session = Backend.getInstance().getSessionGateway().getBySessionId(sessionId); if (session != null) { chain.doFilter(request, response); return; } else if (sessionId != null) { // Remove the cookie Cookie cookie = new Cookie("sessionId", null); cookie.setMaxAge(-1); ((HttpServletResponse)response).addCookie(cookie); } } // Problem due to relative path!! // ((HttpServletResponse)response).sendRedirect("../login.xhtml"); RequestDispatcher rd = request.getRequestDispatcher("/login.xhtml"); rd.forward(request, response); } } ``` So i had just to implement a Bean that authenticates and sets the session cookie. I will add the user agent to have additional security but it basically works. The only problem i have that i can not do a redirect, cause it is not using context path but just redirects to /index.xhtml instead of /my\_app\_context/index.xhtml
620,445
I am using a very simple model to show the unity gainbandwidth of a closed loop sample and hold with a closed loop gain of 2. One would expect an ideal OTA to have a GBW independent of rout as GBW is just \$ \frac{g\_m\*r\_{out}}{r\_{out}\*C\_L} \$ or \$GBW = g\_m/C\_L (\frac {rad}{s}).\$ Yet, the simulation I contrived shows something very different. It can be seen that \$f\_{unity} = GBW\$ varies with \$rout\$. It has a peak that matches the calc exactly, but tapers off to a value far different than calculated. A clue is that the closed loop gain also behaves oddly. We would expect it to start at 0 and rise and settle to an expected close loop gain of 2, as the open loop gain is getting larger with rout, and the closed loop accuracy should increase. The gain plot shows a peaking coincident with the \$f\_{unity}\$ far above 2. I'm not certain if it is the actual simulation or something with LTSPICE or my theoretical expectations that are amiss. Anyone have an explanation? [![enter image description here](https://i.stack.imgur.com/1zNEH.png)](https://i.stack.imgur.com/1zNEH.png)
2022/05/20
[ "https://electronics.stackexchange.com/questions/620445", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/11779/" ]
If it helps anyone, I figured out (through a fairly tedious analysis) that it's more complicated than the numerous texts, literature, and theses using sample and hold and multiplying dac calculations make it out to be (it can be quite sensitive to low feedback factor and output impedance for example). I found an [excellent paper/blog](https://www.electronicdesign.com/technologies/analog/article/21807892/gainbandwidth-product-is-not-always-constant) explaining the fallacy of perpetuating gainbandwidth product is always constant (even with very simple op amp open/closed loop structures). The author shows that it requires assumptions such as closed loop gain greater than about 20. Below that, the more rigorous calculations are called for. Notice that a common pipeline ADC MDAC uses a gain on the order of 2, falling into this zone. As an example, here, instead of just using \$fu= \frac {g\_m}{2\*pi\*C\_{L}}\$ as is typically shown in texts, a more complex analysis (for the circuit I showed) returns something like \$fu= \frac {g\_m}{2\*pi\*C\_{L}} - \frac{1}{r\_{out}\*{c\_{L}}}\$ where the sensitivity to rout is more clear for smaller rout.
I tried this circuit, but as soon as I run the simulator, it gives an error (logical). This error is dependent on the two capacitors. The midpoint has no DC path to the ground. If one adds paralleled resistors, behavior change immediately. Here is a simulation where (my) R1 and C2 are stepped logs (x10). One can see that there is a low-frequency corner (logical) but bandwidth is quasi illimited. (Gain only changes with C2, R2 and R3 must change accordingly with C2 and C1). [![enter image description here](https://i.stack.imgur.com/rdHO5.png)](https://i.stack.imgur.com/rdHO5.png) And here when "resistors" are "adapted" ... [![enter image description here](https://i.stack.imgur.com/OJdQR.png)](https://i.stack.imgur.com/OJdQR.png)
5,847,598
i heard that domain driven design pattern but do not know what it is exactly. is it design pattern? if so then how it is different from mvc or mvp. please discuss this. how to implement domain driven design pattern with c#.
2011/05/01
[ "https://Stackoverflow.com/questions/5847598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/728750/" ]
In short: It's not a design pattern. You can see it as **set of patterns** and **principles** where you write code that reflects real life objects and concepts in a specific domain (problem area): From the StackOverflow tag: > > Domain-driven design (DDD) is an > approach to developing software for > complex needs by deeply connecting the > implementation to an evolving model of > the core business concepts. > > > Here is a link to study: * [Wikipedia](http://en.wikipedia.org/wiki/Domain-driven_design)
I believe this link should get you started and more.. <http://www.infoq.com/articles/ddd-in-practice> The example in the article is not terrific (see the comments). Nonetheless, it contains some decent material on the ideas. Also, Google search on "anemic domain models" will return some relevant results. To read about other domain patterns: <http://www.informit.com/articles/article.aspx?p=1398617&seqNum=4>
5,847,598
i heard that domain driven design pattern but do not know what it is exactly. is it design pattern? if so then how it is different from mvc or mvp. please discuss this. how to implement domain driven design pattern with c#.
2011/05/01
[ "https://Stackoverflow.com/questions/5847598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/728750/" ]
In short: It's not a design pattern. You can see it as **set of patterns** and **principles** where you write code that reflects real life objects and concepts in a specific domain (problem area): From the StackOverflow tag: > > Domain-driven design (DDD) is an > approach to developing software for > complex needs by deeply connecting the > implementation to an evolving model of > the core business concepts. > > > Here is a link to study: * [Wikipedia](http://en.wikipedia.org/wiki/Domain-driven_design)
For DDD in the C# world, please look at [Applying Domain-Driven Design and Patterns: With Examples in C# and .NET](https://rads.stackoverflow.com/amzn/click/com/0321268202) . Jimmy Nilsson (the author) is a recognised leader in DDD using a C# slant.
5,847,598
i heard that domain driven design pattern but do not know what it is exactly. is it design pattern? if so then how it is different from mvc or mvp. please discuss this. how to implement domain driven design pattern with c#.
2011/05/01
[ "https://Stackoverflow.com/questions/5847598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/728750/" ]
I believe this link should get you started and more.. <http://www.infoq.com/articles/ddd-in-practice> The example in the article is not terrific (see the comments). Nonetheless, it contains some decent material on the ideas. Also, Google search on "anemic domain models" will return some relevant results. To read about other domain patterns: <http://www.informit.com/articles/article.aspx?p=1398617&seqNum=4>
For DDD in the C# world, please look at [Applying Domain-Driven Design and Patterns: With Examples in C# and .NET](https://rads.stackoverflow.com/amzn/click/com/0321268202) . Jimmy Nilsson (the author) is a recognised leader in DDD using a C# slant.
43,202,012
I argued with a friend the other day about those two snippets. Which is faster and why ? ``` value = 5; if (condition) { value = 6; } ``` and: ``` if (condition) { value = 6; } else { value = 5; } ``` What if `value` is a matrix ? Note: I know that `value = condition ? 6 : 5;` exists and I expect it to be faster, but it wasn't an option. **Edit** (requested by staff since question is on hold at the moment): * please answer by considering either *x86 assembly* generated by mainstream compilers (*say g++, clang++, vc, mingw*) in both optimized and non optimized versions or *MIPS assembly*. * when assembly differ, explain why a version is faster and when (*e.g. "better because no branching and branching has following issue blahblah"*)
2017/04/04
[ "https://Stackoverflow.com/questions/43202012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3439945/" ]
In pseudo-assembly language, ```none li #0, r0 test r1 beq L1 li #1, r0 L1: ``` *may or may not* be faster than ```none test r1 beq L1 li #1, r0 bra L2 L1: li #0, r0 L2: ``` depending on how sophisticated the actual CPU is. Going from simplest to fanciest: * With *any* CPU manufactured after roughly 1990, good performance depends on the code fitting within the [instruction cache](https://en.wikipedia.org/wiki/Cache_memory). When in doubt, therefore, minimize code size. This weighs in favor of the first example. * With a basic "[in-order, five-stage pipeline](https://en.wikipedia.org/wiki/Classic_RISC_pipeline)" CPU, which is still roughly what you get in many microcontrollers, there is a [pipeline bubble](https://en.wikipedia.org/wiki/Bubble_%28computing%29) every time a branch—conditional or unconditional—is taken, so it is also important to minimize the number of branch instructions. This also weighs in favor of the first example. * Somewhat more sophisticated CPUs—fancy enough to do "[out-of-order execution](https://en.wikipedia.org/wiki/Out-of-order_execution)", but not fancy enough to use the best known implementations of that concept—may incur pipeline bubbles whenever they encounter [write-after-write hazards](https://en.wikipedia.org/wiki/Hazard_%28computer_architecture%29#Write_after_write_.28WAW.29). This weighs in favor of the *second* example, where `r0` is written only once no matter what. These CPUs are usually fancy enough to process unconditional branches in the instruction fetcher, so you *aren't* just trading the write-after-write penalty for a branch penalty. I don't know if anyone is still making this kind of CPU anymore. However, the CPUs that *do* use the "best known implementations" of out-of-order execution are likely to cut corners on the less frequently used instructions, so you need to be aware that this sort of thing can happen. A real example is [false data dependencies on the destination registers in `popcnt` and `lzcnt` on Sandy Bridge CPUs](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62011). * At the highest end, the OOO engine will wind up issuing exactly the same sequence of internal operations for both code fragments—this is the hardware version of "don't worry about it, the compiler will generate the same machine code either way." However, code size still does matter, and now you also should be worrying about the predictability of the conditional branch. [Branch prediction](https://en.wikipedia.org/wiki/Branch_predictor) failures potentially cause a complete pipeline *flush*, which is catastrophic for performance; see [Why is it faster to process a sorted array than an unsorted array?](https://stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array) to understand how much difference this can make. If the branch *is* highly unpredictable, and your CPU has conditional-set or conditional-move instructions, this is the time to use them: ```none li #0, r0 test r1 setne r0 ``` or ```none li #0, r0 li #1, r2 test r1 movne r2, r0 ``` The conditional-set version is also more compact than any other alternative; if that instruction is available it is practically guaranteed to be the Right Thing for this scenario, even if the branch was predictable. The conditional-move version requires an additional scratch register, and always wastes one `li` instruction's worth of dispatch and execute resources; if the branch was in fact predictable, the branchy version may well be faster.
What would make you think any of them even the one liner is faster or slower? ``` unsigned int fun0 ( unsigned int condition, unsigned int value ) { value = 5; if (condition) { value = 6; } return(value); } unsigned int fun1 ( unsigned int condition, unsigned int value ) { if (condition) { value = 6; } else { value = 5; } return(value); } unsigned int fun2 ( unsigned int condition, unsigned int value ) { value = condition ? 6 : 5; return(value); } ``` More lines of code of a high level language gives the compiler more to work with so if you want to make a general rule about it give the compiler more code to work with. If the algorithm is the same like the cases above then one would expect the compiler with minimal optimization to figure that out. ``` 00000000 <fun0>: 0: e3500000 cmp r0, #0 4: 03a00005 moveq r0, #5 8: 13a00006 movne r0, #6 c: e12fff1e bx lr 00000010 <fun1>: 10: e3500000 cmp r0, #0 14: 13a00006 movne r0, #6 18: 03a00005 moveq r0, #5 1c: e12fff1e bx lr 00000020 <fun2>: 20: e3500000 cmp r0, #0 24: 13a00006 movne r0, #6 28: 03a00005 moveq r0, #5 2c: e12fff1e bx lr ``` not a big surprise it did the first function in a different order, same execution time though. ``` 0000000000000000 <fun0>: 0: 7100001f cmp w0, #0x0 4: 1a9f07e0 cset w0, ne 8: 11001400 add w0, w0, #0x5 c: d65f03c0 ret 0000000000000010 <fun1>: 10: 7100001f cmp w0, #0x0 14: 1a9f07e0 cset w0, ne 18: 11001400 add w0, w0, #0x5 1c: d65f03c0 ret 0000000000000020 <fun2>: 20: 7100001f cmp w0, #0x0 24: 1a9f07e0 cset w0, ne 28: 11001400 add w0, w0, #0x5 2c: d65f03c0 ret ``` Hopefully you get the idea you could have just tried this if it wasnt obvious that the different implementations were not actually different. As far as a matrix goes, not sure how that matters, ``` if(condition) { big blob of code a } else { big blob of code b } ``` just going to put the same if-then-else wrapper around the big blobs of code be they value=5 or something more complicated. Likewise the comparison even if it is a big blob of code it still has to be computed, and equal to or not equal to something is often compiled with the negative, if (condition) do something is often compiled as if not condition goto. ``` 00000000 <fun0>: 0: 0f 93 tst r15 2: 03 24 jz $+8 ;abs 0xa 4: 3f 40 06 00 mov #6, r15 ;#0x0006 8: 30 41 ret a: 3f 40 05 00 mov #5, r15 ;#0x0005 e: 30 41 ret 00000010 <fun1>: 10: 0f 93 tst r15 12: 03 20 jnz $+8 ;abs 0x1a 14: 3f 40 05 00 mov #5, r15 ;#0x0005 18: 30 41 ret 1a: 3f 40 06 00 mov #6, r15 ;#0x0006 1e: 30 41 ret 00000020 <fun2>: 20: 0f 93 tst r15 22: 03 20 jnz $+8 ;abs 0x2a 24: 3f 40 05 00 mov #5, r15 ;#0x0005 28: 30 41 ret 2a: 3f 40 06 00 mov #6, r15 ;#0x0006 2e: 30 41 ``` we just went through this exercise with someone else recently on stackoverflow. this mips compiler interestingly in that case not only realized the functions were the same, but had one function simply jump to the other to save on code space. Didnt do that here though ``` 00000000 <fun0>: 0: 0004102b sltu $2,$0,$4 4: 03e00008 jr $31 8: 24420005 addiu $2,$2,5 0000000c <fun1>: c: 0004102b sltu $2,$0,$4 10: 03e00008 jr $31 14: 24420005 addiu $2,$2,5 00000018 <fun2>: 18: 0004102b sltu $2,$0,$4 1c: 03e00008 jr $31 20: 24420005 addiu $2,$2,5 ``` some more targets. ``` 00000000 <_fun0>: 0: 1166 mov r5, -(sp) 2: 1185 mov sp, r5 4: 0bf5 0004 tst 4(r5) 8: 0304 beq 12 <_fun0+0x12> a: 15c0 0006 mov $6, r0 e: 1585 mov (sp)+, r5 10: 0087 rts pc 12: 15c0 0005 mov $5, r0 16: 1585 mov (sp)+, r5 18: 0087 rts pc 0000001a <_fun1>: 1a: 1166 mov r5, -(sp) 1c: 1185 mov sp, r5 1e: 0bf5 0004 tst 4(r5) 22: 0204 bne 2c <_fun1+0x12> 24: 15c0 0005 mov $5, r0 28: 1585 mov (sp)+, r5 2a: 0087 rts pc 2c: 15c0 0006 mov $6, r0 30: 1585 mov (sp)+, r5 32: 0087 rts pc 00000034 <_fun2>: 34: 1166 mov r5, -(sp) 36: 1185 mov sp, r5 38: 0bf5 0004 tst 4(r5) 3c: 0204 bne 46 <_fun2+0x12> 3e: 15c0 0005 mov $5, r0 42: 1585 mov (sp)+, r5 44: 0087 rts pc 46: 15c0 0006 mov $6, r0 4a: 1585 mov (sp)+, r5 4c: 0087 rts pc 00000000 <fun0>: 0: 00a03533 snez x10,x10 4: 0515 addi x10,x10,5 6: 8082 ret 00000008 <fun1>: 8: 00a03533 snez x10,x10 c: 0515 addi x10,x10,5 e: 8082 ret 00000010 <fun2>: 10: 00a03533 snez x10,x10 14: 0515 addi x10,x10,5 16: 8082 ret ``` and compilers with this i code one would expect the different targets to match as well ``` define i32 @fun0(i32 %condition, i32 %value) #0 { %1 = icmp ne i32 %condition, 0 %. = select i1 %1, i32 6, i32 5 ret i32 %. } ; Function Attrs: norecurse nounwind readnone define i32 @fun1(i32 %condition, i32 %value) #0 { %1 = icmp eq i32 %condition, 0 %. = select i1 %1, i32 5, i32 6 ret i32 %. } ; Function Attrs: norecurse nounwind readnone define i32 @fun2(i32 %condition, i32 %value) #0 { %1 = icmp ne i32 %condition, 0 %2 = select i1 %1, i32 6, i32 5 ret i32 %2 } 00000000 <fun0>: 0: e3a01005 mov r1, #5 4: e3500000 cmp r0, #0 8: 13a01006 movne r1, #6 c: e1a00001 mov r0, r1 10: e12fff1e bx lr 00000014 <fun1>: 14: e3a01006 mov r1, #6 18: e3500000 cmp r0, #0 1c: 03a01005 moveq r1, #5 20: e1a00001 mov r0, r1 24: e12fff1e bx lr 00000028 <fun2>: 28: e3a01005 mov r1, #5 2c: e3500000 cmp r0, #0 30: 13a01006 movne r1, #6 34: e1a00001 mov r0, r1 38: e12fff1e bx lr fun0: push.w r4 mov.w r1, r4 mov.w r15, r12 mov.w #6, r15 cmp.w #0, r12 jne .LBB0_2 mov.w #5, r15 .LBB0_2: pop.w r4 ret fun1: push.w r4 mov.w r1, r4 mov.w r15, r12 mov.w #5, r15 cmp.w #0, r12 jeq .LBB1_2 mov.w #6, r15 .LBB1_2: pop.w r4 ret fun2: push.w r4 mov.w r1, r4 mov.w r15, r12 mov.w #6, r15 cmp.w #0, r12 jne .LBB2_2 mov.w #5, r15 .LBB2_2: pop.w r4 ret ``` Now technically there is a performance difference in some of these solutions, sometimes the result is 5 case has a jump over the result is 6 code, and vice versa, is a branch faster than executing through? one could argue but the execution should vary. But that is more of an if condition vs if not condition in the code resulting in the compiler doing the if this jump over else execute through. but this is not necessarily due to the coding style but the comparison and the if and the else cases in whatever syntax.
43,202,012
I argued with a friend the other day about those two snippets. Which is faster and why ? ``` value = 5; if (condition) { value = 6; } ``` and: ``` if (condition) { value = 6; } else { value = 5; } ``` What if `value` is a matrix ? Note: I know that `value = condition ? 6 : 5;` exists and I expect it to be faster, but it wasn't an option. **Edit** (requested by staff since question is on hold at the moment): * please answer by considering either *x86 assembly* generated by mainstream compilers (*say g++, clang++, vc, mingw*) in both optimized and non optimized versions or *MIPS assembly*. * when assembly differ, explain why a version is faster and when (*e.g. "better because no branching and branching has following issue blahblah"*)
2017/04/04
[ "https://Stackoverflow.com/questions/43202012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3439945/" ]
The answer from [CompuChip](https://stackoverflow.com/a/43202221/2805305) shows that for `int` they both are optimized to the same assembly, so it doesn't matter. > > What if value is a matrix ? > > > I will interpret this in a more general way, i.e. what if `value` is of a type whose constructions and assignments are expensive (and moves are cheap). then ``` T value = init1; if (condition) value = init2; ``` is sub-optimal because in case `condition` is true, you do the unnecessary initialization to `init1` and then you do the copy assignment. ``` T value; if (condition) value = init2; else value = init3; ``` This is better. But still sub-optimal if default construction is expensive and if copy construction is more expensive then initialization. You have the conditional operator solution which is good: ``` T value = condition ? init1 : init2; ``` Or, if you don't like the conditional operator, you can create a helper function like this: ``` T create(bool condition) { if (condition) return {init1}; else return {init2}; } T value = create(condition); ``` Depending on what `init1` and `init2` are you can also consider this: ``` auto final_init = condition ? init1 : init2; T value = final_init; ``` But again I must emphasize that this is relevant only when construction and assignments are really expensive for the given type. And even then, only by **profiling** you know for sure.
In unoptimised code, the first example assigns a variable always once and sometimes twice. The second example only ever assigns a variable once. The conditional is the same on both code paths, so that shouldn't matter. In optimised code, it depends on the compiler. As always, if you are that concerned, generate the assembly and see what the compiler is actually doing.
43,202,012
I argued with a friend the other day about those two snippets. Which is faster and why ? ``` value = 5; if (condition) { value = 6; } ``` and: ``` if (condition) { value = 6; } else { value = 5; } ``` What if `value` is a matrix ? Note: I know that `value = condition ? 6 : 5;` exists and I expect it to be faster, but it wasn't an option. **Edit** (requested by staff since question is on hold at the moment): * please answer by considering either *x86 assembly* generated by mainstream compilers (*say g++, clang++, vc, mingw*) in both optimized and non optimized versions or *MIPS assembly*. * when assembly differ, explain why a version is faster and when (*e.g. "better because no branching and branching has following issue blahblah"*)
2017/04/04
[ "https://Stackoverflow.com/questions/43202012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3439945/" ]
What would make you think any of them even the one liner is faster or slower? ``` unsigned int fun0 ( unsigned int condition, unsigned int value ) { value = 5; if (condition) { value = 6; } return(value); } unsigned int fun1 ( unsigned int condition, unsigned int value ) { if (condition) { value = 6; } else { value = 5; } return(value); } unsigned int fun2 ( unsigned int condition, unsigned int value ) { value = condition ? 6 : 5; return(value); } ``` More lines of code of a high level language gives the compiler more to work with so if you want to make a general rule about it give the compiler more code to work with. If the algorithm is the same like the cases above then one would expect the compiler with minimal optimization to figure that out. ``` 00000000 <fun0>: 0: e3500000 cmp r0, #0 4: 03a00005 moveq r0, #5 8: 13a00006 movne r0, #6 c: e12fff1e bx lr 00000010 <fun1>: 10: e3500000 cmp r0, #0 14: 13a00006 movne r0, #6 18: 03a00005 moveq r0, #5 1c: e12fff1e bx lr 00000020 <fun2>: 20: e3500000 cmp r0, #0 24: 13a00006 movne r0, #6 28: 03a00005 moveq r0, #5 2c: e12fff1e bx lr ``` not a big surprise it did the first function in a different order, same execution time though. ``` 0000000000000000 <fun0>: 0: 7100001f cmp w0, #0x0 4: 1a9f07e0 cset w0, ne 8: 11001400 add w0, w0, #0x5 c: d65f03c0 ret 0000000000000010 <fun1>: 10: 7100001f cmp w0, #0x0 14: 1a9f07e0 cset w0, ne 18: 11001400 add w0, w0, #0x5 1c: d65f03c0 ret 0000000000000020 <fun2>: 20: 7100001f cmp w0, #0x0 24: 1a9f07e0 cset w0, ne 28: 11001400 add w0, w0, #0x5 2c: d65f03c0 ret ``` Hopefully you get the idea you could have just tried this if it wasnt obvious that the different implementations were not actually different. As far as a matrix goes, not sure how that matters, ``` if(condition) { big blob of code a } else { big blob of code b } ``` just going to put the same if-then-else wrapper around the big blobs of code be they value=5 or something more complicated. Likewise the comparison even if it is a big blob of code it still has to be computed, and equal to or not equal to something is often compiled with the negative, if (condition) do something is often compiled as if not condition goto. ``` 00000000 <fun0>: 0: 0f 93 tst r15 2: 03 24 jz $+8 ;abs 0xa 4: 3f 40 06 00 mov #6, r15 ;#0x0006 8: 30 41 ret a: 3f 40 05 00 mov #5, r15 ;#0x0005 e: 30 41 ret 00000010 <fun1>: 10: 0f 93 tst r15 12: 03 20 jnz $+8 ;abs 0x1a 14: 3f 40 05 00 mov #5, r15 ;#0x0005 18: 30 41 ret 1a: 3f 40 06 00 mov #6, r15 ;#0x0006 1e: 30 41 ret 00000020 <fun2>: 20: 0f 93 tst r15 22: 03 20 jnz $+8 ;abs 0x2a 24: 3f 40 05 00 mov #5, r15 ;#0x0005 28: 30 41 ret 2a: 3f 40 06 00 mov #6, r15 ;#0x0006 2e: 30 41 ``` we just went through this exercise with someone else recently on stackoverflow. this mips compiler interestingly in that case not only realized the functions were the same, but had one function simply jump to the other to save on code space. Didnt do that here though ``` 00000000 <fun0>: 0: 0004102b sltu $2,$0,$4 4: 03e00008 jr $31 8: 24420005 addiu $2,$2,5 0000000c <fun1>: c: 0004102b sltu $2,$0,$4 10: 03e00008 jr $31 14: 24420005 addiu $2,$2,5 00000018 <fun2>: 18: 0004102b sltu $2,$0,$4 1c: 03e00008 jr $31 20: 24420005 addiu $2,$2,5 ``` some more targets. ``` 00000000 <_fun0>: 0: 1166 mov r5, -(sp) 2: 1185 mov sp, r5 4: 0bf5 0004 tst 4(r5) 8: 0304 beq 12 <_fun0+0x12> a: 15c0 0006 mov $6, r0 e: 1585 mov (sp)+, r5 10: 0087 rts pc 12: 15c0 0005 mov $5, r0 16: 1585 mov (sp)+, r5 18: 0087 rts pc 0000001a <_fun1>: 1a: 1166 mov r5, -(sp) 1c: 1185 mov sp, r5 1e: 0bf5 0004 tst 4(r5) 22: 0204 bne 2c <_fun1+0x12> 24: 15c0 0005 mov $5, r0 28: 1585 mov (sp)+, r5 2a: 0087 rts pc 2c: 15c0 0006 mov $6, r0 30: 1585 mov (sp)+, r5 32: 0087 rts pc 00000034 <_fun2>: 34: 1166 mov r5, -(sp) 36: 1185 mov sp, r5 38: 0bf5 0004 tst 4(r5) 3c: 0204 bne 46 <_fun2+0x12> 3e: 15c0 0005 mov $5, r0 42: 1585 mov (sp)+, r5 44: 0087 rts pc 46: 15c0 0006 mov $6, r0 4a: 1585 mov (sp)+, r5 4c: 0087 rts pc 00000000 <fun0>: 0: 00a03533 snez x10,x10 4: 0515 addi x10,x10,5 6: 8082 ret 00000008 <fun1>: 8: 00a03533 snez x10,x10 c: 0515 addi x10,x10,5 e: 8082 ret 00000010 <fun2>: 10: 00a03533 snez x10,x10 14: 0515 addi x10,x10,5 16: 8082 ret ``` and compilers with this i code one would expect the different targets to match as well ``` define i32 @fun0(i32 %condition, i32 %value) #0 { %1 = icmp ne i32 %condition, 0 %. = select i1 %1, i32 6, i32 5 ret i32 %. } ; Function Attrs: norecurse nounwind readnone define i32 @fun1(i32 %condition, i32 %value) #0 { %1 = icmp eq i32 %condition, 0 %. = select i1 %1, i32 5, i32 6 ret i32 %. } ; Function Attrs: norecurse nounwind readnone define i32 @fun2(i32 %condition, i32 %value) #0 { %1 = icmp ne i32 %condition, 0 %2 = select i1 %1, i32 6, i32 5 ret i32 %2 } 00000000 <fun0>: 0: e3a01005 mov r1, #5 4: e3500000 cmp r0, #0 8: 13a01006 movne r1, #6 c: e1a00001 mov r0, r1 10: e12fff1e bx lr 00000014 <fun1>: 14: e3a01006 mov r1, #6 18: e3500000 cmp r0, #0 1c: 03a01005 moveq r1, #5 20: e1a00001 mov r0, r1 24: e12fff1e bx lr 00000028 <fun2>: 28: e3a01005 mov r1, #5 2c: e3500000 cmp r0, #0 30: 13a01006 movne r1, #6 34: e1a00001 mov r0, r1 38: e12fff1e bx lr fun0: push.w r4 mov.w r1, r4 mov.w r15, r12 mov.w #6, r15 cmp.w #0, r12 jne .LBB0_2 mov.w #5, r15 .LBB0_2: pop.w r4 ret fun1: push.w r4 mov.w r1, r4 mov.w r15, r12 mov.w #5, r15 cmp.w #0, r12 jeq .LBB1_2 mov.w #6, r15 .LBB1_2: pop.w r4 ret fun2: push.w r4 mov.w r1, r4 mov.w r15, r12 mov.w #6, r15 cmp.w #0, r12 jne .LBB2_2 mov.w #5, r15 .LBB2_2: pop.w r4 ret ``` Now technically there is a performance difference in some of these solutions, sometimes the result is 5 case has a jump over the result is 6 code, and vice versa, is a branch faster than executing through? one could argue but the execution should vary. But that is more of an if condition vs if not condition in the code resulting in the compiler doing the if this jump over else execute through. but this is not necessarily due to the coding style but the comparison and the if and the else cases in whatever syntax.
Ok, since assembly is one of the tags, I will just assume your code is pseudo code (and not necessarily c) and translate it by human into 6502 assembly. 1st Option (without else) ``` ldy #$00 lda #$05 dey bmi false lda #$06 false brk ``` 2nd Option (with else) ``` ldy #$00 dey bmi else lda #$06 sec bcs end else lda #$05 end brk ``` Assumptions: Condition is in Y register set this to 0 or 1 on the first line of either option, result will be in accumulator. So, after counting cycles for both possibilities of each case, we see that the 1st construct is generally faster; 9 cycles when condition is 0 and 10 cycles when condition is 1, whereas option two is also 9 cycles when condition is 0, but 13 cycles when condition is 1. (*cycle counts do not include the `BRK` at the end*). **Conclusion: `If only` is faster than `If-Else` construct.** And for completeness, here is an optimized `value = condition + 5` solution: ``` ldy #$00 lda #$00 tya adc #$05 brk ``` This cuts our time down to 8 cycles (*again not including the `BRK` at the end*).
43,202,012
I argued with a friend the other day about those two snippets. Which is faster and why ? ``` value = 5; if (condition) { value = 6; } ``` and: ``` if (condition) { value = 6; } else { value = 5; } ``` What if `value` is a matrix ? Note: I know that `value = condition ? 6 : 5;` exists and I expect it to be faster, but it wasn't an option. **Edit** (requested by staff since question is on hold at the moment): * please answer by considering either *x86 assembly* generated by mainstream compilers (*say g++, clang++, vc, mingw*) in both optimized and non optimized versions or *MIPS assembly*. * when assembly differ, explain why a version is faster and when (*e.g. "better because no branching and branching has following issue blahblah"*)
2017/04/04
[ "https://Stackoverflow.com/questions/43202012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3439945/" ]
**TL;DR:** In unoptimized code, `if` without `else` seems irrelevantly more efficient but with even the most basic level of optimization enabled the code is basically rewritten to `value = condition + 5`. --- I [gave it a try](https://gcc.godbolt.org/) and generated the assembly for the following code: ``` int ifonly(bool condition, int value) { value = 5; if (condition) { value = 6; } return value; } int ifelse(bool condition, int value) { if (condition) { value = 6; } else { value = 5; } return value; } ``` On gcc 6.3 with optimizations disabled (`-O0`), the relevant difference is: ``` mov DWORD PTR [rbp-8], 5 cmp BYTE PTR [rbp-4], 0 je .L2 mov DWORD PTR [rbp-8], 6 .L2: mov eax, DWORD PTR [rbp-8] ``` for `ifonly`, while `ifelse` has ``` cmp BYTE PTR [rbp-4], 0 je .L5 mov DWORD PTR [rbp-8], 6 jmp .L6 .L5: mov DWORD PTR [rbp-8], 5 .L6: mov eax, DWORD PTR [rbp-8] ``` The latter looks slightly less efficient because it has an extra jump but both have at least two and at most three assignments so unless you really need to squeeze every last drop of performance (hint: unless you are working on a space shuttle you don't, and even then you *probably* don't) the difference won't be noticeable. However, even with the lowest optimization level (`-O1`) both functions reduce to the same: ``` test dil, dil setne al movzx eax, al add eax, 5 ``` which is basically the equivalent of ``` return 5 + condition; ``` assuming `condition` is zero or one. Higher optimization levels don't really change the output, except they manage to avoid the `movzx` by efficiently zeroing out the `EAX` register at the start. --- **Disclaimer:** You probably shouldn't write `5 + condition` yourself (even though the standard guarantees that converting `true` to an integer type gives `1`) because your intent might not be immediately obvious to people reading your code (which may include your future self). The point of this code is to show that what the compiler produces in both cases is (practically) identical. [Ciprian Tomoiaga](https://stackoverflow.com/questions/43202012/if-statement-vs-if-else-statement-which-is-faster/43202221?noredirect=1#comment73501865_43202221) states it quite well in the comments: > > a **human**'s job is to write code **for humans** and let the **compiler** write code for **the machine**. > > >
In unoptimised code, the first example assigns a variable always once and sometimes twice. The second example only ever assigns a variable once. The conditional is the same on both code paths, so that shouldn't matter. In optimised code, it depends on the compiler. As always, if you are that concerned, generate the assembly and see what the compiler is actually doing.
43,202,012
I argued with a friend the other day about those two snippets. Which is faster and why ? ``` value = 5; if (condition) { value = 6; } ``` and: ``` if (condition) { value = 6; } else { value = 5; } ``` What if `value` is a matrix ? Note: I know that `value = condition ? 6 : 5;` exists and I expect it to be faster, but it wasn't an option. **Edit** (requested by staff since question is on hold at the moment): * please answer by considering either *x86 assembly* generated by mainstream compilers (*say g++, clang++, vc, mingw*) in both optimized and non optimized versions or *MIPS assembly*. * when assembly differ, explain why a version is faster and when (*e.g. "better because no branching and branching has following issue blahblah"*)
2017/04/04
[ "https://Stackoverflow.com/questions/43202012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3439945/" ]
In pseudo-assembly language, ```none li #0, r0 test r1 beq L1 li #1, r0 L1: ``` *may or may not* be faster than ```none test r1 beq L1 li #1, r0 bra L2 L1: li #0, r0 L2: ``` depending on how sophisticated the actual CPU is. Going from simplest to fanciest: * With *any* CPU manufactured after roughly 1990, good performance depends on the code fitting within the [instruction cache](https://en.wikipedia.org/wiki/Cache_memory). When in doubt, therefore, minimize code size. This weighs in favor of the first example. * With a basic "[in-order, five-stage pipeline](https://en.wikipedia.org/wiki/Classic_RISC_pipeline)" CPU, which is still roughly what you get in many microcontrollers, there is a [pipeline bubble](https://en.wikipedia.org/wiki/Bubble_%28computing%29) every time a branch—conditional or unconditional—is taken, so it is also important to minimize the number of branch instructions. This also weighs in favor of the first example. * Somewhat more sophisticated CPUs—fancy enough to do "[out-of-order execution](https://en.wikipedia.org/wiki/Out-of-order_execution)", but not fancy enough to use the best known implementations of that concept—may incur pipeline bubbles whenever they encounter [write-after-write hazards](https://en.wikipedia.org/wiki/Hazard_%28computer_architecture%29#Write_after_write_.28WAW.29). This weighs in favor of the *second* example, where `r0` is written only once no matter what. These CPUs are usually fancy enough to process unconditional branches in the instruction fetcher, so you *aren't* just trading the write-after-write penalty for a branch penalty. I don't know if anyone is still making this kind of CPU anymore. However, the CPUs that *do* use the "best known implementations" of out-of-order execution are likely to cut corners on the less frequently used instructions, so you need to be aware that this sort of thing can happen. A real example is [false data dependencies on the destination registers in `popcnt` and `lzcnt` on Sandy Bridge CPUs](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62011). * At the highest end, the OOO engine will wind up issuing exactly the same sequence of internal operations for both code fragments—this is the hardware version of "don't worry about it, the compiler will generate the same machine code either way." However, code size still does matter, and now you also should be worrying about the predictability of the conditional branch. [Branch prediction](https://en.wikipedia.org/wiki/Branch_predictor) failures potentially cause a complete pipeline *flush*, which is catastrophic for performance; see [Why is it faster to process a sorted array than an unsorted array?](https://stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array) to understand how much difference this can make. If the branch *is* highly unpredictable, and your CPU has conditional-set or conditional-move instructions, this is the time to use them: ```none li #0, r0 test r1 setne r0 ``` or ```none li #0, r0 li #1, r2 test r1 movne r2, r0 ``` The conditional-set version is also more compact than any other alternative; if that instruction is available it is practically guaranteed to be the Right Thing for this scenario, even if the branch was predictable. The conditional-move version requires an additional scratch register, and always wastes one `li` instruction's worth of dispatch and execute resources; if the branch was in fact predictable, the branchy version may well be faster.
In unoptimised code, the first example assigns a variable always once and sometimes twice. The second example only ever assigns a variable once. The conditional is the same on both code paths, so that shouldn't matter. In optimised code, it depends on the compiler. As always, if you are that concerned, generate the assembly and see what the compiler is actually doing.
43,202,012
I argued with a friend the other day about those two snippets. Which is faster and why ? ``` value = 5; if (condition) { value = 6; } ``` and: ``` if (condition) { value = 6; } else { value = 5; } ``` What if `value` is a matrix ? Note: I know that `value = condition ? 6 : 5;` exists and I expect it to be faster, but it wasn't an option. **Edit** (requested by staff since question is on hold at the moment): * please answer by considering either *x86 assembly* generated by mainstream compilers (*say g++, clang++, vc, mingw*) in both optimized and non optimized versions or *MIPS assembly*. * when assembly differ, explain why a version is faster and when (*e.g. "better because no branching and branching has following issue blahblah"*)
2017/04/04
[ "https://Stackoverflow.com/questions/43202012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3439945/" ]
The answer from [CompuChip](https://stackoverflow.com/a/43202221/2805305) shows that for `int` they both are optimized to the same assembly, so it doesn't matter. > > What if value is a matrix ? > > > I will interpret this in a more general way, i.e. what if `value` is of a type whose constructions and assignments are expensive (and moves are cheap). then ``` T value = init1; if (condition) value = init2; ``` is sub-optimal because in case `condition` is true, you do the unnecessary initialization to `init1` and then you do the copy assignment. ``` T value; if (condition) value = init2; else value = init3; ``` This is better. But still sub-optimal if default construction is expensive and if copy construction is more expensive then initialization. You have the conditional operator solution which is good: ``` T value = condition ? init1 : init2; ``` Or, if you don't like the conditional operator, you can create a helper function like this: ``` T create(bool condition) { if (condition) return {init1}; else return {init2}; } T value = create(condition); ``` Depending on what `init1` and `init2` are you can also consider this: ``` auto final_init = condition ? init1 : init2; T value = final_init; ``` But again I must emphasize that this is relevant only when construction and assignments are really expensive for the given type. And even then, only by **profiling** you know for sure.
Ok, since assembly is one of the tags, I will just assume your code is pseudo code (and not necessarily c) and translate it by human into 6502 assembly. 1st Option (without else) ``` ldy #$00 lda #$05 dey bmi false lda #$06 false brk ``` 2nd Option (with else) ``` ldy #$00 dey bmi else lda #$06 sec bcs end else lda #$05 end brk ``` Assumptions: Condition is in Y register set this to 0 or 1 on the first line of either option, result will be in accumulator. So, after counting cycles for both possibilities of each case, we see that the 1st construct is generally faster; 9 cycles when condition is 0 and 10 cycles when condition is 1, whereas option two is also 9 cycles when condition is 0, but 13 cycles when condition is 1. (*cycle counts do not include the `BRK` at the end*). **Conclusion: `If only` is faster than `If-Else` construct.** And for completeness, here is an optimized `value = condition + 5` solution: ``` ldy #$00 lda #$00 tya adc #$05 brk ``` This cuts our time down to 8 cycles (*again not including the `BRK` at the end*).
43,202,012
I argued with a friend the other day about those two snippets. Which is faster and why ? ``` value = 5; if (condition) { value = 6; } ``` and: ``` if (condition) { value = 6; } else { value = 5; } ``` What if `value` is a matrix ? Note: I know that `value = condition ? 6 : 5;` exists and I expect it to be faster, but it wasn't an option. **Edit** (requested by staff since question is on hold at the moment): * please answer by considering either *x86 assembly* generated by mainstream compilers (*say g++, clang++, vc, mingw*) in both optimized and non optimized versions or *MIPS assembly*. * when assembly differ, explain why a version is faster and when (*e.g. "better because no branching and branching has following issue blahblah"*)
2017/04/04
[ "https://Stackoverflow.com/questions/43202012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3439945/" ]
**TL;DR:** In unoptimized code, `if` without `else` seems irrelevantly more efficient but with even the most basic level of optimization enabled the code is basically rewritten to `value = condition + 5`. --- I [gave it a try](https://gcc.godbolt.org/) and generated the assembly for the following code: ``` int ifonly(bool condition, int value) { value = 5; if (condition) { value = 6; } return value; } int ifelse(bool condition, int value) { if (condition) { value = 6; } else { value = 5; } return value; } ``` On gcc 6.3 with optimizations disabled (`-O0`), the relevant difference is: ``` mov DWORD PTR [rbp-8], 5 cmp BYTE PTR [rbp-4], 0 je .L2 mov DWORD PTR [rbp-8], 6 .L2: mov eax, DWORD PTR [rbp-8] ``` for `ifonly`, while `ifelse` has ``` cmp BYTE PTR [rbp-4], 0 je .L5 mov DWORD PTR [rbp-8], 6 jmp .L6 .L5: mov DWORD PTR [rbp-8], 5 .L6: mov eax, DWORD PTR [rbp-8] ``` The latter looks slightly less efficient because it has an extra jump but both have at least two and at most three assignments so unless you really need to squeeze every last drop of performance (hint: unless you are working on a space shuttle you don't, and even then you *probably* don't) the difference won't be noticeable. However, even with the lowest optimization level (`-O1`) both functions reduce to the same: ``` test dil, dil setne al movzx eax, al add eax, 5 ``` which is basically the equivalent of ``` return 5 + condition; ``` assuming `condition` is zero or one. Higher optimization levels don't really change the output, except they manage to avoid the `movzx` by efficiently zeroing out the `EAX` register at the start. --- **Disclaimer:** You probably shouldn't write `5 + condition` yourself (even though the standard guarantees that converting `true` to an integer type gives `1`) because your intent might not be immediately obvious to people reading your code (which may include your future self). The point of this code is to show that what the compiler produces in both cases is (practically) identical. [Ciprian Tomoiaga](https://stackoverflow.com/questions/43202012/if-statement-vs-if-else-statement-which-is-faster/43202221?noredirect=1#comment73501865_43202221) states it quite well in the comments: > > a **human**'s job is to write code **for humans** and let the **compiler** write code for **the machine**. > > >
What would make you think any of them even the one liner is faster or slower? ``` unsigned int fun0 ( unsigned int condition, unsigned int value ) { value = 5; if (condition) { value = 6; } return(value); } unsigned int fun1 ( unsigned int condition, unsigned int value ) { if (condition) { value = 6; } else { value = 5; } return(value); } unsigned int fun2 ( unsigned int condition, unsigned int value ) { value = condition ? 6 : 5; return(value); } ``` More lines of code of a high level language gives the compiler more to work with so if you want to make a general rule about it give the compiler more code to work with. If the algorithm is the same like the cases above then one would expect the compiler with minimal optimization to figure that out. ``` 00000000 <fun0>: 0: e3500000 cmp r0, #0 4: 03a00005 moveq r0, #5 8: 13a00006 movne r0, #6 c: e12fff1e bx lr 00000010 <fun1>: 10: e3500000 cmp r0, #0 14: 13a00006 movne r0, #6 18: 03a00005 moveq r0, #5 1c: e12fff1e bx lr 00000020 <fun2>: 20: e3500000 cmp r0, #0 24: 13a00006 movne r0, #6 28: 03a00005 moveq r0, #5 2c: e12fff1e bx lr ``` not a big surprise it did the first function in a different order, same execution time though. ``` 0000000000000000 <fun0>: 0: 7100001f cmp w0, #0x0 4: 1a9f07e0 cset w0, ne 8: 11001400 add w0, w0, #0x5 c: d65f03c0 ret 0000000000000010 <fun1>: 10: 7100001f cmp w0, #0x0 14: 1a9f07e0 cset w0, ne 18: 11001400 add w0, w0, #0x5 1c: d65f03c0 ret 0000000000000020 <fun2>: 20: 7100001f cmp w0, #0x0 24: 1a9f07e0 cset w0, ne 28: 11001400 add w0, w0, #0x5 2c: d65f03c0 ret ``` Hopefully you get the idea you could have just tried this if it wasnt obvious that the different implementations were not actually different. As far as a matrix goes, not sure how that matters, ``` if(condition) { big blob of code a } else { big blob of code b } ``` just going to put the same if-then-else wrapper around the big blobs of code be they value=5 or something more complicated. Likewise the comparison even if it is a big blob of code it still has to be computed, and equal to or not equal to something is often compiled with the negative, if (condition) do something is often compiled as if not condition goto. ``` 00000000 <fun0>: 0: 0f 93 tst r15 2: 03 24 jz $+8 ;abs 0xa 4: 3f 40 06 00 mov #6, r15 ;#0x0006 8: 30 41 ret a: 3f 40 05 00 mov #5, r15 ;#0x0005 e: 30 41 ret 00000010 <fun1>: 10: 0f 93 tst r15 12: 03 20 jnz $+8 ;abs 0x1a 14: 3f 40 05 00 mov #5, r15 ;#0x0005 18: 30 41 ret 1a: 3f 40 06 00 mov #6, r15 ;#0x0006 1e: 30 41 ret 00000020 <fun2>: 20: 0f 93 tst r15 22: 03 20 jnz $+8 ;abs 0x2a 24: 3f 40 05 00 mov #5, r15 ;#0x0005 28: 30 41 ret 2a: 3f 40 06 00 mov #6, r15 ;#0x0006 2e: 30 41 ``` we just went through this exercise with someone else recently on stackoverflow. this mips compiler interestingly in that case not only realized the functions were the same, but had one function simply jump to the other to save on code space. Didnt do that here though ``` 00000000 <fun0>: 0: 0004102b sltu $2,$0,$4 4: 03e00008 jr $31 8: 24420005 addiu $2,$2,5 0000000c <fun1>: c: 0004102b sltu $2,$0,$4 10: 03e00008 jr $31 14: 24420005 addiu $2,$2,5 00000018 <fun2>: 18: 0004102b sltu $2,$0,$4 1c: 03e00008 jr $31 20: 24420005 addiu $2,$2,5 ``` some more targets. ``` 00000000 <_fun0>: 0: 1166 mov r5, -(sp) 2: 1185 mov sp, r5 4: 0bf5 0004 tst 4(r5) 8: 0304 beq 12 <_fun0+0x12> a: 15c0 0006 mov $6, r0 e: 1585 mov (sp)+, r5 10: 0087 rts pc 12: 15c0 0005 mov $5, r0 16: 1585 mov (sp)+, r5 18: 0087 rts pc 0000001a <_fun1>: 1a: 1166 mov r5, -(sp) 1c: 1185 mov sp, r5 1e: 0bf5 0004 tst 4(r5) 22: 0204 bne 2c <_fun1+0x12> 24: 15c0 0005 mov $5, r0 28: 1585 mov (sp)+, r5 2a: 0087 rts pc 2c: 15c0 0006 mov $6, r0 30: 1585 mov (sp)+, r5 32: 0087 rts pc 00000034 <_fun2>: 34: 1166 mov r5, -(sp) 36: 1185 mov sp, r5 38: 0bf5 0004 tst 4(r5) 3c: 0204 bne 46 <_fun2+0x12> 3e: 15c0 0005 mov $5, r0 42: 1585 mov (sp)+, r5 44: 0087 rts pc 46: 15c0 0006 mov $6, r0 4a: 1585 mov (sp)+, r5 4c: 0087 rts pc 00000000 <fun0>: 0: 00a03533 snez x10,x10 4: 0515 addi x10,x10,5 6: 8082 ret 00000008 <fun1>: 8: 00a03533 snez x10,x10 c: 0515 addi x10,x10,5 e: 8082 ret 00000010 <fun2>: 10: 00a03533 snez x10,x10 14: 0515 addi x10,x10,5 16: 8082 ret ``` and compilers with this i code one would expect the different targets to match as well ``` define i32 @fun0(i32 %condition, i32 %value) #0 { %1 = icmp ne i32 %condition, 0 %. = select i1 %1, i32 6, i32 5 ret i32 %. } ; Function Attrs: norecurse nounwind readnone define i32 @fun1(i32 %condition, i32 %value) #0 { %1 = icmp eq i32 %condition, 0 %. = select i1 %1, i32 5, i32 6 ret i32 %. } ; Function Attrs: norecurse nounwind readnone define i32 @fun2(i32 %condition, i32 %value) #0 { %1 = icmp ne i32 %condition, 0 %2 = select i1 %1, i32 6, i32 5 ret i32 %2 } 00000000 <fun0>: 0: e3a01005 mov r1, #5 4: e3500000 cmp r0, #0 8: 13a01006 movne r1, #6 c: e1a00001 mov r0, r1 10: e12fff1e bx lr 00000014 <fun1>: 14: e3a01006 mov r1, #6 18: e3500000 cmp r0, #0 1c: 03a01005 moveq r1, #5 20: e1a00001 mov r0, r1 24: e12fff1e bx lr 00000028 <fun2>: 28: e3a01005 mov r1, #5 2c: e3500000 cmp r0, #0 30: 13a01006 movne r1, #6 34: e1a00001 mov r0, r1 38: e12fff1e bx lr fun0: push.w r4 mov.w r1, r4 mov.w r15, r12 mov.w #6, r15 cmp.w #0, r12 jne .LBB0_2 mov.w #5, r15 .LBB0_2: pop.w r4 ret fun1: push.w r4 mov.w r1, r4 mov.w r15, r12 mov.w #5, r15 cmp.w #0, r12 jeq .LBB1_2 mov.w #6, r15 .LBB1_2: pop.w r4 ret fun2: push.w r4 mov.w r1, r4 mov.w r15, r12 mov.w #6, r15 cmp.w #0, r12 jne .LBB2_2 mov.w #5, r15 .LBB2_2: pop.w r4 ret ``` Now technically there is a performance difference in some of these solutions, sometimes the result is 5 case has a jump over the result is 6 code, and vice versa, is a branch faster than executing through? one could argue but the execution should vary. But that is more of an if condition vs if not condition in the code resulting in the compiler doing the if this jump over else execute through. but this is not necessarily due to the coding style but the comparison and the if and the else cases in whatever syntax.
43,202,012
I argued with a friend the other day about those two snippets. Which is faster and why ? ``` value = 5; if (condition) { value = 6; } ``` and: ``` if (condition) { value = 6; } else { value = 5; } ``` What if `value` is a matrix ? Note: I know that `value = condition ? 6 : 5;` exists and I expect it to be faster, but it wasn't an option. **Edit** (requested by staff since question is on hold at the moment): * please answer by considering either *x86 assembly* generated by mainstream compilers (*say g++, clang++, vc, mingw*) in both optimized and non optimized versions or *MIPS assembly*. * when assembly differ, explain why a version is faster and when (*e.g. "better because no branching and branching has following issue blahblah"*)
2017/04/04
[ "https://Stackoverflow.com/questions/43202012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3439945/" ]
In unoptimised code, the first example assigns a variable always once and sometimes twice. The second example only ever assigns a variable once. The conditional is the same on both code paths, so that shouldn't matter. In optimised code, it depends on the compiler. As always, if you are that concerned, generate the assembly and see what the compiler is actually doing.
Ok, since assembly is one of the tags, I will just assume your code is pseudo code (and not necessarily c) and translate it by human into 6502 assembly. 1st Option (without else) ``` ldy #$00 lda #$05 dey bmi false lda #$06 false brk ``` 2nd Option (with else) ``` ldy #$00 dey bmi else lda #$06 sec bcs end else lda #$05 end brk ``` Assumptions: Condition is in Y register set this to 0 or 1 on the first line of either option, result will be in accumulator. So, after counting cycles for both possibilities of each case, we see that the 1st construct is generally faster; 9 cycles when condition is 0 and 10 cycles when condition is 1, whereas option two is also 9 cycles when condition is 0, but 13 cycles when condition is 1. (*cycle counts do not include the `BRK` at the end*). **Conclusion: `If only` is faster than `If-Else` construct.** And for completeness, here is an optimized `value = condition + 5` solution: ``` ldy #$00 lda #$00 tya adc #$05 brk ``` This cuts our time down to 8 cycles (*again not including the `BRK` at the end*).
43,202,012
I argued with a friend the other day about those two snippets. Which is faster and why ? ``` value = 5; if (condition) { value = 6; } ``` and: ``` if (condition) { value = 6; } else { value = 5; } ``` What if `value` is a matrix ? Note: I know that `value = condition ? 6 : 5;` exists and I expect it to be faster, but it wasn't an option. **Edit** (requested by staff since question is on hold at the moment): * please answer by considering either *x86 assembly* generated by mainstream compilers (*say g++, clang++, vc, mingw*) in both optimized and non optimized versions or *MIPS assembly*. * when assembly differ, explain why a version is faster and when (*e.g. "better because no branching and branching has following issue blahblah"*)
2017/04/04
[ "https://Stackoverflow.com/questions/43202012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3439945/" ]
The answer from [CompuChip](https://stackoverflow.com/a/43202221/2805305) shows that for `int` they both are optimized to the same assembly, so it doesn't matter. > > What if value is a matrix ? > > > I will interpret this in a more general way, i.e. what if `value` is of a type whose constructions and assignments are expensive (and moves are cheap). then ``` T value = init1; if (condition) value = init2; ``` is sub-optimal because in case `condition` is true, you do the unnecessary initialization to `init1` and then you do the copy assignment. ``` T value; if (condition) value = init2; else value = init3; ``` This is better. But still sub-optimal if default construction is expensive and if copy construction is more expensive then initialization. You have the conditional operator solution which is good: ``` T value = condition ? init1 : init2; ``` Or, if you don't like the conditional operator, you can create a helper function like this: ``` T create(bool condition) { if (condition) return {init1}; else return {init2}; } T value = create(condition); ``` Depending on what `init1` and `init2` are you can also consider this: ``` auto final_init = condition ? init1 : init2; T value = final_init; ``` But again I must emphasize that this is relevant only when construction and assignments are really expensive for the given type. And even then, only by **profiling** you know for sure.
In pseudo-assembly language, ```none li #0, r0 test r1 beq L1 li #1, r0 L1: ``` *may or may not* be faster than ```none test r1 beq L1 li #1, r0 bra L2 L1: li #0, r0 L2: ``` depending on how sophisticated the actual CPU is. Going from simplest to fanciest: * With *any* CPU manufactured after roughly 1990, good performance depends on the code fitting within the [instruction cache](https://en.wikipedia.org/wiki/Cache_memory). When in doubt, therefore, minimize code size. This weighs in favor of the first example. * With a basic "[in-order, five-stage pipeline](https://en.wikipedia.org/wiki/Classic_RISC_pipeline)" CPU, which is still roughly what you get in many microcontrollers, there is a [pipeline bubble](https://en.wikipedia.org/wiki/Bubble_%28computing%29) every time a branch—conditional or unconditional—is taken, so it is also important to minimize the number of branch instructions. This also weighs in favor of the first example. * Somewhat more sophisticated CPUs—fancy enough to do "[out-of-order execution](https://en.wikipedia.org/wiki/Out-of-order_execution)", but not fancy enough to use the best known implementations of that concept—may incur pipeline bubbles whenever they encounter [write-after-write hazards](https://en.wikipedia.org/wiki/Hazard_%28computer_architecture%29#Write_after_write_.28WAW.29). This weighs in favor of the *second* example, where `r0` is written only once no matter what. These CPUs are usually fancy enough to process unconditional branches in the instruction fetcher, so you *aren't* just trading the write-after-write penalty for a branch penalty. I don't know if anyone is still making this kind of CPU anymore. However, the CPUs that *do* use the "best known implementations" of out-of-order execution are likely to cut corners on the less frequently used instructions, so you need to be aware that this sort of thing can happen. A real example is [false data dependencies on the destination registers in `popcnt` and `lzcnt` on Sandy Bridge CPUs](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62011). * At the highest end, the OOO engine will wind up issuing exactly the same sequence of internal operations for both code fragments—this is the hardware version of "don't worry about it, the compiler will generate the same machine code either way." However, code size still does matter, and now you also should be worrying about the predictability of the conditional branch. [Branch prediction](https://en.wikipedia.org/wiki/Branch_predictor) failures potentially cause a complete pipeline *flush*, which is catastrophic for performance; see [Why is it faster to process a sorted array than an unsorted array?](https://stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array) to understand how much difference this can make. If the branch *is* highly unpredictable, and your CPU has conditional-set or conditional-move instructions, this is the time to use them: ```none li #0, r0 test r1 setne r0 ``` or ```none li #0, r0 li #1, r2 test r1 movne r2, r0 ``` The conditional-set version is also more compact than any other alternative; if that instruction is available it is practically guaranteed to be the Right Thing for this scenario, even if the branch was predictable. The conditional-move version requires an additional scratch register, and always wastes one `li` instruction's worth of dispatch and execute resources; if the branch was in fact predictable, the branchy version may well be faster.
43,202,012
I argued with a friend the other day about those two snippets. Which is faster and why ? ``` value = 5; if (condition) { value = 6; } ``` and: ``` if (condition) { value = 6; } else { value = 5; } ``` What if `value` is a matrix ? Note: I know that `value = condition ? 6 : 5;` exists and I expect it to be faster, but it wasn't an option. **Edit** (requested by staff since question is on hold at the moment): * please answer by considering either *x86 assembly* generated by mainstream compilers (*say g++, clang++, vc, mingw*) in both optimized and non optimized versions or *MIPS assembly*. * when assembly differ, explain why a version is faster and when (*e.g. "better because no branching and branching has following issue blahblah"*)
2017/04/04
[ "https://Stackoverflow.com/questions/43202012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3439945/" ]
**TL;DR:** In unoptimized code, `if` without `else` seems irrelevantly more efficient but with even the most basic level of optimization enabled the code is basically rewritten to `value = condition + 5`. --- I [gave it a try](https://gcc.godbolt.org/) and generated the assembly for the following code: ``` int ifonly(bool condition, int value) { value = 5; if (condition) { value = 6; } return value; } int ifelse(bool condition, int value) { if (condition) { value = 6; } else { value = 5; } return value; } ``` On gcc 6.3 with optimizations disabled (`-O0`), the relevant difference is: ``` mov DWORD PTR [rbp-8], 5 cmp BYTE PTR [rbp-4], 0 je .L2 mov DWORD PTR [rbp-8], 6 .L2: mov eax, DWORD PTR [rbp-8] ``` for `ifonly`, while `ifelse` has ``` cmp BYTE PTR [rbp-4], 0 je .L5 mov DWORD PTR [rbp-8], 6 jmp .L6 .L5: mov DWORD PTR [rbp-8], 5 .L6: mov eax, DWORD PTR [rbp-8] ``` The latter looks slightly less efficient because it has an extra jump but both have at least two and at most three assignments so unless you really need to squeeze every last drop of performance (hint: unless you are working on a space shuttle you don't, and even then you *probably* don't) the difference won't be noticeable. However, even with the lowest optimization level (`-O1`) both functions reduce to the same: ``` test dil, dil setne al movzx eax, al add eax, 5 ``` which is basically the equivalent of ``` return 5 + condition; ``` assuming `condition` is zero or one. Higher optimization levels don't really change the output, except they manage to avoid the `movzx` by efficiently zeroing out the `EAX` register at the start. --- **Disclaimer:** You probably shouldn't write `5 + condition` yourself (even though the standard guarantees that converting `true` to an integer type gives `1`) because your intent might not be immediately obvious to people reading your code (which may include your future self). The point of this code is to show that what the compiler produces in both cases is (practically) identical. [Ciprian Tomoiaga](https://stackoverflow.com/questions/43202012/if-statement-vs-if-else-statement-which-is-faster/43202221?noredirect=1#comment73501865_43202221) states it quite well in the comments: > > a **human**'s job is to write code **for humans** and let the **compiler** write code for **the machine**. > > >
In pseudo-assembly language, ```none li #0, r0 test r1 beq L1 li #1, r0 L1: ``` *may or may not* be faster than ```none test r1 beq L1 li #1, r0 bra L2 L1: li #0, r0 L2: ``` depending on how sophisticated the actual CPU is. Going from simplest to fanciest: * With *any* CPU manufactured after roughly 1990, good performance depends on the code fitting within the [instruction cache](https://en.wikipedia.org/wiki/Cache_memory). When in doubt, therefore, minimize code size. This weighs in favor of the first example. * With a basic "[in-order, five-stage pipeline](https://en.wikipedia.org/wiki/Classic_RISC_pipeline)" CPU, which is still roughly what you get in many microcontrollers, there is a [pipeline bubble](https://en.wikipedia.org/wiki/Bubble_%28computing%29) every time a branch—conditional or unconditional—is taken, so it is also important to minimize the number of branch instructions. This also weighs in favor of the first example. * Somewhat more sophisticated CPUs—fancy enough to do "[out-of-order execution](https://en.wikipedia.org/wiki/Out-of-order_execution)", but not fancy enough to use the best known implementations of that concept—may incur pipeline bubbles whenever they encounter [write-after-write hazards](https://en.wikipedia.org/wiki/Hazard_%28computer_architecture%29#Write_after_write_.28WAW.29). This weighs in favor of the *second* example, where `r0` is written only once no matter what. These CPUs are usually fancy enough to process unconditional branches in the instruction fetcher, so you *aren't* just trading the write-after-write penalty for a branch penalty. I don't know if anyone is still making this kind of CPU anymore. However, the CPUs that *do* use the "best known implementations" of out-of-order execution are likely to cut corners on the less frequently used instructions, so you need to be aware that this sort of thing can happen. A real example is [false data dependencies on the destination registers in `popcnt` and `lzcnt` on Sandy Bridge CPUs](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=62011). * At the highest end, the OOO engine will wind up issuing exactly the same sequence of internal operations for both code fragments—this is the hardware version of "don't worry about it, the compiler will generate the same machine code either way." However, code size still does matter, and now you also should be worrying about the predictability of the conditional branch. [Branch prediction](https://en.wikipedia.org/wiki/Branch_predictor) failures potentially cause a complete pipeline *flush*, which is catastrophic for performance; see [Why is it faster to process a sorted array than an unsorted array?](https://stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array) to understand how much difference this can make. If the branch *is* highly unpredictable, and your CPU has conditional-set or conditional-move instructions, this is the time to use them: ```none li #0, r0 test r1 setne r0 ``` or ```none li #0, r0 li #1, r2 test r1 movne r2, r0 ``` The conditional-set version is also more compact than any other alternative; if that instruction is available it is practically guaranteed to be the Right Thing for this scenario, even if the branch was predictable. The conditional-move version requires an additional scratch register, and always wastes one `li` instruction's worth of dispatch and execute resources; if the branch was in fact predictable, the branchy version may well be faster.
155,428
Our Wordpress website was hacked. I couldn't find anything intelligible from my limited experience from the limited logs my hosting gives. However, browsing in the FTP files I found a post.php file in the root and two more themes. Nothing strange in the DB, nor a new user. In the index I found the string "Silence is golden". I spent my day reading about it and it seems one of the most classic WP attacks. The server hosts a directory of the root where there is a form powered by AppGini, which relies on another DB and is loaded in an iframe in the Wordpress pages. This form is not password protected, however AppGini ships by default protection of MySQL injection. In your opinion, could this form be the door to enter the WP installation? Is this technically possible? Or is it a 100% Wordpress attack, regardless of what is beside it?
2017/03/31
[ "https://security.stackexchange.com/questions/155428", "https://security.stackexchange.com", "https://security.stackexchange.com/users/143619/" ]
the entry points for attacker can include: outdated - PHP, themes, plugins, weak passwords, misconfigured php.ini file that can lead to issues. Please check if any of these have been overlooked.
The best practise to put in place is to ensure that your wordpress and its plugins are updated at a regular interval , i prefer to check for update every 10 days. Given the scenario there do not seem to be any APPgini based exploits available publically and my guess would be a vulnerability in the plugins that might have been installed. Also i suggest if there are a limited people accessing the panel make use of a 2FA. Coming to the point , this could be a wordpress plugin exploit. An exact guess cannot be given because i dont know what plugins and what version were installed on your wordpress. But yes , there are reverse shell php scripts available through which a limited shell access can be obtained.
155,428
Our Wordpress website was hacked. I couldn't find anything intelligible from my limited experience from the limited logs my hosting gives. However, browsing in the FTP files I found a post.php file in the root and two more themes. Nothing strange in the DB, nor a new user. In the index I found the string "Silence is golden". I spent my day reading about it and it seems one of the most classic WP attacks. The server hosts a directory of the root where there is a form powered by AppGini, which relies on another DB and is loaded in an iframe in the Wordpress pages. This form is not password protected, however AppGini ships by default protection of MySQL injection. In your opinion, could this form be the door to enter the WP installation? Is this technically possible? Or is it a 100% Wordpress attack, regardless of what is beside it?
2017/03/31
[ "https://security.stackexchange.com/questions/155428", "https://security.stackexchange.com", "https://security.stackexchange.com/users/143619/" ]
the entry points for attacker can include: outdated - PHP, themes, plugins, weak passwords, misconfigured php.ini file that can lead to issues. Please check if any of these have been overlooked.
found the complete Log in another Post of you. Here is what I read from it: The GET Request for the Files wp-login.php from 91.210.145.98 (Windows 10 64Bit, with probably Mozilla Firefox 50) is 200 200 = HTTP Statuscode = OK which means successfull. The POST of the Login Data was successfull. (A interesting thing is, that i dont see any Bruteforce signs in the LOG you posted). The Attacker is now successfull logged in (access to wp-admin) The Attacker opens the Theme Editor. (/wp-admin/theme-editor.php) The Attacker checks if the Theme TwentyFourteen already exists. ( /wp-admin/theme-editor.php?file=404.php&theme=twentyfourteen) The Attacker opens the Page to upload a Theme. The Attacker binds an Wordpress Remote Shell to the database.php of the Theme Gaukingo (Wordpress Shell Uploader\gaukingo) and uploads it. The Attacker binds an Wordpress Remote Shell to the db.php of the Plugin three-column-screen-layout (three-column-screen-layout/db.php) and uploads it. He checks if the File GET /wp-content/uploads/db.php already exist but gets an HTTP 404 which means Not Found. He does the same with /wp-content/uploads/2017/23/db.php. He issues an HEAD Request which means he just recieves Homepage Header Data, which is faster for example if you want to recieve Data in a Linux-Shell. Maybe he is using a Program like Metasploit from now on because he has way more possibel Browsers (Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45) - He logs on via wp-login.php - He opens the Page to upload a Theme - He checks if the Theme sketch is already installed text here **After I read the Log I think he is trying to use a weakness in outdated but still installed Plugins and Themes. I think it's the best to secure your Wordpress in the future as suggested in the Comments.** ``` [30/Mar/2017:13:52:56 +0100] "GET /wp-login.php HTTP/1.1" 200 2752 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:52:57 +0100] "POST /wp-login.php HTTP/1.1" 302 1136 "http://*************.com.it/wp-login.php" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:52:58 +0100] "GET /wp-admin/ HTTP/1.1" 200 62061 "http://*************.com.it/wp-login.php" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:52:59 +0100] "GET /wp-admin/theme-editor.php HTTP/1.1" 200 38782 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:00 +0100] "GET /wp-admin/theme-editor.php?file=404.php&theme=twentyfourteen HTTP/1.1" 500 3785 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:01 +0100] "GET /wp-admin/theme-install.php?upload HTTP/1.1" 200 52466 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:02 +0100] "POST /wp-admin/update.php?action=upload-theme HTTP/1.1" 200 31812 "*************.com.it/wp-admin/theme-install.php?upload" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:07 +0100] "GET /wp-content/themes/F:\xc4\xee\xf0\xee\xe3\xee\xf1\xf2\xee\xff\xf9\xe8\xe5\MultiShell2\xf8\xe5\xeb\xeb\xfb\xcf\xee\xea\xf3\xef\xed\xee\xe9 \xf1\xee\xf4\xf2\uploader\Wordpress Shell Uploader\gaukingo/db.php HTTP/1.1" 404 51872 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:08 +0100] "GET /wp-admin/plugin-install.php?tab=upload HTTP/1.1" 200 40682 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:09 +0100] "POST /wp-admin/update.php?action=upload-plugin HTTP/1.1" 200 31541 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:15 +0100] "GET /wp-content/plugins/F:\xc4\xee\xf0\xee\xe3\xee\xf1\xf2\xee\xff\xf9\xe8\xe5\MultiShell2\xf8\xe5\xeb\xeb\xfb\xcf\xee\xea\xf3\xef\xed\xee\xe9 \xf1\xee\xf4\xf2\uploader\Wordpress Shell Uploader\three-column-screen-layout/db.php HTTP/1.1" 404 51874 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:16 +0100] "POST /wp-admin/update.php?action=upload-plugin HTTP/1.1" 200 31426 "*************.com.it/wp-admin/theme-install.php?tab=upload" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:19 +0100] "GET /wp-content/uploads/db.php HTTP/1.1" 404 51729 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:20 +0100] "GET /wp-content/uploads/2017/23/db.php HTTP/1.1" 404 51753 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:58:22 +0100] "HEAD /wp-login.php HTTP/1.1" 200 343 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" 91.210.145.98 - - [30/Mar/2017:13:58:23 +0100] "GET /wp-login.php HTTP/1.1" 200 2697 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" 91.210.145.98 - - [30/Mar/2017:13:58:23 +0100] "POST /wp-login.php HTTP/1.0" 302 1305 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" 91.210.145.98 - - [30/Mar/2017:13:58:24 +0100] "POST /wp-admin/ HTTP/1.0" 200 61984 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" 91.210.145.98 - - [30/Mar/2017:13:58:25 +0100] "GET /wp-admin/theme-install.php HTTP/1.1" 200 52420 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" 91.210.145.98 - - [30/Mar/2017:13:58:27 +0100] "POST /wp-admin/update.php?action=upload-theme HTTP/1.0" 200 32257 "http://*************.com.it/wp-admin/theme-install.php?upload" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" 91.210.145.98 - - [30/Mar/2017:13:58:33 +0100] "GET /wp-content/themes/sketch/404.php HTTP/1.1" 200 377 "http://*************.com.it/wp-admin/theme-install.php?upload" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" ```
155,428
Our Wordpress website was hacked. I couldn't find anything intelligible from my limited experience from the limited logs my hosting gives. However, browsing in the FTP files I found a post.php file in the root and two more themes. Nothing strange in the DB, nor a new user. In the index I found the string "Silence is golden". I spent my day reading about it and it seems one of the most classic WP attacks. The server hosts a directory of the root where there is a form powered by AppGini, which relies on another DB and is loaded in an iframe in the Wordpress pages. This form is not password protected, however AppGini ships by default protection of MySQL injection. In your opinion, could this form be the door to enter the WP installation? Is this technically possible? Or is it a 100% Wordpress attack, regardless of what is beside it?
2017/03/31
[ "https://security.stackexchange.com/questions/155428", "https://security.stackexchange.com", "https://security.stackexchange.com/users/143619/" ]
Sure, if there is a PHP script which allows code execution - eg via command injection, file upload, etc - on the same server then an attacker can use that to gain access to the WordPress installation. The same is true for directory traversal vulnerabilities. (Assuming that you do not take any measure to separate different applications such as different virtual machines) If a separate script contains an SQL injection, that could also lead to access to WordPress, depending on the setup of the database permissions. If the script is on the same domain, XSS could also be exploited. I'm not familiar with AppGini, and I do not know what kind of form you are using, but as it is some kind of development/code generation tool with a browser-based administration GUI, any form really should be password protected. We can't tell you how an attacker gained access (@K BHATTs answer covers the most common issues), but this also seems like a likely attack vector. "Silence is golden" index.php files are from WordPress. They are not a sign of anything, they are just there to prevent directory listing.
The best practise to put in place is to ensure that your wordpress and its plugins are updated at a regular interval , i prefer to check for update every 10 days. Given the scenario there do not seem to be any APPgini based exploits available publically and my guess would be a vulnerability in the plugins that might have been installed. Also i suggest if there are a limited people accessing the panel make use of a 2FA. Coming to the point , this could be a wordpress plugin exploit. An exact guess cannot be given because i dont know what plugins and what version were installed on your wordpress. But yes , there are reverse shell php scripts available through which a limited shell access can be obtained.
155,428
Our Wordpress website was hacked. I couldn't find anything intelligible from my limited experience from the limited logs my hosting gives. However, browsing in the FTP files I found a post.php file in the root and two more themes. Nothing strange in the DB, nor a new user. In the index I found the string "Silence is golden". I spent my day reading about it and it seems one of the most classic WP attacks. The server hosts a directory of the root where there is a form powered by AppGini, which relies on another DB and is loaded in an iframe in the Wordpress pages. This form is not password protected, however AppGini ships by default protection of MySQL injection. In your opinion, could this form be the door to enter the WP installation? Is this technically possible? Or is it a 100% Wordpress attack, regardless of what is beside it?
2017/03/31
[ "https://security.stackexchange.com/questions/155428", "https://security.stackexchange.com", "https://security.stackexchange.com/users/143619/" ]
Sure, if there is a PHP script which allows code execution - eg via command injection, file upload, etc - on the same server then an attacker can use that to gain access to the WordPress installation. The same is true for directory traversal vulnerabilities. (Assuming that you do not take any measure to separate different applications such as different virtual machines) If a separate script contains an SQL injection, that could also lead to access to WordPress, depending on the setup of the database permissions. If the script is on the same domain, XSS could also be exploited. I'm not familiar with AppGini, and I do not know what kind of form you are using, but as it is some kind of development/code generation tool with a browser-based administration GUI, any form really should be password protected. We can't tell you how an attacker gained access (@K BHATTs answer covers the most common issues), but this also seems like a likely attack vector. "Silence is golden" index.php files are from WordPress. They are not a sign of anything, they are just there to prevent directory listing.
found the complete Log in another Post of you. Here is what I read from it: The GET Request for the Files wp-login.php from 91.210.145.98 (Windows 10 64Bit, with probably Mozilla Firefox 50) is 200 200 = HTTP Statuscode = OK which means successfull. The POST of the Login Data was successfull. (A interesting thing is, that i dont see any Bruteforce signs in the LOG you posted). The Attacker is now successfull logged in (access to wp-admin) The Attacker opens the Theme Editor. (/wp-admin/theme-editor.php) The Attacker checks if the Theme TwentyFourteen already exists. ( /wp-admin/theme-editor.php?file=404.php&theme=twentyfourteen) The Attacker opens the Page to upload a Theme. The Attacker binds an Wordpress Remote Shell to the database.php of the Theme Gaukingo (Wordpress Shell Uploader\gaukingo) and uploads it. The Attacker binds an Wordpress Remote Shell to the db.php of the Plugin three-column-screen-layout (three-column-screen-layout/db.php) and uploads it. He checks if the File GET /wp-content/uploads/db.php already exist but gets an HTTP 404 which means Not Found. He does the same with /wp-content/uploads/2017/23/db.php. He issues an HEAD Request which means he just recieves Homepage Header Data, which is faster for example if you want to recieve Data in a Linux-Shell. Maybe he is using a Program like Metasploit from now on because he has way more possibel Browsers (Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45) - He logs on via wp-login.php - He opens the Page to upload a Theme - He checks if the Theme sketch is already installed text here **After I read the Log I think he is trying to use a weakness in outdated but still installed Plugins and Themes. I think it's the best to secure your Wordpress in the future as suggested in the Comments.** ``` [30/Mar/2017:13:52:56 +0100] "GET /wp-login.php HTTP/1.1" 200 2752 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:52:57 +0100] "POST /wp-login.php HTTP/1.1" 302 1136 "http://*************.com.it/wp-login.php" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:52:58 +0100] "GET /wp-admin/ HTTP/1.1" 200 62061 "http://*************.com.it/wp-login.php" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:52:59 +0100] "GET /wp-admin/theme-editor.php HTTP/1.1" 200 38782 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:00 +0100] "GET /wp-admin/theme-editor.php?file=404.php&theme=twentyfourteen HTTP/1.1" 500 3785 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:01 +0100] "GET /wp-admin/theme-install.php?upload HTTP/1.1" 200 52466 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:02 +0100] "POST /wp-admin/update.php?action=upload-theme HTTP/1.1" 200 31812 "*************.com.it/wp-admin/theme-install.php?upload" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:07 +0100] "GET /wp-content/themes/F:\xc4\xee\xf0\xee\xe3\xee\xf1\xf2\xee\xff\xf9\xe8\xe5\MultiShell2\xf8\xe5\xeb\xeb\xfb\xcf\xee\xea\xf3\xef\xed\xee\xe9 \xf1\xee\xf4\xf2\uploader\Wordpress Shell Uploader\gaukingo/db.php HTTP/1.1" 404 51872 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:08 +0100] "GET /wp-admin/plugin-install.php?tab=upload HTTP/1.1" 200 40682 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:09 +0100] "POST /wp-admin/update.php?action=upload-plugin HTTP/1.1" 200 31541 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:15 +0100] "GET /wp-content/plugins/F:\xc4\xee\xf0\xee\xe3\xee\xf1\xf2\xee\xff\xf9\xe8\xe5\MultiShell2\xf8\xe5\xeb\xeb\xfb\xcf\xee\xea\xf3\xef\xed\xee\xe9 \xf1\xee\xf4\xf2\uploader\Wordpress Shell Uploader\three-column-screen-layout/db.php HTTP/1.1" 404 51874 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:16 +0100] "POST /wp-admin/update.php?action=upload-plugin HTTP/1.1" 200 31426 "*************.com.it/wp-admin/theme-install.php?tab=upload" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:19 +0100] "GET /wp-content/uploads/db.php HTTP/1.1" 404 51729 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:53:20 +0100] "GET /wp-content/uploads/2017/23/db.php HTTP/1.1" 404 51753 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0" 91.210.145.98 - - [30/Mar/2017:13:58:22 +0100] "HEAD /wp-login.php HTTP/1.1" 200 343 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" 91.210.145.98 - - [30/Mar/2017:13:58:23 +0100] "GET /wp-login.php HTTP/1.1" 200 2697 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" 91.210.145.98 - - [30/Mar/2017:13:58:23 +0100] "POST /wp-login.php HTTP/1.0" 302 1305 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" 91.210.145.98 - - [30/Mar/2017:13:58:24 +0100] "POST /wp-admin/ HTTP/1.0" 200 61984 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" 91.210.145.98 - - [30/Mar/2017:13:58:25 +0100] "GET /wp-admin/theme-install.php HTTP/1.1" 200 52420 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" 91.210.145.98 - - [30/Mar/2017:13:58:27 +0100] "POST /wp-admin/update.php?action=upload-theme HTTP/1.0" 200 32257 "http://*************.com.it/wp-admin/theme-install.php?upload" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" 91.210.145.98 - - [30/Mar/2017:13:58:33 +0100] "GET /wp-content/themes/sketch/404.php HTTP/1.1" 200 377 "http://*************.com.it/wp-admin/theme-install.php?upload" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.45" ```
6,662,087
I'm making an flight search app with Sencha Touch and have encountered a small problem. I want to create a textfield for all the airports and need autocomplete functionality for in order to make it easy for the user to choose departure airport and return airport. How can i implement this? The airports will be loaded via XML-schema and I can't seem to find any good documentation for this feature. Thanx in advance!
2011/07/12
[ "https://Stackoverflow.com/questions/6662087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618162/" ]
Since there were no custom components out there and I needed something like this myself as well, I smashed it together. So, here it is. **Sencha Touch 2 Autocomplete Textfield component:** <https://github.com/martintajur/sencha-touch-2-autocomplete-textfield> It currently uses AJAX request response for populating the autocomplete matches. It also supports custom input by the user. When serializing the form data, the value of this type of input will be: * the selected item ID in case user has selected a matched autocomplete result * the typed text when the user has not chosen an autocomplete result It is very basic at the moment and completely driven by own need for such a control. Feel free to fork, modify, adapt. It's MIT-licenced.
I think you should use a searchfield instead of textfield as suggested by @Ismailp, Then you should create a popup(a panel) in its keyup event, which should contain a list of Airports. Go through the hidden folder list-search in the example folder in downloaded sencha framework.It shows how to search through a list.
5,209,031
I'm trying to make a C++ library available as a Python module. It seems SIP is the best tool for the job. (If wrong, please correct me.) One class looks like the programmer was trying to get around c's lack of dynamic typing: ``` class Item{ private: enum ITEMTYPE{TYPE_INT,TYPE_FLOAT,TYPE_INT_ARRAY,TYPE_FLOAT_ARRAY}; enum ITEMTYPE type; int intValue; int* intArrayValue; float floatValue; float* floatArrayValue; public: enum ITEMTYPE getType(); int getItemCount(); int getIntValue(); int* getIntArrayValue(); float getFloatValue(); float* getFloatArrayValue(); ... }; ``` I can't find documentation anywhere that says how to handle functions that return arrays. At minimum, I'd like to be able to call getIntArrayValue() from Python. Even better would be to have a single Python function that automatically calls getType(), then calls one of the get???Value() to get the value (and if necessary, calls getItemCount() to determine the array length, treating arrays as numpy or tuples. My current .sil file looks like this: ``` class Item{ %TypeHeaderCode #include<Item.h> %End public: enum ITEMTYPE{ TYPE_INT=0, TYPE_FLOAT=1, TYPE_INT_ARRAY=2, TYPE_FLOAT_ARRAY=3, }; ITEMTYPE getType(); int getItemCount(); int getIntValue(); //int*getIntArrayValue(); float getFloatValue(); //float*getFloatArrayValue(); }; ``` Thanks in advance. I've been searching so hard, but have come up empty.
2011/03/06
[ "https://Stackoverflow.com/questions/5209031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/360886/" ]
There are 26 characters, So you can use [`counting sort`](http://en.wikipedia.org/wiki/Counting_sort) to sort them, in your counting sort you can have an index which determines when specific character visited first time to save order of occurrence. [They can be sorted by their count and their occurrence with sort like radix sort]. **Edit:** by words first thing every one can think about it, is using Hash table and insert words in hash, and in this way count them, and They can be sorted in O(n), because all numbers are within 1..n steel you can sort them by counting sort in O(n), also for their occurrence you can traverse string and change position of same values.
Order of n means you traverse the string only once or some lesser multiple of n ,where n is number of characters in the string. So your solution to store the String and number of its occurences is O(n) , order of n, as you loop through the complete string only once. However it uses extra space in form of the list you created.
5,209,031
I'm trying to make a C++ library available as a Python module. It seems SIP is the best tool for the job. (If wrong, please correct me.) One class looks like the programmer was trying to get around c's lack of dynamic typing: ``` class Item{ private: enum ITEMTYPE{TYPE_INT,TYPE_FLOAT,TYPE_INT_ARRAY,TYPE_FLOAT_ARRAY}; enum ITEMTYPE type; int intValue; int* intArrayValue; float floatValue; float* floatArrayValue; public: enum ITEMTYPE getType(); int getItemCount(); int getIntValue(); int* getIntArrayValue(); float getFloatValue(); float* getFloatArrayValue(); ... }; ``` I can't find documentation anywhere that says how to handle functions that return arrays. At minimum, I'd like to be able to call getIntArrayValue() from Python. Even better would be to have a single Python function that automatically calls getType(), then calls one of the get???Value() to get the value (and if necessary, calls getItemCount() to determine the array length, treating arrays as numpy or tuples. My current .sil file looks like this: ``` class Item{ %TypeHeaderCode #include<Item.h> %End public: enum ITEMTYPE{ TYPE_INT=0, TYPE_FLOAT=1, TYPE_INT_ARRAY=2, TYPE_FLOAT_ARRAY=3, }; ITEMTYPE getType(); int getItemCount(); int getIntValue(); //int*getIntArrayValue(); float getFloatValue(); //float*getFloatArrayValue(); }; ``` Thanks in advance. I've been searching so hard, but have come up empty.
2011/03/06
[ "https://Stackoverflow.com/questions/5209031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/360886/" ]
There are 26 characters, So you can use [`counting sort`](http://en.wikipedia.org/wiki/Counting_sort) to sort them, in your counting sort you can have an index which determines when specific character visited first time to save order of occurrence. [They can be sorted by their count and their occurrence with sort like radix sort]. **Edit:** by words first thing every one can think about it, is using Hash table and insert words in hash, and in this way count them, and They can be sorted in O(n), because all numbers are within 1..n steel you can sort them by counting sort in O(n), also for their occurrence you can traverse string and change position of same values.
Order N refers to the Big O computational complexity analysis where you get a good upper bound on algorithms. It is a theory we cover early in a Data Structures class, so we can torment, I mean help the student gain facility with it as we traverse in a balanced way, heaps of different trees of knowledge, all different. In your case they want your algorithm to grow in compute time proportional to the size of the text as it grows.
5,209,031
I'm trying to make a C++ library available as a Python module. It seems SIP is the best tool for the job. (If wrong, please correct me.) One class looks like the programmer was trying to get around c's lack of dynamic typing: ``` class Item{ private: enum ITEMTYPE{TYPE_INT,TYPE_FLOAT,TYPE_INT_ARRAY,TYPE_FLOAT_ARRAY}; enum ITEMTYPE type; int intValue; int* intArrayValue; float floatValue; float* floatArrayValue; public: enum ITEMTYPE getType(); int getItemCount(); int getIntValue(); int* getIntArrayValue(); float getFloatValue(); float* getFloatArrayValue(); ... }; ``` I can't find documentation anywhere that says how to handle functions that return arrays. At minimum, I'd like to be able to call getIntArrayValue() from Python. Even better would be to have a single Python function that automatically calls getType(), then calls one of the get???Value() to get the value (and if necessary, calls getItemCount() to determine the array length, treating arrays as numpy or tuples. My current .sil file looks like this: ``` class Item{ %TypeHeaderCode #include<Item.h> %End public: enum ITEMTYPE{ TYPE_INT=0, TYPE_FLOAT=1, TYPE_INT_ARRAY=2, TYPE_FLOAT_ARRAY=3, }; ITEMTYPE getType(); int getItemCount(); int getIntValue(); //int*getIntArrayValue(); float getFloatValue(); //float*getFloatArrayValue(); }; ``` Thanks in advance. I've been searching so hard, but have come up empty.
2011/03/06
[ "https://Stackoverflow.com/questions/5209031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/360886/" ]
There are 26 characters, So you can use [`counting sort`](http://en.wikipedia.org/wiki/Counting_sort) to sort them, in your counting sort you can have an index which determines when specific character visited first time to save order of occurrence. [They can be sorted by their count and their occurrence with sort like radix sort]. **Edit:** by words first thing every one can think about it, is using Hash table and insert words in hash, and in this way count them, and They can be sorted in O(n), because all numbers are within 1..n steel you can sort them by counting sort in O(n), also for their occurrence you can traverse string and change position of same values.
It's a reference to [Big O notation](https://stackoverflow.com/questions/487258/plain-english-explanation-of-big-o). Basically the interviewer means that you have to complete the task with an O(N) algorithm.
5,209,031
I'm trying to make a C++ library available as a Python module. It seems SIP is the best tool for the job. (If wrong, please correct me.) One class looks like the programmer was trying to get around c's lack of dynamic typing: ``` class Item{ private: enum ITEMTYPE{TYPE_INT,TYPE_FLOAT,TYPE_INT_ARRAY,TYPE_FLOAT_ARRAY}; enum ITEMTYPE type; int intValue; int* intArrayValue; float floatValue; float* floatArrayValue; public: enum ITEMTYPE getType(); int getItemCount(); int getIntValue(); int* getIntArrayValue(); float getFloatValue(); float* getFloatArrayValue(); ... }; ``` I can't find documentation anywhere that says how to handle functions that return arrays. At minimum, I'd like to be able to call getIntArrayValue() from Python. Even better would be to have a single Python function that automatically calls getType(), then calls one of the get???Value() to get the value (and if necessary, calls getItemCount() to determine the array length, treating arrays as numpy or tuples. My current .sil file looks like this: ``` class Item{ %TypeHeaderCode #include<Item.h> %End public: enum ITEMTYPE{ TYPE_INT=0, TYPE_FLOAT=1, TYPE_INT_ARRAY=2, TYPE_FLOAT_ARRAY=3, }; ITEMTYPE getType(); int getItemCount(); int getIntValue(); //int*getIntArrayValue(); float getFloatValue(); //float*getFloatArrayValue(); }; ``` Thanks in advance. I've been searching so hard, but have come up empty.
2011/03/06
[ "https://Stackoverflow.com/questions/5209031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/360886/" ]
There are 26 characters, So you can use [`counting sort`](http://en.wikipedia.org/wiki/Counting_sort) to sort them, in your counting sort you can have an index which determines when specific character visited first time to save order of occurrence. [They can be sorted by their count and their occurrence with sort like radix sort]. **Edit:** by words first thing every one can think about it, is using Hash table and insert words in hash, and in this way count them, and They can be sorted in O(n), because all numbers are within 1..n steel you can sort them by counting sort in O(n), also for their occurrence you can traverse string and change position of same values.
"Order n" is referring to [Big O notation](http://en.wikipedia.org/wiki/Big_O_notation). Big O is a way for mathematicians and computer scientists to describe the behavior of a function. When someone specifies searching a string "in order n", that means that the time it takes for the function to execute grows linearly as the length of that string increases. In other words, if you plotted time of execution vs length of input, you would see a straight line. Saying that your function must be of Order n does not mean that your function must equal O(n), a function with a Big O less than O(n) would also be considered acceptable. In your problems case, this would not be possible (because in order to count a letter, you must "touch" that letter, thus there must be some operation dependent on the input size).
5,209,031
I'm trying to make a C++ library available as a Python module. It seems SIP is the best tool for the job. (If wrong, please correct me.) One class looks like the programmer was trying to get around c's lack of dynamic typing: ``` class Item{ private: enum ITEMTYPE{TYPE_INT,TYPE_FLOAT,TYPE_INT_ARRAY,TYPE_FLOAT_ARRAY}; enum ITEMTYPE type; int intValue; int* intArrayValue; float floatValue; float* floatArrayValue; public: enum ITEMTYPE getType(); int getItemCount(); int getIntValue(); int* getIntArrayValue(); float getFloatValue(); float* getFloatArrayValue(); ... }; ``` I can't find documentation anywhere that says how to handle functions that return arrays. At minimum, I'd like to be able to call getIntArrayValue() from Python. Even better would be to have a single Python function that automatically calls getType(), then calls one of the get???Value() to get the value (and if necessary, calls getItemCount() to determine the array length, treating arrays as numpy or tuples. My current .sil file looks like this: ``` class Item{ %TypeHeaderCode #include<Item.h> %End public: enum ITEMTYPE{ TYPE_INT=0, TYPE_FLOAT=1, TYPE_INT_ARRAY=2, TYPE_FLOAT_ARRAY=3, }; ITEMTYPE getType(); int getItemCount(); int getIntValue(); //int*getIntArrayValue(); float getFloatValue(); //float*getFloatArrayValue(); }; ``` Thanks in advance. I've been searching so hard, but have come up empty.
2011/03/06
[ "https://Stackoverflow.com/questions/5209031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/360886/" ]
There are 26 characters, So you can use [`counting sort`](http://en.wikipedia.org/wiki/Counting_sort) to sort them, in your counting sort you can have an index which determines when specific character visited first time to save order of occurrence. [They can be sorted by their count and their occurrence with sort like radix sort]. **Edit:** by words first thing every one can think about it, is using Hash table and insert words in hash, and in this way count them, and They can be sorted in O(n), because all numbers are within 1..n steel you can sort them by counting sort in O(n), also for their occurrence you can traverse string and change position of same values.
One possible method is to traverse the string linearly. Then create a hash and list. The idea is to use the word as the hash key and increment the value for each occurance. If the value is non-existent in the hash, add the word to the end of the list. After traversing the string, go through the list in order using the hash values as the count. The order of the algorithm is O(n). The hash lookup and list add operations are O(1) (or very close to it).
7,495,932
Sometimes I accidentally leave blank lines at the end of the file I am editing. How can I trim them on saving in Vim? ### Update Thanks guys, all solutions seem to work. Unfortunately, they all reset current cursor position, so I wrote the following function. ``` function TrimEndLines() let save_cursor = getpos(".") silent! %s#\($\n\s*\)\+\%$## call setpos('.', save_cursor) endfunction autocmd BufWritePre *.py call TrimEndLines() ```
2011/09/21
[ "https://Stackoverflow.com/questions/7495932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423585/" ]
This substitute command should do it: ``` :%s#\($\n\s*\)\+\%$## ``` Note that this removes all trailing lines that contain only whitespace. To remove only truly "empty" lines, remove the `\s*` from the above command. **EDIT** Explanation: * `\(` ..... Start a match group * `$\n` ... Match a new line (end-of-line character followed by a carriage return). * `\s*` ... Allow any amount of whitespace on this new line * `\)` ..... End the match group * `\+` ..... Allow any number of occurrences of this group (one or more). * `\%$` ... Match the end of the file Thus the regex matches any number of adjacent lines containing only whitespace, terminated only by the end of the file. The substitute command then replaces the match with a null string.
I found the previous answers using substitute caused trouble when operating on very large files and polluted my registers. Here's a function I came up with which performs better for me, and avoids polluting registers: ``` " Strip trailing empty newlines function TrimTrailingLines() let lastLine = line('$') let lastNonblankLine = prevnonblank(lastLine) if lastLine > 0 && lastNonblankLine != lastLine silent! execute lastNonblankLine + 1 . ',$delete _' endif endfunction autocmd BufWritePre <buffer> call TrimTrailingLines() ```
7,495,932
Sometimes I accidentally leave blank lines at the end of the file I am editing. How can I trim them on saving in Vim? ### Update Thanks guys, all solutions seem to work. Unfortunately, they all reset current cursor position, so I wrote the following function. ``` function TrimEndLines() let save_cursor = getpos(".") silent! %s#\($\n\s*\)\+\%$## call setpos('.', save_cursor) endfunction autocmd BufWritePre *.py call TrimEndLines() ```
2011/09/21
[ "https://Stackoverflow.com/questions/7495932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423585/" ]
You can put this into your vimrc ``` au BufWritePre *.txt $put _ | $;?\(^\s*$\)\@!?+1,$d ``` (replace `*.txt` with whatever globbing pattern you want) Detail: * `BufWritePre` is the event before writing a buffer to a file. * `$put _` appends a blank line at file end (from the always-empty register) * `|` chains Ex commands * `$;?\(^\s*$\)\@!?` goes to end of file (`$`) then (`;`) looks up backwards (`?…?`) for the first line which is not entirely blank (`\(^\s*$\)\@!`), also see `:help /\@!` for negative assertions in vim searches. * `×××+1,$` forms a range from line ×××+1 till the last line * `d` deletes the line range.
Inspired by solution from @Prince Goulash, add the following to your `~/.vimrc` to remove trailing blank lines for every save for Ruby and Python files: ``` autocmd FileType ruby,python autocmd BufWritePre <buffer> :%s/\($\n\s*\)\+\%$//e ```
7,495,932
Sometimes I accidentally leave blank lines at the end of the file I am editing. How can I trim them on saving in Vim? ### Update Thanks guys, all solutions seem to work. Unfortunately, they all reset current cursor position, so I wrote the following function. ``` function TrimEndLines() let save_cursor = getpos(".") silent! %s#\($\n\s*\)\+\%$## call setpos('.', save_cursor) endfunction autocmd BufWritePre *.py call TrimEndLines() ```
2011/09/21
[ "https://Stackoverflow.com/questions/7495932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423585/" ]
This substitute command should do it: ``` :%s#\($\n\s*\)\+\%$## ``` Note that this removes all trailing lines that contain only whitespace. To remove only truly "empty" lines, remove the `\s*` from the above command. **EDIT** Explanation: * `\(` ..... Start a match group * `$\n` ... Match a new line (end-of-line character followed by a carriage return). * `\s*` ... Allow any amount of whitespace on this new line * `\)` ..... End the match group * `\+` ..... Allow any number of occurrences of this group (one or more). * `\%$` ... Match the end of the file Thus the regex matches any number of adjacent lines containing only whitespace, terminated only by the end of the file. The substitute command then replaces the match with a null string.
I have a separated function called *Preserve* which I can call from other functions, It makes easy to use Preserve to do other stuff: ``` " remove consecutive blank lines " see Preserve function definition " another way to remove blank lines :g/^$/,/./-j " Reference: https://stackoverflow.com/a/7496112/2571881 if !exists('*DelBlankLines') fun! DelBlankLines() range if !&binary && &filetype != 'diff' call Preserve(':%s/\s\+$//e') call Preserve(':%s/^\n\{2,}/\r/ge') call Preserve(':%s/\v($\n\s*)+%$/\r/e') endif endfun endif ``` In my case, I keep at least one blank line, but not more than one, at the end of the file. ``` " Utility function that save last search and cursor position " http://technotales.wordpress.com/2010/03/31/preserve-a-vim-function-that-keeps-your-state/ " video from vimcasts.org: http://vimcasts.org/episodes/tidying-whitespace " using 'execute' command doesn't overwrite the last search pattern, so I " don't need to store and restore it. " preserve function if !exists('*Preserve') function! Preserve(command) try let l:win_view = winsaveview() "silent! keepjumps keeppatterns execute a:command silent! execute 'keeppatterns keepjumps ' . a:command finally call winrestview(l:win_view) endtry endfunction endif ``` Here's why I have a separated Preserve function: ``` command! -nargs=0 Reindent :call Preserve('exec "normal! gg=G"') " join lines keeping cursor position nnoremap J :call Preserve(':join')<CR> nnoremap <Leader>J :call Preserve(':join!')<CR> " Reloads vimrc after saving but keep cursor position if !exists('*ReloadVimrcFunction') function! ReloadVimrcFunction() call Preserve(':source $MYVIMRC') " hi Normal guibg=NONE ctermbg=NONE windo redraw echom "Reloaded init.vim" endfunction endif noremap <silent> <Leader>v :drop $MYVIMRC<cr> command! -nargs=0 ReloadVimrc :call ReloadVimrcFunction() " Strip trailing whitespaces command! Cls :call Preserve(':%s/\v\s+$//e') ``` And if by any chance you want to create an autocommand you must create a group to avoid overloading autocommands: ``` augroup removetrailingspaces au! au! BufwritePre *.md,*.py,*.sh,*.zsh,*.txt :call Preserve(':%s/\v\s+$//e') augroup END ``` This one is to change file headers (if you have any suggestions) feel free to interact: ``` " trying avoid searching history in this function if !exists('*ChangeHeader') fun! ChangeHeader() abort if line('$')>=7 call Preserve(':1,7s/\v(Last (Change|Modified)|date):\s+\zs.*/\=strftime("%b %d, %Y - %H:%M")/ei') endif endfun endif " dos2unix ^M if !exists('*Dos2unixFunction') fun! Dos2unixFunction() abort "call Preserve('%s/ $//ge') call Preserve(":%s/\x0D$//e") set ff=unix set bomb set encoding=utf-8 set fileencoding=utf-8 endfun endif com! Dos2Unix :call Dos2unixFunction() ```
7,495,932
Sometimes I accidentally leave blank lines at the end of the file I am editing. How can I trim them on saving in Vim? ### Update Thanks guys, all solutions seem to work. Unfortunately, they all reset current cursor position, so I wrote the following function. ``` function TrimEndLines() let save_cursor = getpos(".") silent! %s#\($\n\s*\)\+\%$## call setpos('.', save_cursor) endfunction autocmd BufWritePre *.py call TrimEndLines() ```
2011/09/21
[ "https://Stackoverflow.com/questions/7495932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423585/" ]
**1.** An elegant solution can be based on the `:vglobal` command (or, which is the same thing, on the `:global` with `!` modifier): ``` :v/\_s*\S/d ``` This command executes `:delete` on every line that does not have non-whitespace characters in it, as well as after it in the remaining text to the end of buffer (see `:help /\s`, `:help /\S`, and `:help /\_` to understand the pattern). Hence, the command removes the tailing *blank* lines. To delete the *empty* lines in a strict sense—as opposed to blank ones containing only whitespace—change the pattern in that `:vglobal` command as follows. ``` :v/\n*./d ``` **2.** On huge sparse files containing large blocks of consecutive whitespace characters (starting from about hundreds of kilobytes of whitespace) the above commands might have unacceptable performance. If that is the case, the same elegant idea can be used to transform that `:vglobal` commands into much faster (but perhaps less elegantly-looking) `:delete` commands with pattern-defined ranges. For blank lines: ``` :0;/^\%(\_s*\S\)\@!/,$d ``` For empty lines: ``` :0;/^\%(\n*.\)\@!/,$d ``` The essence of both commands is the same; namely, removing the lines belonging to the specified ranges, which are defined according to the following three steps: 1. Move the cursor to the first line of the buffer before interpreting the rest of the range (`0;`—see `:help :;`). The difference between `0` and `1` line numbers is that the former allows a match at the first line, when there is a search pattern used to define the ending line of the range. 2. Search for a line where the pattern describing a non-tailing blank line (`\_s*\S` or `\n*.`) does not match (negation is due to the `\@!` atom—see `:help /\@!`). Set the starting line of the range to that line. 3. Set the ending line of the range to the last line of the buffer (`,$`—see `:help :$`). **3.** To run any of the above commands on saving, trigger it using an autocommand to be fired on the `BufWrite` event (or its synonym, `BufWritePre`).
You can put this into your vimrc ``` au BufWritePre *.txt $put _ | $;?\(^\s*$\)\@!?+1,$d ``` (replace `*.txt` with whatever globbing pattern you want) Detail: * `BufWritePre` is the event before writing a buffer to a file. * `$put _` appends a blank line at file end (from the always-empty register) * `|` chains Ex commands * `$;?\(^\s*$\)\@!?` goes to end of file (`$`) then (`;`) looks up backwards (`?…?`) for the first line which is not entirely blank (`\(^\s*$\)\@!`), also see `:help /\@!` for negative assertions in vim searches. * `×××+1,$` forms a range from line ×××+1 till the last line * `d` deletes the line range.
7,495,932
Sometimes I accidentally leave blank lines at the end of the file I am editing. How can I trim them on saving in Vim? ### Update Thanks guys, all solutions seem to work. Unfortunately, they all reset current cursor position, so I wrote the following function. ``` function TrimEndLines() let save_cursor = getpos(".") silent! %s#\($\n\s*\)\+\%$## call setpos('.', save_cursor) endfunction autocmd BufWritePre *.py call TrimEndLines() ```
2011/09/21
[ "https://Stackoverflow.com/questions/7495932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423585/" ]
**1.** An elegant solution can be based on the `:vglobal` command (or, which is the same thing, on the `:global` with `!` modifier): ``` :v/\_s*\S/d ``` This command executes `:delete` on every line that does not have non-whitespace characters in it, as well as after it in the remaining text to the end of buffer (see `:help /\s`, `:help /\S`, and `:help /\_` to understand the pattern). Hence, the command removes the tailing *blank* lines. To delete the *empty* lines in a strict sense—as opposed to blank ones containing only whitespace—change the pattern in that `:vglobal` command as follows. ``` :v/\n*./d ``` **2.** On huge sparse files containing large blocks of consecutive whitespace characters (starting from about hundreds of kilobytes of whitespace) the above commands might have unacceptable performance. If that is the case, the same elegant idea can be used to transform that `:vglobal` commands into much faster (but perhaps less elegantly-looking) `:delete` commands with pattern-defined ranges. For blank lines: ``` :0;/^\%(\_s*\S\)\@!/,$d ``` For empty lines: ``` :0;/^\%(\n*.\)\@!/,$d ``` The essence of both commands is the same; namely, removing the lines belonging to the specified ranges, which are defined according to the following three steps: 1. Move the cursor to the first line of the buffer before interpreting the rest of the range (`0;`—see `:help :;`). The difference between `0` and `1` line numbers is that the former allows a match at the first line, when there is a search pattern used to define the ending line of the range. 2. Search for a line where the pattern describing a non-tailing blank line (`\_s*\S` or `\n*.`) does not match (negation is due to the `\@!` atom—see `:help /\@!`). Set the starting line of the range to that line. 3. Set the ending line of the range to the last line of the buffer (`,$`—see `:help :$`). **3.** To run any of the above commands on saving, trigger it using an autocommand to be fired on the `BufWrite` event (or its synonym, `BufWritePre`).
I have a separated function called *Preserve* which I can call from other functions, It makes easy to use Preserve to do other stuff: ``` " remove consecutive blank lines " see Preserve function definition " another way to remove blank lines :g/^$/,/./-j " Reference: https://stackoverflow.com/a/7496112/2571881 if !exists('*DelBlankLines') fun! DelBlankLines() range if !&binary && &filetype != 'diff' call Preserve(':%s/\s\+$//e') call Preserve(':%s/^\n\{2,}/\r/ge') call Preserve(':%s/\v($\n\s*)+%$/\r/e') endif endfun endif ``` In my case, I keep at least one blank line, but not more than one, at the end of the file. ``` " Utility function that save last search and cursor position " http://technotales.wordpress.com/2010/03/31/preserve-a-vim-function-that-keeps-your-state/ " video from vimcasts.org: http://vimcasts.org/episodes/tidying-whitespace " using 'execute' command doesn't overwrite the last search pattern, so I " don't need to store and restore it. " preserve function if !exists('*Preserve') function! Preserve(command) try let l:win_view = winsaveview() "silent! keepjumps keeppatterns execute a:command silent! execute 'keeppatterns keepjumps ' . a:command finally call winrestview(l:win_view) endtry endfunction endif ``` Here's why I have a separated Preserve function: ``` command! -nargs=0 Reindent :call Preserve('exec "normal! gg=G"') " join lines keeping cursor position nnoremap J :call Preserve(':join')<CR> nnoremap <Leader>J :call Preserve(':join!')<CR> " Reloads vimrc after saving but keep cursor position if !exists('*ReloadVimrcFunction') function! ReloadVimrcFunction() call Preserve(':source $MYVIMRC') " hi Normal guibg=NONE ctermbg=NONE windo redraw echom "Reloaded init.vim" endfunction endif noremap <silent> <Leader>v :drop $MYVIMRC<cr> command! -nargs=0 ReloadVimrc :call ReloadVimrcFunction() " Strip trailing whitespaces command! Cls :call Preserve(':%s/\v\s+$//e') ``` And if by any chance you want to create an autocommand you must create a group to avoid overloading autocommands: ``` augroup removetrailingspaces au! au! BufwritePre *.md,*.py,*.sh,*.zsh,*.txt :call Preserve(':%s/\v\s+$//e') augroup END ``` This one is to change file headers (if you have any suggestions) feel free to interact: ``` " trying avoid searching history in this function if !exists('*ChangeHeader') fun! ChangeHeader() abort if line('$')>=7 call Preserve(':1,7s/\v(Last (Change|Modified)|date):\s+\zs.*/\=strftime("%b %d, %Y - %H:%M")/ei') endif endfun endif " dos2unix ^M if !exists('*Dos2unixFunction') fun! Dos2unixFunction() abort "call Preserve('%s/ $//ge') call Preserve(":%s/\x0D$//e") set ff=unix set bomb set encoding=utf-8 set fileencoding=utf-8 endfun endif com! Dos2Unix :call Dos2unixFunction() ```
7,495,932
Sometimes I accidentally leave blank lines at the end of the file I am editing. How can I trim them on saving in Vim? ### Update Thanks guys, all solutions seem to work. Unfortunately, they all reset current cursor position, so I wrote the following function. ``` function TrimEndLines() let save_cursor = getpos(".") silent! %s#\($\n\s*\)\+\%$## call setpos('.', save_cursor) endfunction autocmd BufWritePre *.py call TrimEndLines() ```
2011/09/21
[ "https://Stackoverflow.com/questions/7495932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423585/" ]
**1.** An elegant solution can be based on the `:vglobal` command (or, which is the same thing, on the `:global` with `!` modifier): ``` :v/\_s*\S/d ``` This command executes `:delete` on every line that does not have non-whitespace characters in it, as well as after it in the remaining text to the end of buffer (see `:help /\s`, `:help /\S`, and `:help /\_` to understand the pattern). Hence, the command removes the tailing *blank* lines. To delete the *empty* lines in a strict sense—as opposed to blank ones containing only whitespace—change the pattern in that `:vglobal` command as follows. ``` :v/\n*./d ``` **2.** On huge sparse files containing large blocks of consecutive whitespace characters (starting from about hundreds of kilobytes of whitespace) the above commands might have unacceptable performance. If that is the case, the same elegant idea can be used to transform that `:vglobal` commands into much faster (but perhaps less elegantly-looking) `:delete` commands with pattern-defined ranges. For blank lines: ``` :0;/^\%(\_s*\S\)\@!/,$d ``` For empty lines: ``` :0;/^\%(\n*.\)\@!/,$d ``` The essence of both commands is the same; namely, removing the lines belonging to the specified ranges, which are defined according to the following three steps: 1. Move the cursor to the first line of the buffer before interpreting the rest of the range (`0;`—see `:help :;`). The difference between `0` and `1` line numbers is that the former allows a match at the first line, when there is a search pattern used to define the ending line of the range. 2. Search for a line where the pattern describing a non-tailing blank line (`\_s*\S` or `\n*.`) does not match (negation is due to the `\@!` atom—see `:help /\@!`). Set the starting line of the range to that line. 3. Set the ending line of the range to the last line of the buffer (`,$`—see `:help :$`). **3.** To run any of the above commands on saving, trigger it using an autocommand to be fired on the `BufWrite` event (or its synonym, `BufWritePre`).
Inspired by solution from @Prince Goulash, add the following to your `~/.vimrc` to remove trailing blank lines for every save for Ruby and Python files: ``` autocmd FileType ruby,python autocmd BufWritePre <buffer> :%s/\($\n\s*\)\+\%$//e ```
7,495,932
Sometimes I accidentally leave blank lines at the end of the file I am editing. How can I trim them on saving in Vim? ### Update Thanks guys, all solutions seem to work. Unfortunately, they all reset current cursor position, so I wrote the following function. ``` function TrimEndLines() let save_cursor = getpos(".") silent! %s#\($\n\s*\)\+\%$## call setpos('.', save_cursor) endfunction autocmd BufWritePre *.py call TrimEndLines() ```
2011/09/21
[ "https://Stackoverflow.com/questions/7495932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423585/" ]
**1.** An elegant solution can be based on the `:vglobal` command (or, which is the same thing, on the `:global` with `!` modifier): ``` :v/\_s*\S/d ``` This command executes `:delete` on every line that does not have non-whitespace characters in it, as well as after it in the remaining text to the end of buffer (see `:help /\s`, `:help /\S`, and `:help /\_` to understand the pattern). Hence, the command removes the tailing *blank* lines. To delete the *empty* lines in a strict sense—as opposed to blank ones containing only whitespace—change the pattern in that `:vglobal` command as follows. ``` :v/\n*./d ``` **2.** On huge sparse files containing large blocks of consecutive whitespace characters (starting from about hundreds of kilobytes of whitespace) the above commands might have unacceptable performance. If that is the case, the same elegant idea can be used to transform that `:vglobal` commands into much faster (but perhaps less elegantly-looking) `:delete` commands with pattern-defined ranges. For blank lines: ``` :0;/^\%(\_s*\S\)\@!/,$d ``` For empty lines: ``` :0;/^\%(\n*.\)\@!/,$d ``` The essence of both commands is the same; namely, removing the lines belonging to the specified ranges, which are defined according to the following three steps: 1. Move the cursor to the first line of the buffer before interpreting the rest of the range (`0;`—see `:help :;`). The difference between `0` and `1` line numbers is that the former allows a match at the first line, when there is a search pattern used to define the ending line of the range. 2. Search for a line where the pattern describing a non-tailing blank line (`\_s*\S` or `\n*.`) does not match (negation is due to the `\@!` atom—see `:help /\@!`). Set the starting line of the range to that line. 3. Set the ending line of the range to the last line of the buffer (`,$`—see `:help :$`). **3.** To run any of the above commands on saving, trigger it using an autocommand to be fired on the `BufWrite` event (or its synonym, `BufWritePre`).
I found the previous answers using substitute caused trouble when operating on very large files and polluted my registers. Here's a function I came up with which performs better for me, and avoids polluting registers: ``` " Strip trailing empty newlines function TrimTrailingLines() let lastLine = line('$') let lastNonblankLine = prevnonblank(lastLine) if lastLine > 0 && lastNonblankLine != lastLine silent! execute lastNonblankLine + 1 . ',$delete _' endif endfunction autocmd BufWritePre <buffer> call TrimTrailingLines() ```
7,495,932
Sometimes I accidentally leave blank lines at the end of the file I am editing. How can I trim them on saving in Vim? ### Update Thanks guys, all solutions seem to work. Unfortunately, they all reset current cursor position, so I wrote the following function. ``` function TrimEndLines() let save_cursor = getpos(".") silent! %s#\($\n\s*\)\+\%$## call setpos('.', save_cursor) endfunction autocmd BufWritePre *.py call TrimEndLines() ```
2011/09/21
[ "https://Stackoverflow.com/questions/7495932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423585/" ]
You can put this into your vimrc ``` au BufWritePre *.txt $put _ | $;?\(^\s*$\)\@!?+1,$d ``` (replace `*.txt` with whatever globbing pattern you want) Detail: * `BufWritePre` is the event before writing a buffer to a file. * `$put _` appends a blank line at file end (from the always-empty register) * `|` chains Ex commands * `$;?\(^\s*$\)\@!?` goes to end of file (`$`) then (`;`) looks up backwards (`?…?`) for the first line which is not entirely blank (`\(^\s*$\)\@!`), also see `:help /\@!` for negative assertions in vim searches. * `×××+1,$` forms a range from line ×××+1 till the last line * `d` deletes the line range.
I have a separated function called *Preserve* which I can call from other functions, It makes easy to use Preserve to do other stuff: ``` " remove consecutive blank lines " see Preserve function definition " another way to remove blank lines :g/^$/,/./-j " Reference: https://stackoverflow.com/a/7496112/2571881 if !exists('*DelBlankLines') fun! DelBlankLines() range if !&binary && &filetype != 'diff' call Preserve(':%s/\s\+$//e') call Preserve(':%s/^\n\{2,}/\r/ge') call Preserve(':%s/\v($\n\s*)+%$/\r/e') endif endfun endif ``` In my case, I keep at least one blank line, but not more than one, at the end of the file. ``` " Utility function that save last search and cursor position " http://technotales.wordpress.com/2010/03/31/preserve-a-vim-function-that-keeps-your-state/ " video from vimcasts.org: http://vimcasts.org/episodes/tidying-whitespace " using 'execute' command doesn't overwrite the last search pattern, so I " don't need to store and restore it. " preserve function if !exists('*Preserve') function! Preserve(command) try let l:win_view = winsaveview() "silent! keepjumps keeppatterns execute a:command silent! execute 'keeppatterns keepjumps ' . a:command finally call winrestview(l:win_view) endtry endfunction endif ``` Here's why I have a separated Preserve function: ``` command! -nargs=0 Reindent :call Preserve('exec "normal! gg=G"') " join lines keeping cursor position nnoremap J :call Preserve(':join')<CR> nnoremap <Leader>J :call Preserve(':join!')<CR> " Reloads vimrc after saving but keep cursor position if !exists('*ReloadVimrcFunction') function! ReloadVimrcFunction() call Preserve(':source $MYVIMRC') " hi Normal guibg=NONE ctermbg=NONE windo redraw echom "Reloaded init.vim" endfunction endif noremap <silent> <Leader>v :drop $MYVIMRC<cr> command! -nargs=0 ReloadVimrc :call ReloadVimrcFunction() " Strip trailing whitespaces command! Cls :call Preserve(':%s/\v\s+$//e') ``` And if by any chance you want to create an autocommand you must create a group to avoid overloading autocommands: ``` augroup removetrailingspaces au! au! BufwritePre *.md,*.py,*.sh,*.zsh,*.txt :call Preserve(':%s/\v\s+$//e') augroup END ``` This one is to change file headers (if you have any suggestions) feel free to interact: ``` " trying avoid searching history in this function if !exists('*ChangeHeader') fun! ChangeHeader() abort if line('$')>=7 call Preserve(':1,7s/\v(Last (Change|Modified)|date):\s+\zs.*/\=strftime("%b %d, %Y - %H:%M")/ei') endif endfun endif " dos2unix ^M if !exists('*Dos2unixFunction') fun! Dos2unixFunction() abort "call Preserve('%s/ $//ge') call Preserve(":%s/\x0D$//e") set ff=unix set bomb set encoding=utf-8 set fileencoding=utf-8 endfun endif com! Dos2Unix :call Dos2unixFunction() ```
7,495,932
Sometimes I accidentally leave blank lines at the end of the file I am editing. How can I trim them on saving in Vim? ### Update Thanks guys, all solutions seem to work. Unfortunately, they all reset current cursor position, so I wrote the following function. ``` function TrimEndLines() let save_cursor = getpos(".") silent! %s#\($\n\s*\)\+\%$## call setpos('.', save_cursor) endfunction autocmd BufWritePre *.py call TrimEndLines() ```
2011/09/21
[ "https://Stackoverflow.com/questions/7495932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423585/" ]
This substitute command should do it: ``` :%s#\($\n\s*\)\+\%$## ``` Note that this removes all trailing lines that contain only whitespace. To remove only truly "empty" lines, remove the `\s*` from the above command. **EDIT** Explanation: * `\(` ..... Start a match group * `$\n` ... Match a new line (end-of-line character followed by a carriage return). * `\s*` ... Allow any amount of whitespace on this new line * `\)` ..... End the match group * `\+` ..... Allow any number of occurrences of this group (one or more). * `\%$` ... Match the end of the file Thus the regex matches any number of adjacent lines containing only whitespace, terminated only by the end of the file. The substitute command then replaces the match with a null string.
**1.** An elegant solution can be based on the `:vglobal` command (or, which is the same thing, on the `:global` with `!` modifier): ``` :v/\_s*\S/d ``` This command executes `:delete` on every line that does not have non-whitespace characters in it, as well as after it in the remaining text to the end of buffer (see `:help /\s`, `:help /\S`, and `:help /\_` to understand the pattern). Hence, the command removes the tailing *blank* lines. To delete the *empty* lines in a strict sense—as opposed to blank ones containing only whitespace—change the pattern in that `:vglobal` command as follows. ``` :v/\n*./d ``` **2.** On huge sparse files containing large blocks of consecutive whitespace characters (starting from about hundreds of kilobytes of whitespace) the above commands might have unacceptable performance. If that is the case, the same elegant idea can be used to transform that `:vglobal` commands into much faster (but perhaps less elegantly-looking) `:delete` commands with pattern-defined ranges. For blank lines: ``` :0;/^\%(\_s*\S\)\@!/,$d ``` For empty lines: ``` :0;/^\%(\n*.\)\@!/,$d ``` The essence of both commands is the same; namely, removing the lines belonging to the specified ranges, which are defined according to the following three steps: 1. Move the cursor to the first line of the buffer before interpreting the rest of the range (`0;`—see `:help :;`). The difference between `0` and `1` line numbers is that the former allows a match at the first line, when there is a search pattern used to define the ending line of the range. 2. Search for a line where the pattern describing a non-tailing blank line (`\_s*\S` or `\n*.`) does not match (negation is due to the `\@!` atom—see `:help /\@!`). Set the starting line of the range to that line. 3. Set the ending line of the range to the last line of the buffer (`,$`—see `:help :$`). **3.** To run any of the above commands on saving, trigger it using an autocommand to be fired on the `BufWrite` event (or its synonym, `BufWritePre`).
7,495,932
Sometimes I accidentally leave blank lines at the end of the file I am editing. How can I trim them on saving in Vim? ### Update Thanks guys, all solutions seem to work. Unfortunately, they all reset current cursor position, so I wrote the following function. ``` function TrimEndLines() let save_cursor = getpos(".") silent! %s#\($\n\s*\)\+\%$## call setpos('.', save_cursor) endfunction autocmd BufWritePre *.py call TrimEndLines() ```
2011/09/21
[ "https://Stackoverflow.com/questions/7495932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/423585/" ]
This substitute command should do it: ``` :%s#\($\n\s*\)\+\%$## ``` Note that this removes all trailing lines that contain only whitespace. To remove only truly "empty" lines, remove the `\s*` from the above command. **EDIT** Explanation: * `\(` ..... Start a match group * `$\n` ... Match a new line (end-of-line character followed by a carriage return). * `\s*` ... Allow any amount of whitespace on this new line * `\)` ..... End the match group * `\+` ..... Allow any number of occurrences of this group (one or more). * `\%$` ... Match the end of the file Thus the regex matches any number of adjacent lines containing only whitespace, terminated only by the end of the file. The substitute command then replaces the match with a null string.
You can put this into your vimrc ``` au BufWritePre *.txt $put _ | $;?\(^\s*$\)\@!?+1,$d ``` (replace `*.txt` with whatever globbing pattern you want) Detail: * `BufWritePre` is the event before writing a buffer to a file. * `$put _` appends a blank line at file end (from the always-empty register) * `|` chains Ex commands * `$;?\(^\s*$\)\@!?` goes to end of file (`$`) then (`;`) looks up backwards (`?…?`) for the first line which is not entirely blank (`\(^\s*$\)\@!`), also see `:help /\@!` for negative assertions in vim searches. * `×××+1,$` forms a range from line ×××+1 till the last line * `d` deletes the line range.
2,893,751
Here's a problem from Cohn's *Measure Theory*. > > [Cohn, 2.1.3] Let $f$ and $g$ be continuous real-valued functions on $\mathbb{R}$. Show that if $f =g$ for $\lambda$-almost every $x$, then $f = g$ everywhere. > > > Here $\lambda$ denotes Lebesgue measure. Here's what I do. Let $h: \mathbb{R} \to \mathbb{R}$ be a continuous function. Suppose that $h \neq 0$. Then for some $x \in \mathbb{R}$, there is $n \in \mathbb{N}$ such that $|h(x)| > 2/n$. Then by continuity for some $\delta > 0$, we may ensure that whenever $|y - x| < \delta/2$, we have $$ |h(y)| \geq |h(x)| - |h(y) - h(x)| > 2/n - 1/n = 1/n. $$ Hence, $\lambda(\{h \neq 0\}) \geq \lambda(\{|h| > 1/n\}) \geq \delta > 0$. Taking the contrapositive, we just showed if $h$ is a continuous real-valued function on $\mathbb{R}$, then $\lambda\{h \neq 0\} = 0$ implies $h = 0$ (everywhere). The result follows now by setting $h = f - g$, which is continuous. **Question.** Is this basically the simplest way to do it? Other ways?
2018/08/25
[ "https://math.stackexchange.com/questions/2893751", "https://math.stackexchange.com", "https://math.stackexchange.com/users/503984/" ]
I would say that $\{x:h(x)\ne0\}$ is an open set in $\Bbb R$. (Since it is the inverse image of the open set $\Bbb R\setminus\{0\}$ under the continuous function $h$). Each nonempty open set contains a nonempty open interval, which has positive Lebesgue measure. So if $h$ is continuous, and not identically zero, then it cannot be almost everywhere zero (w.r.t. Lebesgue measure).
(For completeness, following Lord Shark the Unknown's advice.) Let $h: \mathbb{R} \to \mathbb{R}$ be a continuous function. Suppose that $h \neq 0$. Thus, the set $\{h \neq 0\}$ is nonempty and open, and hence has positive Lebesgue measure. Taking the contrapositive, if $h$ is a continuous real-valued function on $\mathbb{R}$, then $\lambda\{h \neq 0\} = 0$ implies $h = 0$ (everywhere). Now take $h = f - g$. The result follows.
123,917
I've been trying to train a model that predicts an individual's survival time. My training set is an unbalanced panel; it has multiple observations per individual and thus time varying covariates. Every individual is observed from start to finish so no censoring. As a test, I used a plain random forest regression (not a random survival forest), treating each observation as if it were iid (even if it came from the same individual) with the duration as the target. When testing the predictions on a test set, the results have been surprisingly accurate. Why is this working so well? I thought random forests needed iid observations.
2014/11/13
[ "https://stats.stackexchange.com/questions/123917", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/32018/" ]
Although there is structure to your data, it may be that the variation in baseline risk does not vary substantially enough among your subjects to cause a model without a frailty term to form poor predictions. Of course, it's perfectly possible that a model with a frailty term would perform better than the pooled random forest model. Even if you did run a pooled and hierarchical model and the pooled model did as well or slightly better, you may still want to use the hierarchical model because the variance in baseline risk is very likely NOT zero among your subjects, and the hierarchical model would probably perform better in the long term on data that was in neither your test or training sets. As an aside, consider whether the cross validation score you are using aligns with the goals of your prediction task in the first place before comparing pooled and hierarchical models. If your goal is to make predictions on the same group of individuals as in your test/training data, then simple k fold or loo cross validation on the response is sufficient. But if you want to make predictions about new individuals, you should instead do k fold cross validation that samples at the individual level. In the first case you are scoring your predictions without regard for the structure of the data. In the second case you are estimating your ability to predict risk within individuals that are not in your sample. Lastly, remember always that CV is itself data dependent, and only an estimate of your model's predictive capabilities.
I am just starting to work with Random Forest but I believe it is mainly the bagging that needs to be iid for each tree and the subset of features selection at each node. I am unaware of any formal constraints on the data itself. Why it works so well on your data I can not say until I have investigated your data. But the non-iid'ness of your features will not influence performance too much.
37,252,793
I have the following ARM assembly code: ``` mov r0, SP mov r1, LR bl func ``` Is there a way of calling the function func using C code? something like `func(SP, LR)` Thanks!
2016/05/16
[ "https://Stackoverflow.com/questions/37252793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6340494/" ]
Depends on what exactly you want to do and what compiler you use. With `gcc` something like this could work: ``` extern void func(void*, void*); void foo() { int dummy[4]; func(&dummy, __builtin_return_address(0)); } ``` This might not always give you the exact stack pointer, though. As per [godbolt](https://godbolt.org/g/aFvbrK) it produces the following assembly code: ``` foo(): push {lr} sub sp, sp, #20 mov r1, lr mov r0, sp bl func(void*, void*) add sp, sp, #20 ldr pc, [sp], #4 ```
Use output registers to place `LR` and `SP` in variables: ``` void *lr, *sp; asm ("mov %0, sp" : "=r" (sp)); asm ("mov %0, lr" : "=r" (lr)); func(lr, sp); ```
18,786
> > **मानुष्यं च समासाद्य स्वर्गमोक्षप्रसाधनम्।** > > **नाचरत्यात्मनः श्रेयः स मृतः शोचते चिरम्॥३०॥** > > > The human body is the means for achieving of the heaven and moksa and even after achieving the same, he does not do good to himself. After death he keeps on thinking for a long time. > > > > > > It is difficult for even the gods and the demons to achieve the human body. Therefore after achieving the human body, one should act in a way that he has not to face the agonies of the hell. > > > > > And we all along find several verses through Hinduism saying this- **Human Birth is extremely rare and auspicious. We must not waste it and effect our Moksha practicing Yoga *(Karma, Gyaana, Bhakti, Kriya, Raaja Yog: means of attaining Brahma)*.** If it be argued- **'*God gave those human being punishment of previous Karma*'** , then also God could have given them inferior births such as- fishes, birds, animals, et cetera. Why does God give them Human Birth?
2017/06/09
[ "https://hinduism.stackexchange.com/questions/18786", "https://hinduism.stackexchange.com", "https://hinduism.stackexchange.com/users/-1/" ]
We all live in Mrityu Lok or Karma Lok. It is called karma lok because we do Karma in this world/lok and get karma phal in return. Whatever deeds we do, we will surely get Karma phal of that deed in return. The grief or joy we experience in life is nothing but result of our karma referred as karma phal. If we do good deeds then we will get joy and if we do bad then we will get grief. As per **Bhagwat Geeta** and **Garur Puran**, when human dies then he only carries his karma phal (not worldly things like money, fame etc) with him while traveling to other lok known as Yam lok. There Yamraj judges our all karma and decides whether we will stay in Hell or we will go to heaven. Whether we will go to hell or heaven, The main purpose of visiting those loks are just to get karma phal of those karma which we did when we were alive in karma lok. Even when we visit hell or heaven to get karma phal, our all karma phal can't be given in one lok at a time. Means, we have to take birth again to get all of our karma phal but that birth is not easy to get. We only get birth in karma lok if any of our karma phal is pending, hence we have to take birth to get our pending karma phal. And that pending karma phal can be of any kind of karma whether it was sin karma or saintly karma. **How Lord decide where and how we will be born** Following things are decided for us before giving us birth * whether we will born in rich family or in poor family. * We will born as beautiful/pretty person Or ugly person * We will born as healthy or with diseased (mentally or physically). * how long we will live or what will be our age. * How much joy and how much grief we will get during our life time. * How much struggle we need to do in our life to get success. and so on... All these things are decided by the Lord himself before giving us birth. And these things are decided by our karma phal, those karma phal which we earn in our previous birth. So whether people are **Lunatic**, **Autistic** or **Schizophrenic**... etc. It's not Lords wish to make such kind of people but It's karma phal of those people which they earn in previous birth and because of their karma phal they get diseases and other things, Lord can't do anything in this. Pretty much this is the only reason for getting birth in this lok so that we can get all of our karma phal because as par **Bhagawad Geeta** one can't get moksha, if their karma phal is pending. So to get moksha we have to get birth. But unfortunate thing is that, when we get birth to get our pending karma phal then we also do new karma and hence our new karma phal gets generated and to get karma phal of our new karma (which we do in our current birth) we have to take birth again then in next birth while getting our pending karma phal we again do new karma and to get karma phal of new karma we again take birth and then again and again... This cycle of rebirth continues to flow because our karma continues to flow. As long as we are doing karma in this lok, we will be getting birth again and again and we will never get moksha.
Everything and everyone is Brahman. When you harm others you are harming yourself. There are people in this world who bring great pains to animal and human life, ie they destroy themselves according to karmic laws. just like an alcoholic do not understand at the time that he is destroying his liver, the evil doer does not understand what part of himself he is destroying. But the sinner is still not one with Brahman. His field of experience is what he calls as himself. So when such an individual dies and when his mind is destroyed he comes into contact with reality, which includes the person he wronged or tortured. He comes into contact with the agony he created and that becomes his reality and he is born with this reality. Asking why is there suffering in the world, when humans, animals and even the earth is tortured, ignored and humiliated, is like stabbing yourself in the leg and wondering 'why am I in pain?!' When people do good deeds their soul becomes strong and the grace of God is on them. Painful realities they encounter while they die are not strong enough to change their reality because they gave comfort, trust and justice to souls their reality becomes enriched by their good actions and they receive appropriate life's, bodies and circumstances, when they are reborn. But still everyone who are involved in the circle of Karma are all fools according to the great sages like Vyasa. Because you are still bound by Karma. liberation from the bondage of Karma is what you should seek. Which is easy in Kali Yuga(current yuga is kali. Kali the demonic era, not to be confused with Kahli the goddess). In Kali yuga you don't have to meditate for years or do great yagnas to attain liberation, simply chanting the name of God with submission, trust and honesty will do. If you don't do this you are carrying the burden of karma on your shoulders good or bad and therefore you are not free and hence will be born again and again to pay your karmic debt or receive credit or both, with increased levels of debt and low level of credit or vice versa. God has nothing to do with it. God is Satchitananda. You can't know the wishes of Brahm because you are it and you choose to be ignorant of your reality in the spirit of playing the game of life. Whether you are suffering or having a good time you are always playing. There is no victim in life you are doing everything to yourself. Waking up to this reality is enlightenment.
18,786
> > **मानुष्यं च समासाद्य स्वर्गमोक्षप्रसाधनम्।** > > **नाचरत्यात्मनः श्रेयः स मृतः शोचते चिरम्॥३०॥** > > > The human body is the means for achieving of the heaven and moksa and even after achieving the same, he does not do good to himself. After death he keeps on thinking for a long time. > > > > > > It is difficult for even the gods and the demons to achieve the human body. Therefore after achieving the human body, one should act in a way that he has not to face the agonies of the hell. > > > > > And we all along find several verses through Hinduism saying this- **Human Birth is extremely rare and auspicious. We must not waste it and effect our Moksha practicing Yoga *(Karma, Gyaana, Bhakti, Kriya, Raaja Yog: means of attaining Brahma)*.** If it be argued- **'*God gave those human being punishment of previous Karma*'** , then also God could have given them inferior births such as- fishes, birds, animals, et cetera. Why does God give them Human Birth?
2017/06/09
[ "https://hinduism.stackexchange.com/questions/18786", "https://hinduism.stackexchange.com", "https://hinduism.stackexchange.com/users/-1/" ]
Human birth is result of accumulation in Manas of a Jeeva. After death, the impressions on Manas if are in resonance with human birth, the Jeeva will appear in human womb. From Chapter 1 of Shiv Rahasya, we find. > > 62. Verily from lack of Awareness, there arises Self-forgetfulness. From that springs wrong knowledge. From wrong knowledge comes greed, lust, envy, hatred and other defects of the mind. **Moreover, man reaps the fruits of his own actions. And actions are done according to his knowledge.** Therefore, the performance of actions that spring from wrong knowledge is the greatest defect of all. > 63. It is due to this cause that men are invested with different kinds of physical bodies and minds. For, **one is born with a body and mind that correspond to the inner latent tendencies one has developed in a previous existence. All bodies are born of mind. And the mind is nothing but the light of the Soul tinted by latent tendencies acquired in the past.** Therefore, know that whatsoever corporeal form a Soul assumes in this life or the next, the same will reflect his mental state, even as the light that passes through a coloured gem (assumes that very colour). > > > This has been explained by Swāmi Vivekānanda (The Complete Works of Swami Vivekananda/Volume 2/Jnana-Yoga/The Cosmos: The Microcosm) very well [here](https://en.m.wikisource.org/wiki/The_Complete_Works_of_Swami_Vivekananda/Volume_2/Jnana-Yoga/The_Cosmos:_The_Microcosm) as well. > > ...Again, if in the bioplasmic cell the infinite amount of impressions > from all time has entered, where and how is it? This is a most > impossible position, and until these physiologists can prove how and > where those impressions live in that cell, and what they mean by a > mental impression sleeping in the physical cell, their position cannot > be taken for granted. **So far it is clear then, that this impression is > in the mind, that the mind comes to take its birth and rebirth, > and uses the material which is most proper for it, and that the mind > which has made itself fit for only a particular kind of body will have > to wait until it gets that material.** This we understand. The theory > then comes to this, that there is hereditary transmission so far as > furnishing the material to the soul is concerned. But the soul > migrates and manufactures body after body, and each thought we think, > and each deed we do, is stored in it in fine forms, ready to spring up > again and take a new shape.When I look at you a wave rises in my mind. > It dives down, as it were, and becomes finer and finer, but it does > not die. It is ready to start up again as a wave in the shape of > memory. So all these impressions are in my mind, and when I die the > resultant force of them will be upon me. A ball is here, and each one > of us takes a mallet in his hands and strikes the ball from all sides; > the ball goes from point to point in the room, and when it reaches the > door it flies out. What does it carry out with it? The resultant of > all these blows. That will give it its direction. **So, what directs the > soul when the body dies? The resultant, the sum total of all the works > it has done, of the thoughts it has thought. If the resultant is such > that it has to manufacture a new body for further experience, it will > go to those parents who are ready to supply it with suitable material > for that body. Thus, from body to body it will go, sometimes to a > heaven, and back again to earth, becoming man, or some lower animal. > This way it will go on until it has finished its experience, and > completed the circle.** It then knows its own nature, knows what it is, > and ignorance vanishes, its powers become manifest, it becomes > perfect; no more is there any necessity for the soul to work through > physical bodies, nor is there any necessity for it to work through > finer, or mental bodies. It shines in its own light, and is free, no > more to be born, no more to die... > > > Therefore, Resultant forces of impressions decide next birth. For example, let's say you have gathered - * 10 units of impressions of Dog. * 15 units of impressions of Cockroache. * 50 units of impressions of human. Resultant impressions = max(10 of human, 15 of Cockroaches, 50 of human) = 50 units. Therefore, you will get human birth after death with some hidden qualities of Cockroaches & dog.
Everything and everyone is Brahman. When you harm others you are harming yourself. There are people in this world who bring great pains to animal and human life, ie they destroy themselves according to karmic laws. just like an alcoholic do not understand at the time that he is destroying his liver, the evil doer does not understand what part of himself he is destroying. But the sinner is still not one with Brahman. His field of experience is what he calls as himself. So when such an individual dies and when his mind is destroyed he comes into contact with reality, which includes the person he wronged or tortured. He comes into contact with the agony he created and that becomes his reality and he is born with this reality. Asking why is there suffering in the world, when humans, animals and even the earth is tortured, ignored and humiliated, is like stabbing yourself in the leg and wondering 'why am I in pain?!' When people do good deeds their soul becomes strong and the grace of God is on them. Painful realities they encounter while they die are not strong enough to change their reality because they gave comfort, trust and justice to souls their reality becomes enriched by their good actions and they receive appropriate life's, bodies and circumstances, when they are reborn. But still everyone who are involved in the circle of Karma are all fools according to the great sages like Vyasa. Because you are still bound by Karma. liberation from the bondage of Karma is what you should seek. Which is easy in Kali Yuga(current yuga is kali. Kali the demonic era, not to be confused with Kahli the goddess). In Kali yuga you don't have to meditate for years or do great yagnas to attain liberation, simply chanting the name of God with submission, trust and honesty will do. If you don't do this you are carrying the burden of karma on your shoulders good or bad and therefore you are not free and hence will be born again and again to pay your karmic debt or receive credit or both, with increased levels of debt and low level of credit or vice versa. God has nothing to do with it. God is Satchitananda. You can't know the wishes of Brahm because you are it and you choose to be ignorant of your reality in the spirit of playing the game of life. Whether you are suffering or having a good time you are always playing. There is no victim in life you are doing everything to yourself. Waking up to this reality is enlightenment.
18,786
> > **मानुष्यं च समासाद्य स्वर्गमोक्षप्रसाधनम्।** > > **नाचरत्यात्मनः श्रेयः स मृतः शोचते चिरम्॥३०॥** > > > The human body is the means for achieving of the heaven and moksa and even after achieving the same, he does not do good to himself. After death he keeps on thinking for a long time. > > > > > > It is difficult for even the gods and the demons to achieve the human body. Therefore after achieving the human body, one should act in a way that he has not to face the agonies of the hell. > > > > > And we all along find several verses through Hinduism saying this- **Human Birth is extremely rare and auspicious. We must not waste it and effect our Moksha practicing Yoga *(Karma, Gyaana, Bhakti, Kriya, Raaja Yog: means of attaining Brahma)*.** If it be argued- **'*God gave those human being punishment of previous Karma*'** , then also God could have given them inferior births such as- fishes, birds, animals, et cetera. Why does God give them Human Birth?
2017/06/09
[ "https://hinduism.stackexchange.com/questions/18786", "https://hinduism.stackexchange.com", "https://hinduism.stackexchange.com/users/-1/" ]
Well, we do bad karmas & we face the consequences, we do good karmas & we reap the benefits. So, why are you bringing in God into all this? The diseases from which we suffer in our lifetime are nothing but signs of our bad karmas or crimes done in our previous lives. This has been explicitly stated in many scriptures. Suppose, one does bad karmas in one's lifetime. Then he has two options: either to repent for it by performing the prescribed expiation measures or suffer the torments in the hellish planets. After that (the punishments in hell), depending on the seriousness and nature of crimes, one gets birth in lower yonis like plants, insects, animals etc or gets human birth with bodily deformities (like deaf and dumb, blind etc) and diseases of various sorts. > > 11.52. **Thus in consequence of a remnant of (the guilt of former) crimes, are born idiots, dumb, blind, deaf, and deformed men,** who are > (all) despised by the virtuous > > > 11.53. Penances, therefore, must always be performed for the sake of purification, **because those whose sins have not been expiated, are > born (again) with disgraceful marks.** > > > **Manu Smriti.** > > > Depending on the nature of sins one gets one or the other diseases in their next births. > > **A person, stealing tin, is born suffering from eye diseases**. Fasting > for a day, he should give away one hundred Palas of tin. (6) > > > **A person, pilfering lead, is born as suffering from head-diseases**. > Fasting for a day, he should give away one Dhenu weight of clarified > butter according to the proper regulations. (7) > > > **A person, stealing milk, is born as a diabetic patient.** He should duly > give, unto a Brahmana, milk one Dhenu in weight. (8) > > > **By stealing milk curd a person is born insane**. For purification, curd, > one Dhcnu in weight, should be given by him unto a Vipra. (9) > > > **Satatapa Smriti, Chapter 5.** > > > So, all the diseases we suffer from in our present life are nothing but results of our own bad karmas which we did in our previous lives. And, we should not blame God for that. In several Agama & Tantra texts its clearly stated that a person who has bodily deformity , has one finger more in hand or less, is not fit to be a Guru. Because Guru himself has to be sinless but all these bodily deformities are nothing but pathakas (or sins) that he is carrying forward from his previous births.
Everything and everyone is Brahman. When you harm others you are harming yourself. There are people in this world who bring great pains to animal and human life, ie they destroy themselves according to karmic laws. just like an alcoholic do not understand at the time that he is destroying his liver, the evil doer does not understand what part of himself he is destroying. But the sinner is still not one with Brahman. His field of experience is what he calls as himself. So when such an individual dies and when his mind is destroyed he comes into contact with reality, which includes the person he wronged or tortured. He comes into contact with the agony he created and that becomes his reality and he is born with this reality. Asking why is there suffering in the world, when humans, animals and even the earth is tortured, ignored and humiliated, is like stabbing yourself in the leg and wondering 'why am I in pain?!' When people do good deeds their soul becomes strong and the grace of God is on them. Painful realities they encounter while they die are not strong enough to change their reality because they gave comfort, trust and justice to souls their reality becomes enriched by their good actions and they receive appropriate life's, bodies and circumstances, when they are reborn. But still everyone who are involved in the circle of Karma are all fools according to the great sages like Vyasa. Because you are still bound by Karma. liberation from the bondage of Karma is what you should seek. Which is easy in Kali Yuga(current yuga is kali. Kali the demonic era, not to be confused with Kahli the goddess). In Kali yuga you don't have to meditate for years or do great yagnas to attain liberation, simply chanting the name of God with submission, trust and honesty will do. If you don't do this you are carrying the burden of karma on your shoulders good or bad and therefore you are not free and hence will be born again and again to pay your karmic debt or receive credit or both, with increased levels of debt and low level of credit or vice versa. God has nothing to do with it. God is Satchitananda. You can't know the wishes of Brahm because you are it and you choose to be ignorant of your reality in the spirit of playing the game of life. Whether you are suffering or having a good time you are always playing. There is no victim in life you are doing everything to yourself. Waking up to this reality is enlightenment.
71,996,211
I'm only learning Java and Spring and after several projects/tutorials went well I'm stuck with this error on a new project: > > org.springframework.beans.factory.BeanCreationException: Error > creating bean with name 'entityManagerFactory' defined in class path > resource > [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: > Invocation of init method failed; nested exception is > java.lang.NullPointerException > > > I googled and checked stackoverflow questions, but haven't seen *"nested exception is java.lang.NullPointerException"* in any cases. It's quite a vague error message to me, so I can't understand what's causing the error. Here's my pom.xml file ``` <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.7</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>shoptest</artifactId> <version>0.0.1-SNAPSHOT</version> <name>shoptest</name> <description>Shop Test for my project</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-hateoas</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` **Edit**: Stack trace: ``` org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1154) ~[spring-context-5.3.19.jar:5.3.19] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:908) ~[spring-context-5.3.19.jar:5.3.19] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.19.jar:5.3.19] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.7.jar:2.6.7] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) ~[spring-boot-2.6.7.jar:2.6.7] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) ~[spring-boot-2.6.7.jar:2.6.7] at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-2.6.7.jar:2.6.7] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.7.jar:2.6.7] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.7.jar:2.6.7] at com.example.shoptest.ShoptestApplication.main(ShoptestApplication.java:10) ~[classes/:na] Caused by: java.lang.NullPointerException: null at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processFkSecondPassesInOrder(InFlightMetadataCollectorImpl.java:1672) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final] at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1623) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final] at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:295) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1460) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1494) ~[hibernate-core-5.6.8.Final.jar:5.6.8.Final] at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.3.19.jar:5.3.19] at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.3.19.jar:5.3.19] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-5.3.19.jar:5.3.19] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-5.3.19.jar:5.3.19] at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.19.jar:5.3.19] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.19.jar:5.3.19] ... 16 common frames omitted ```
2022/04/25
[ "https://Stackoverflow.com/questions/71996211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13447185/" ]
So to fetch all the unused docker images without actually pruning them, you could do the following 1. Fetch all the images belonging to the running containers(which are not stopped or exited) 2. Fetch all the images on the machine 3. Then filter the images in step 1 from step 2 Below are the shell commands ``` runningImages=$(docker ps --format {{.Image}}) docker images --format "{{.ID}} {{.Repository}}:{{.Tag}}" | grep -v "$runningImages" ```
you can use this command to show all of images: ``` docker images -a ``` You can find unused images using the command: ``` docker images -f dangling=true ``` and just a list of their IDs: ``` docker images -q -f dangling=true ``` In case you want to delete them: ``` docker rmi $(docker images -q -f dangling=true) ```
3,220,890
`DataServiceRequestException` was unhandled by user code. An error occurred while processing this request. This is in relation to the previous post I added ``` public void AddEmailAddress(EmailAddressEntity emailAddressTobeAdded) { AddObject("EmailAddress", emailAddressTobeAdded); SaveChanges(); } ``` Again the code breaks and gives a new exception this time. Last time it was Storage Client Exception, now it is `DataServiceRequestException`. Code breaks at `SaveChanges`.
2010/07/10
[ "https://Stackoverflow.com/questions/3220890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388592/" ]
I was looking into implementing something like this a few month ago. Since GWT compiles your code to JavaScript there is no way for you to do that on the client side, JavaScript can't access the file system. So you would need to upload the file to the server first and do the conversion on the server side and send the converted file back. I have never heard of JODConverter before, the the library I wanted to use was [Apache POI](http://poi.apache.org/index.html) . Unfortunately I can't tell you anything about it, because I haven't tried it yet.
GWT is mostly a client side toolkit. Are you trying to make a tool that does all the conversion on the client side, with no help from the server? In that case, you should be looking for JavaScript libraries that can read/convert all those formats. If you are planning to have the user upload their files to the server, then you can use whatever technology you want on the server, and just use GWT for the UI.
3,220,890
`DataServiceRequestException` was unhandled by user code. An error occurred while processing this request. This is in relation to the previous post I added ``` public void AddEmailAddress(EmailAddressEntity emailAddressTobeAdded) { AddObject("EmailAddress", emailAddressTobeAdded); SaveChanges(); } ``` Again the code breaks and gives a new exception this time. Last time it was Storage Client Exception, now it is `DataServiceRequestException`. Code breaks at `SaveChanges`.
2010/07/10
[ "https://Stackoverflow.com/questions/3220890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388592/" ]
It sounds like JOD Converter is precisely what you need since you're looking at multi format conversions from Java. You would install OpenOffice on your server and link it up with JOD Converter. When a document is uploaded, your application would call JOD Converter to perform the conversion and stream the converted document back to the caller. Alternatively you can put the file somewhere, and send a link (URL) back to the caller so they can fetch the document. You can also look at [JOD Reports](http://jodreports.sourceforge.net/) or [Docmosis](http://www.docmosis.com) if you need to manipulate the documents.
GWT is mostly a client side toolkit. Are you trying to make a tool that does all the conversion on the client side, with no help from the server? In that case, you should be looking for JavaScript libraries that can read/convert all those formats. If you are planning to have the user upload their files to the server, then you can use whatever technology you want on the server, and just use GWT for the UI.
253,693
Consider the following code: ``` \documentclass{article} \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \[ \frac{278\,922}{74\,088} \] to be reduced to \[ \frac{6641}{1764} \] \end{document} ``` ![output](https://i.stack.imgur.com/wUiA2.jpg) P.S. The numerator and denominator are always both natural numbers in my case.
2015/07/04
[ "https://tex.stackexchange.com/questions/253693", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/15874/" ]
If you are not bound to [`expl3`](https://www.ctan.org/pkg/expl3) (in which case you “just” need to implement the algorithm): ``` \documentclass{scrartcl} \usepackage{xintgcd,xintfrac} \newcommand*\reducedfrac[2] {\begingroup \edef\gcd{\xintGCD{#1}{#2}}% \frac{\xintNum{\xintDiv{#1}{\gcd}}}{\xintNum{\xintDiv{#2}{\gcd}}}% \endgroup} \begin{document} \[ \frac{278922}{74088} = \reducedfrac{278922}{74088} \] \end{document} ```
There's already another LuaTeX answer, but IMO it doesn't handle properly with locality and integer division. So here, and taking advantage of the fact Lua 5.3+ [includes bitwise operators](https://www.lua.org/manual/5.3/manual.html#3.4.2), a different approach using a [binary GCD algorithm](https://xlinux.nist.gov/dads/HTML/binaryGCD.html): ``` \documentclass{standalone} %\usepackage{amsmath} \usepackage{luacode} \begin{luacode*} userdata = userdata or {} --https://xlinux.nist.gov/dads/HTML/binaryGCD.html userdata.gcd = function (u,v) --To handle with negative values local u, v, g = math.abs(u), math.abs(v), 1 --Nice error message assert(v~=0, "Denominator cannot be zero") while u&1==0 and v&1==0 do u=u>>1 v=v>>1 g=g<<1 end while u>0 do if u&1==0 then u=u>>1 elseif v&1==0 then v=v>>1 else local t = math.abs(u-v)>>1 if u<v then v=t else u=t end end end return v*g end userdata.simplified = function(u,v) local gcd = userdata.gcd(u,v) tex.sprint(("\\frac{%d}{%d}") :format(u//gcd, v//gcd)) end \end{luacode*} \newcommand\simplified[2]{\directlua{userdata.simplified(#1,#2)}} \begin{document} $\displaystyle\simplified{278922}{74088}$ \end{document} ``` [![enter image description here](https://i.stack.imgur.com/MuxMU.png)](https://i.stack.imgur.com/MuxMU.png) The binary algorithm is slightly faster, but that's only noticeable when simplified fractions are extensively used in a document.
253,693
Consider the following code: ``` \documentclass{article} \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \[ \frac{278\,922}{74\,088} \] to be reduced to \[ \frac{6641}{1764} \] \end{document} ``` ![output](https://i.stack.imgur.com/wUiA2.jpg) P.S. The numerator and denominator are always both natural numbers in my case.
2015/07/04
[ "https://tex.stackexchange.com/questions/253693", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/15874/" ]
An [`expl3`](https://ctan.org/pkg/expl3) implementation: ``` \nonstopmode \input expl3-generic \relax \ExplSyntaxOn % -*- expl3 -*- \cs_new:Nn \svend_gcd:nn { \int_compare:nNnTF {#2} = { 0 } {#1} { \svend_gcd:ff {#2} { \int_mod:nn {#1} {#2} } } } \cs_generate_variant:Nn \svend_gcd:nn { ff } \int_new:N \l__svend_tmp_int \cs_new:Nn \svend_reduced:nn { \int_set:Nn \l__svend_tmp_int { \svend_gcd:nn {#1} {#2} } { \int_eval:n { #1 / \l__svend_tmp_int } } \over { \int_eval:n { #2 / \l__svend_tmp_int } } } $$ \svend_reduced:nn {278922} {74088} $$ \bye ``` LaTeX version: ``` \documentclass{article} \usepackage{xparse} \ExplSyntaxOn % ... code code code \msg_new:nnn { svend } { malformed-fraction } { The~input~you~have~provided~is~malformed.~ Please~provide~input~in~the~form~of~`p/q'. } \NewDocumentCommand \ReducedFraction { > { \SplitList { / } } m } { \int_compare:nTF { \tl_count:n {#1} = 2 } { \svend_reduced:nn #1 } { \msg_error:nn { svend } { malformed-fraction } } } \ExplSyntaxOff \begin{document} \[ \ReducedFraction{278922/74088} \] \end{document} ``` ### Edit with wrapper ``` \documentclass{article} \usepackage{xparse} \ExplSyntaxOn \cs_new:Nn \svend_gcd:nn { \int_compare:nNnTF {#2} = { 0 } {#1} { \svend_gcd:ff {#2} { \int_mod:nn {#1} {#2} } } } \cs_generate_variant:Nn \svend_gcd:nn { ff } \int_new:N \l__svend_tmp_int \cs_new:Nn \svend_reduced:nn { \int_set:Nn \l__svend_tmp_int { \svend_gcd:nn {#1} {#2} } \frac { \svend_reduced_wrap:n { \int_eval:n { #1 / \l__svend_tmp_int } } } { \svend_reduced_wrap:n { \int_eval:n { #2 / \l__svend_tmp_int } } } } \cs_new:Nn \svend_reduced_use_wrapper:N { \cs_set_eq:NN \svend_reduced_wrap:n #1 } \svend_reduced_use_wrapper:N \use:n %%% Interface \msg_new:nnn { svend } { malformed-fraction } { The~input~you~have~provided~is~malformed.~ Please~provide~input~in~the~form~of~`p/q'. } \NewDocumentCommand \ReducedFractionWrapper { m } { \svend_reduced_use_wrapper:N #1 } \NewDocumentCommand \ReducedFraction { o > { \SplitList { / } } m } { \group_begin: \IfValueT{#1}{\ReducedFractionWrapper{#1}} \int_compare:nTF { \tl_count:n {#2} = 2 } { \svend_reduced:nn #2 } { \msg_error:nn { svend } { malformed-fraction } } \group_end: } \ExplSyntaxOff \usepackage{siunitx} \begin{document} \[ \ReducedFraction[\num]{278922/74088} \] \ReducedFractionWrapper{\num} \[ \ReducedFraction{27892/74088} \] \end{document} ```
There's already another LuaTeX answer, but IMO it doesn't handle properly with locality and integer division. So here, and taking advantage of the fact Lua 5.3+ [includes bitwise operators](https://www.lua.org/manual/5.3/manual.html#3.4.2), a different approach using a [binary GCD algorithm](https://xlinux.nist.gov/dads/HTML/binaryGCD.html): ``` \documentclass{standalone} %\usepackage{amsmath} \usepackage{luacode} \begin{luacode*} userdata = userdata or {} --https://xlinux.nist.gov/dads/HTML/binaryGCD.html userdata.gcd = function (u,v) --To handle with negative values local u, v, g = math.abs(u), math.abs(v), 1 --Nice error message assert(v~=0, "Denominator cannot be zero") while u&1==0 and v&1==0 do u=u>>1 v=v>>1 g=g<<1 end while u>0 do if u&1==0 then u=u>>1 elseif v&1==0 then v=v>>1 else local t = math.abs(u-v)>>1 if u<v then v=t else u=t end end end return v*g end userdata.simplified = function(u,v) local gcd = userdata.gcd(u,v) tex.sprint(("\\frac{%d}{%d}") :format(u//gcd, v//gcd)) end \end{luacode*} \newcommand\simplified[2]{\directlua{userdata.simplified(#1,#2)}} \begin{document} $\displaystyle\simplified{278922}{74088}$ \end{document} ``` [![enter image description here](https://i.stack.imgur.com/MuxMU.png)](https://i.stack.imgur.com/MuxMU.png) The binary algorithm is slightly faster, but that's only noticeable when simplified fractions are extensively used in a document.
253,693
Consider the following code: ``` \documentclass{article} \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \[ \frac{278\,922}{74\,088} \] to be reduced to \[ \frac{6641}{1764} \] \end{document} ``` ![output](https://i.stack.imgur.com/wUiA2.jpg) P.S. The numerator and denominator are always both natural numbers in my case.
2015/07/04
[ "https://tex.stackexchange.com/questions/253693", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/15874/" ]
If you are not bound to [`expl3`](https://www.ctan.org/pkg/expl3) (in which case you “just” need to implement the algorithm): ``` \documentclass{scrartcl} \usepackage{xintgcd,xintfrac} \newcommand*\reducedfrac[2] {\begingroup \edef\gcd{\xintGCD{#1}{#2}}% \frac{\xintNum{\xintDiv{#1}{\gcd}}}{\xintNum{\xintDiv{#2}{\gcd}}}% \endgroup} \begin{document} \[ \frac{278922}{74088} = \reducedfrac{278922}{74088} \] \end{document} ```
Here is a solution using **R** for the computations and the R-package `knitr` to link back to the LaTeX file. ``` \documentclass{article} \begin{document} Using R with the package 'knitr' to reduce the fraction and then get both the reduced fraction but also the components of the fraction. Note: This is a quick demo of linking R and LaTeX using the 'knitr' package. This has been run on Windows 8.1, with MikTeX 2.9, and TeXmaker 4.4.1 as the IDE. The following code is saved as \textbf{knit02.Rnw} (and this is case sensitive). With the package 'knitr' installed in R 3.1.3 you run the command: \emph{knit("knit02.Rnw")}. This will generate the file \textbf{knit02.tex} which you now compile with pdflatex and view as a pdf. <<echo=FALSE>>= library(MASS) ## This function is from http://stackoverflow.com/questions ## /14820029/getting-numerator-and-denominator-of-a-fraction-in-r getfracs <- function(frac) { tmp <- strsplit(attr(frac,"fracs"), "/")[[1]] list(numerator=as.numeric(tmp[1]),denominator=as.numeric(tmp[2])) } dd<-278922 nn<-74088 x<- fractions(dd/nn) fracs<-getfracs(x) denom<-fracs$denominator numer<-fracs$numerator @ \medskip The original fraction is $\displaystyle{\frac{\Sexpr{as.integer(dd)}}{\Sexpr{as.integer(nn)}}}$. \medskip The reduced fraction components are \Sexpr{fracs}. \medskip The reduced denominator is \Sexpr{denom}. \medskip The reduced numerator is \Sexpr{numer}. \medskip And the reduced fraction is $\displaystyle{\frac{\Sexpr{denom}}{\Sexpr{numer}}}$ \end{document} ``` And the output using `pdflatex`: ![enter image description here](https://i.stack.imgur.com/U8GiF.png)
253,693
Consider the following code: ``` \documentclass{article} \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \[ \frac{278\,922}{74\,088} \] to be reduced to \[ \frac{6641}{1764} \] \end{document} ``` ![output](https://i.stack.imgur.com/wUiA2.jpg) P.S. The numerator and denominator are always both natural numbers in my case.
2015/07/04
[ "https://tex.stackexchange.com/questions/253693", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/15874/" ]
Here is a flat LaTeX2e implementation. ``` \documentclass{article} \usepackage{amsmath} \newcount{\numerator} \newcount{\denominator} \newcount{\gcd} % compute \gcd and returns reduced \numerator and \denominator \newcommand{\reduce}[2]% #1=numerator, #2=denominator {\numerator=#1\relax \denominator=#2\relax \loop \ifnum\numerator<\denominator \advance\denominator by -\numerator \gcd=\denominator \else \advance\numerator by -\denominator \gcd=\numerator% swap \fi \ifnum\gcd>1 \repeat \ifnum\gcd=0 \gcd=\denominator\fi \numerator=#1\relax \divide\numerator by \gcd \denominator=#2\relax \divide\denominator by \gcd } \begin{document} For example, I would like the fraction \begin{equation*} \frac{278922}{74088} \end{equation*} to be reduced to\reduce{278922}{74088} \begin{equation*} \frac{\the\numerator}{\the\denominator} = \frac{6641}{1764} \end{equation*} \end{document} ```
There's already another LuaTeX answer, but IMO it doesn't handle properly with locality and integer division. So here, and taking advantage of the fact Lua 5.3+ [includes bitwise operators](https://www.lua.org/manual/5.3/manual.html#3.4.2), a different approach using a [binary GCD algorithm](https://xlinux.nist.gov/dads/HTML/binaryGCD.html): ``` \documentclass{standalone} %\usepackage{amsmath} \usepackage{luacode} \begin{luacode*} userdata = userdata or {} --https://xlinux.nist.gov/dads/HTML/binaryGCD.html userdata.gcd = function (u,v) --To handle with negative values local u, v, g = math.abs(u), math.abs(v), 1 --Nice error message assert(v~=0, "Denominator cannot be zero") while u&1==0 and v&1==0 do u=u>>1 v=v>>1 g=g<<1 end while u>0 do if u&1==0 then u=u>>1 elseif v&1==0 then v=v>>1 else local t = math.abs(u-v)>>1 if u<v then v=t else u=t end end end return v*g end userdata.simplified = function(u,v) local gcd = userdata.gcd(u,v) tex.sprint(("\\frac{%d}{%d}") :format(u//gcd, v//gcd)) end \end{luacode*} \newcommand\simplified[2]{\directlua{userdata.simplified(#1,#2)}} \begin{document} $\displaystyle\simplified{278922}{74088}$ \end{document} ``` [![enter image description here](https://i.stack.imgur.com/MuxMU.png)](https://i.stack.imgur.com/MuxMU.png) The binary algorithm is slightly faster, but that's only noticeable when simplified fractions are extensively used in a document.
253,693
Consider the following code: ``` \documentclass{article} \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \[ \frac{278\,922}{74\,088} \] to be reduced to \[ \frac{6641}{1764} \] \end{document} ``` ![output](https://i.stack.imgur.com/wUiA2.jpg) P.S. The numerator and denominator are always both natural numbers in my case.
2015/07/04
[ "https://tex.stackexchange.com/questions/253693", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/15874/" ]
If you are not bound to [`expl3`](https://www.ctan.org/pkg/expl3) (in which case you “just” need to implement the algorithm): ``` \documentclass{scrartcl} \usepackage{xintgcd,xintfrac} \newcommand*\reducedfrac[2] {\begingroup \edef\gcd{\xintGCD{#1}{#2}}% \frac{\xintNum{\xintDiv{#1}{\gcd}}}{\xintNum{\xintDiv{#2}{\gcd}}}% \endgroup} \begin{document} \[ \frac{278922}{74088} = \reducedfrac{278922}{74088} \] \end{document} ```
If you are an Emacs user, just call Calc embedded (C-x \* e) while the point is on ``` \[ \frac{278922}{74088} \] ``` and the expression is transformed to ``` \[ \frac{6641}{1764} \] ``` `C-x \* e' a second time to come back to latex-mode. Similarly Emacs Calc can perform reduction for rational fractions, for example ``` \[\frac{x^3 - x^2 - x - 2}{2 * x^3 - x^2 - x - 3}\] ``` "C- \* e" to enter the calc embedded mode and the command "a f" product ``` \[\frac{x - 2}{2 x - 3}\] ```
253,693
Consider the following code: ``` \documentclass{article} \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \[ \frac{278\,922}{74\,088} \] to be reduced to \[ \frac{6641}{1764} \] \end{document} ``` ![output](https://i.stack.imgur.com/wUiA2.jpg) P.S. The numerator and denominator are always both natural numbers in my case.
2015/07/04
[ "https://tex.stackexchange.com/questions/253693", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/15874/" ]
Here is a flat LaTeX2e implementation. ``` \documentclass{article} \usepackage{amsmath} \newcount{\numerator} \newcount{\denominator} \newcount{\gcd} % compute \gcd and returns reduced \numerator and \denominator \newcommand{\reduce}[2]% #1=numerator, #2=denominator {\numerator=#1\relax \denominator=#2\relax \loop \ifnum\numerator<\denominator \advance\denominator by -\numerator \gcd=\denominator \else \advance\numerator by -\denominator \gcd=\numerator% swap \fi \ifnum\gcd>1 \repeat \ifnum\gcd=0 \gcd=\denominator\fi \numerator=#1\relax \divide\numerator by \gcd \denominator=#2\relax \divide\denominator by \gcd } \begin{document} For example, I would like the fraction \begin{equation*} \frac{278922}{74088} \end{equation*} to be reduced to\reduce{278922}{74088} \begin{equation*} \frac{\the\numerator}{\the\denominator} = \frac{6641}{1764} \end{equation*} \end{document} ```
If you are an Emacs user, just call Calc embedded (C-x \* e) while the point is on ``` \[ \frac{278922}{74088} \] ``` and the expression is transformed to ``` \[ \frac{6641}{1764} \] ``` `C-x \* e' a second time to come back to latex-mode. Similarly Emacs Calc can perform reduction for rational fractions, for example ``` \[\frac{x^3 - x^2 - x - 2}{2 * x^3 - x^2 - x - 3}\] ``` "C- \* e" to enter the calc embedded mode and the command "a f" product ``` \[\frac{x - 2}{2 x - 3}\] ```
253,693
Consider the following code: ``` \documentclass{article} \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \[ \frac{278\,922}{74\,088} \] to be reduced to \[ \frac{6641}{1764} \] \end{document} ``` ![output](https://i.stack.imgur.com/wUiA2.jpg) P.S. The numerator and denominator are always both natural numbers in my case.
2015/07/04
[ "https://tex.stackexchange.com/questions/253693", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/15874/" ]
An option using Lua+LaTeX. Made small improvement. Made a Lua function to be called as a LaTeX command, with the numerator and denominator passed as arguments, instead of hardcoding the values in as before. The command is `\simplify{a}{b}`: ``` \documentclass{article} \usepackage{luacode} \usepackage{amsmath} %------------------------ \begin{luacode} function simplify(a,b) local function gcd(a,b) if b ~= 0 then return gcd(b, a % b) else return math.abs(a) end end t = gcd(a, b) tex.print("\\frac{"..a/t.."}{"..b/t.."}") end \end{luacode} \newcommand\simplify[2]{\directlua{simplify(#1,#2) }}% %------------------- \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \begin{equation*} \frac{278\,922}{74\,088} \end{equation*} to be reduced to \begin{equation*} \simplify{278922}{74088} \end{equation*} \end{document} ``` **Original answer** ``` \documentclass{article} \usepackage{luacode} \usepackage{amsmath} \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \begin{equation*} \frac{278\,922}{74\,088} \end{equation*} to be reduced to %------------------------------------ \begin{luacode*} function gcd(a,b) if b ~= 0 then return gcd(b, a % b) else return math.abs(a) end end u = 278922 v = 74088 t = gcd(v, u) tex.print("\\begin{equation*}") tex.print(" \\frac{"..u/t.."}{"..v/t.."}") tex.print("\\end{equation*}") \end{luacode*} %------------------------------------ \end{document} ``` `lualatex foo.tex` gives ![Mathematica graphics](https://i.stack.imgur.com/ya9hd.png) references <http://rosettacode.org/wiki/Greatest_common_divisor#Lua> and <http://www.lua.org/manual/5.3/manual.html>
There's already another LuaTeX answer, but IMO it doesn't handle properly with locality and integer division. So here, and taking advantage of the fact Lua 5.3+ [includes bitwise operators](https://www.lua.org/manual/5.3/manual.html#3.4.2), a different approach using a [binary GCD algorithm](https://xlinux.nist.gov/dads/HTML/binaryGCD.html): ``` \documentclass{standalone} %\usepackage{amsmath} \usepackage{luacode} \begin{luacode*} userdata = userdata or {} --https://xlinux.nist.gov/dads/HTML/binaryGCD.html userdata.gcd = function (u,v) --To handle with negative values local u, v, g = math.abs(u), math.abs(v), 1 --Nice error message assert(v~=0, "Denominator cannot be zero") while u&1==0 and v&1==0 do u=u>>1 v=v>>1 g=g<<1 end while u>0 do if u&1==0 then u=u>>1 elseif v&1==0 then v=v>>1 else local t = math.abs(u-v)>>1 if u<v then v=t else u=t end end end return v*g end userdata.simplified = function(u,v) local gcd = userdata.gcd(u,v) tex.sprint(("\\frac{%d}{%d}") :format(u//gcd, v//gcd)) end \end{luacode*} \newcommand\simplified[2]{\directlua{userdata.simplified(#1,#2)}} \begin{document} $\displaystyle\simplified{278922}{74088}$ \end{document} ``` [![enter image description here](https://i.stack.imgur.com/MuxMU.png)](https://i.stack.imgur.com/MuxMU.png) The binary algorithm is slightly faster, but that's only noticeable when simplified fractions are extensively used in a document.
253,693
Consider the following code: ``` \documentclass{article} \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \[ \frac{278\,922}{74\,088} \] to be reduced to \[ \frac{6641}{1764} \] \end{document} ``` ![output](https://i.stack.imgur.com/wUiA2.jpg) P.S. The numerator and denominator are always both natural numbers in my case.
2015/07/04
[ "https://tex.stackexchange.com/questions/253693", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/15874/" ]
Here is a solution using **R** for the computations and the R-package `knitr` to link back to the LaTeX file. ``` \documentclass{article} \begin{document} Using R with the package 'knitr' to reduce the fraction and then get both the reduced fraction but also the components of the fraction. Note: This is a quick demo of linking R and LaTeX using the 'knitr' package. This has been run on Windows 8.1, with MikTeX 2.9, and TeXmaker 4.4.1 as the IDE. The following code is saved as \textbf{knit02.Rnw} (and this is case sensitive). With the package 'knitr' installed in R 3.1.3 you run the command: \emph{knit("knit02.Rnw")}. This will generate the file \textbf{knit02.tex} which you now compile with pdflatex and view as a pdf. <<echo=FALSE>>= library(MASS) ## This function is from http://stackoverflow.com/questions ## /14820029/getting-numerator-and-denominator-of-a-fraction-in-r getfracs <- function(frac) { tmp <- strsplit(attr(frac,"fracs"), "/")[[1]] list(numerator=as.numeric(tmp[1]),denominator=as.numeric(tmp[2])) } dd<-278922 nn<-74088 x<- fractions(dd/nn) fracs<-getfracs(x) denom<-fracs$denominator numer<-fracs$numerator @ \medskip The original fraction is $\displaystyle{\frac{\Sexpr{as.integer(dd)}}{\Sexpr{as.integer(nn)}}}$. \medskip The reduced fraction components are \Sexpr{fracs}. \medskip The reduced denominator is \Sexpr{denom}. \medskip The reduced numerator is \Sexpr{numer}. \medskip And the reduced fraction is $\displaystyle{\frac{\Sexpr{denom}}{\Sexpr{numer}}}$ \end{document} ``` And the output using `pdflatex`: ![enter image description here](https://i.stack.imgur.com/U8GiF.png)
There's already another LuaTeX answer, but IMO it doesn't handle properly with locality and integer division. So here, and taking advantage of the fact Lua 5.3+ [includes bitwise operators](https://www.lua.org/manual/5.3/manual.html#3.4.2), a different approach using a [binary GCD algorithm](https://xlinux.nist.gov/dads/HTML/binaryGCD.html): ``` \documentclass{standalone} %\usepackage{amsmath} \usepackage{luacode} \begin{luacode*} userdata = userdata or {} --https://xlinux.nist.gov/dads/HTML/binaryGCD.html userdata.gcd = function (u,v) --To handle with negative values local u, v, g = math.abs(u), math.abs(v), 1 --Nice error message assert(v~=0, "Denominator cannot be zero") while u&1==0 and v&1==0 do u=u>>1 v=v>>1 g=g<<1 end while u>0 do if u&1==0 then u=u>>1 elseif v&1==0 then v=v>>1 else local t = math.abs(u-v)>>1 if u<v then v=t else u=t end end end return v*g end userdata.simplified = function(u,v) local gcd = userdata.gcd(u,v) tex.sprint(("\\frac{%d}{%d}") :format(u//gcd, v//gcd)) end \end{luacode*} \newcommand\simplified[2]{\directlua{userdata.simplified(#1,#2)}} \begin{document} $\displaystyle\simplified{278922}{74088}$ \end{document} ``` [![enter image description here](https://i.stack.imgur.com/MuxMU.png)](https://i.stack.imgur.com/MuxMU.png) The binary algorithm is slightly faster, but that's only noticeable when simplified fractions are extensively used in a document.
253,693
Consider the following code: ``` \documentclass{article} \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \[ \frac{278\,922}{74\,088} \] to be reduced to \[ \frac{6641}{1764} \] \end{document} ``` ![output](https://i.stack.imgur.com/wUiA2.jpg) P.S. The numerator and denominator are always both natural numbers in my case.
2015/07/04
[ "https://tex.stackexchange.com/questions/253693", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/15874/" ]
An [`expl3`](https://ctan.org/pkg/expl3) implementation: ``` \nonstopmode \input expl3-generic \relax \ExplSyntaxOn % -*- expl3 -*- \cs_new:Nn \svend_gcd:nn { \int_compare:nNnTF {#2} = { 0 } {#1} { \svend_gcd:ff {#2} { \int_mod:nn {#1} {#2} } } } \cs_generate_variant:Nn \svend_gcd:nn { ff } \int_new:N \l__svend_tmp_int \cs_new:Nn \svend_reduced:nn { \int_set:Nn \l__svend_tmp_int { \svend_gcd:nn {#1} {#2} } { \int_eval:n { #1 / \l__svend_tmp_int } } \over { \int_eval:n { #2 / \l__svend_tmp_int } } } $$ \svend_reduced:nn {278922} {74088} $$ \bye ``` LaTeX version: ``` \documentclass{article} \usepackage{xparse} \ExplSyntaxOn % ... code code code \msg_new:nnn { svend } { malformed-fraction } { The~input~you~have~provided~is~malformed.~ Please~provide~input~in~the~form~of~`p/q'. } \NewDocumentCommand \ReducedFraction { > { \SplitList { / } } m } { \int_compare:nTF { \tl_count:n {#1} = 2 } { \svend_reduced:nn #1 } { \msg_error:nn { svend } { malformed-fraction } } } \ExplSyntaxOff \begin{document} \[ \ReducedFraction{278922/74088} \] \end{document} ``` ### Edit with wrapper ``` \documentclass{article} \usepackage{xparse} \ExplSyntaxOn \cs_new:Nn \svend_gcd:nn { \int_compare:nNnTF {#2} = { 0 } {#1} { \svend_gcd:ff {#2} { \int_mod:nn {#1} {#2} } } } \cs_generate_variant:Nn \svend_gcd:nn { ff } \int_new:N \l__svend_tmp_int \cs_new:Nn \svend_reduced:nn { \int_set:Nn \l__svend_tmp_int { \svend_gcd:nn {#1} {#2} } \frac { \svend_reduced_wrap:n { \int_eval:n { #1 / \l__svend_tmp_int } } } { \svend_reduced_wrap:n { \int_eval:n { #2 / \l__svend_tmp_int } } } } \cs_new:Nn \svend_reduced_use_wrapper:N { \cs_set_eq:NN \svend_reduced_wrap:n #1 } \svend_reduced_use_wrapper:N \use:n %%% Interface \msg_new:nnn { svend } { malformed-fraction } { The~input~you~have~provided~is~malformed.~ Please~provide~input~in~the~form~of~`p/q'. } \NewDocumentCommand \ReducedFractionWrapper { m } { \svend_reduced_use_wrapper:N #1 } \NewDocumentCommand \ReducedFraction { o > { \SplitList { / } } m } { \group_begin: \IfValueT{#1}{\ReducedFractionWrapper{#1}} \int_compare:nTF { \tl_count:n {#2} = 2 } { \svend_reduced:nn #2 } { \msg_error:nn { svend } { malformed-fraction } } \group_end: } \ExplSyntaxOff \usepackage{siunitx} \begin{document} \[ \ReducedFraction[\num]{278922/74088} \] \ReducedFractionWrapper{\num} \[ \ReducedFraction{27892/74088} \] \end{document} ```
Here is a solution using **R** for the computations and the R-package `knitr` to link back to the LaTeX file. ``` \documentclass{article} \begin{document} Using R with the package 'knitr' to reduce the fraction and then get both the reduced fraction but also the components of the fraction. Note: This is a quick demo of linking R and LaTeX using the 'knitr' package. This has been run on Windows 8.1, with MikTeX 2.9, and TeXmaker 4.4.1 as the IDE. The following code is saved as \textbf{knit02.Rnw} (and this is case sensitive). With the package 'knitr' installed in R 3.1.3 you run the command: \emph{knit("knit02.Rnw")}. This will generate the file \textbf{knit02.tex} which you now compile with pdflatex and view as a pdf. <<echo=FALSE>>= library(MASS) ## This function is from http://stackoverflow.com/questions ## /14820029/getting-numerator-and-denominator-of-a-fraction-in-r getfracs <- function(frac) { tmp <- strsplit(attr(frac,"fracs"), "/")[[1]] list(numerator=as.numeric(tmp[1]),denominator=as.numeric(tmp[2])) } dd<-278922 nn<-74088 x<- fractions(dd/nn) fracs<-getfracs(x) denom<-fracs$denominator numer<-fracs$numerator @ \medskip The original fraction is $\displaystyle{\frac{\Sexpr{as.integer(dd)}}{\Sexpr{as.integer(nn)}}}$. \medskip The reduced fraction components are \Sexpr{fracs}. \medskip The reduced denominator is \Sexpr{denom}. \medskip The reduced numerator is \Sexpr{numer}. \medskip And the reduced fraction is $\displaystyle{\frac{\Sexpr{denom}}{\Sexpr{numer}}}$ \end{document} ``` And the output using `pdflatex`: ![enter image description here](https://i.stack.imgur.com/U8GiF.png)
253,693
Consider the following code: ``` \documentclass{article} \begin{document} \noindent Can I make \LaTeX{} reduce a fraction automatically?\\[\baselineskip] For example, I would like the fraction \[ \frac{278\,922}{74\,088} \] to be reduced to \[ \frac{6641}{1764} \] \end{document} ``` ![output](https://i.stack.imgur.com/wUiA2.jpg) P.S. The numerator and denominator are always both natural numbers in my case.
2015/07/04
[ "https://tex.stackexchange.com/questions/253693", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/15874/" ]
An [`expl3`](https://ctan.org/pkg/expl3) implementation: ``` \nonstopmode \input expl3-generic \relax \ExplSyntaxOn % -*- expl3 -*- \cs_new:Nn \svend_gcd:nn { \int_compare:nNnTF {#2} = { 0 } {#1} { \svend_gcd:ff {#2} { \int_mod:nn {#1} {#2} } } } \cs_generate_variant:Nn \svend_gcd:nn { ff } \int_new:N \l__svend_tmp_int \cs_new:Nn \svend_reduced:nn { \int_set:Nn \l__svend_tmp_int { \svend_gcd:nn {#1} {#2} } { \int_eval:n { #1 / \l__svend_tmp_int } } \over { \int_eval:n { #2 / \l__svend_tmp_int } } } $$ \svend_reduced:nn {278922} {74088} $$ \bye ``` LaTeX version: ``` \documentclass{article} \usepackage{xparse} \ExplSyntaxOn % ... code code code \msg_new:nnn { svend } { malformed-fraction } { The~input~you~have~provided~is~malformed.~ Please~provide~input~in~the~form~of~`p/q'. } \NewDocumentCommand \ReducedFraction { > { \SplitList { / } } m } { \int_compare:nTF { \tl_count:n {#1} = 2 } { \svend_reduced:nn #1 } { \msg_error:nn { svend } { malformed-fraction } } } \ExplSyntaxOff \begin{document} \[ \ReducedFraction{278922/74088} \] \end{document} ``` ### Edit with wrapper ``` \documentclass{article} \usepackage{xparse} \ExplSyntaxOn \cs_new:Nn \svend_gcd:nn { \int_compare:nNnTF {#2} = { 0 } {#1} { \svend_gcd:ff {#2} { \int_mod:nn {#1} {#2} } } } \cs_generate_variant:Nn \svend_gcd:nn { ff } \int_new:N \l__svend_tmp_int \cs_new:Nn \svend_reduced:nn { \int_set:Nn \l__svend_tmp_int { \svend_gcd:nn {#1} {#2} } \frac { \svend_reduced_wrap:n { \int_eval:n { #1 / \l__svend_tmp_int } } } { \svend_reduced_wrap:n { \int_eval:n { #2 / \l__svend_tmp_int } } } } \cs_new:Nn \svend_reduced_use_wrapper:N { \cs_set_eq:NN \svend_reduced_wrap:n #1 } \svend_reduced_use_wrapper:N \use:n %%% Interface \msg_new:nnn { svend } { malformed-fraction } { The~input~you~have~provided~is~malformed.~ Please~provide~input~in~the~form~of~`p/q'. } \NewDocumentCommand \ReducedFractionWrapper { m } { \svend_reduced_use_wrapper:N #1 } \NewDocumentCommand \ReducedFraction { o > { \SplitList { / } } m } { \group_begin: \IfValueT{#1}{\ReducedFractionWrapper{#1}} \int_compare:nTF { \tl_count:n {#2} = 2 } { \svend_reduced:nn #2 } { \msg_error:nn { svend } { malformed-fraction } } \group_end: } \ExplSyntaxOff \usepackage{siunitx} \begin{document} \[ \ReducedFraction[\num]{278922/74088} \] \ReducedFractionWrapper{\num} \[ \ReducedFraction{27892/74088} \] \end{document} ```
Here is a flat LaTeX2e implementation. ``` \documentclass{article} \usepackage{amsmath} \newcount{\numerator} \newcount{\denominator} \newcount{\gcd} % compute \gcd and returns reduced \numerator and \denominator \newcommand{\reduce}[2]% #1=numerator, #2=denominator {\numerator=#1\relax \denominator=#2\relax \loop \ifnum\numerator<\denominator \advance\denominator by -\numerator \gcd=\denominator \else \advance\numerator by -\denominator \gcd=\numerator% swap \fi \ifnum\gcd>1 \repeat \ifnum\gcd=0 \gcd=\denominator\fi \numerator=#1\relax \divide\numerator by \gcd \denominator=#2\relax \divide\denominator by \gcd } \begin{document} For example, I would like the fraction \begin{equation*} \frac{278922}{74088} \end{equation*} to be reduced to\reduce{278922}{74088} \begin{equation*} \frac{\the\numerator}{\the\denominator} = \frac{6641}{1764} \end{equation*} \end{document} ```
34,520
In den letzten Wochen fällt mir immer öfter auf, dass in Sätzen, in denen früher »man braucht« gesagt wurde, seit neuestem »es braucht« verwendet wird. > > früher: »Wenn das so ist, dann braucht *man* keine Regierung mehr. > > heute: »Wenn das so ist, dann braucht *es* keine Regierung mehr. > > > (Soeben in einer Nachrichtensendung im österreichischen Fernsehen gehört.) Andere Beispiele: > > früher: Braucht *man* die EU noch? > > heute: Braucht *es* die EU noch? > > > früher: Hier, in dieser Region, bräuchte *man* dringend mehr Regen. > > heute: Hier, in dieser Region, bräuchte *es* dringend mehr Regen. > > > Mir ist dieses »es braucht« bisher nur im schweizerischen Deutsch aufgefallen. Anscheinend breitet es sich auch in Österreich aus. Wie ist die Situation in anderen Regionen? Wie ist dieses »es« grammatisch zu bewerten? (Generell in solchen Sätzen, und speziell auch im Vergleich mit dem »man«.)
2017/01/25
[ "https://german.stackexchange.com/questions/34520", "https://german.stackexchange.com", "https://german.stackexchange.com/users/1487/" ]
Im geschriebenen Deutsch würde ich immer eher eine Formulierung im Passiv erwarten, die ohne Pronomen auskommt: > > * Wenn das so ist, *wird* keine Regierung mehr *gebraucht*. (*benötigt*) > * *Wird* die EU noch *gebraucht*? (*benötigt*) > * In dieser Region *wird* dringend mehr Regen *gebraucht*. (*benötigt*) > > > Mit dem etwas „feineren“ *benötigen* statt *brauchen*, welches außerdem nicht die missverständliche Nebenbedeutung ‚verwenden‘ aufweist, ist nur *man*, aber nicht *es* möglich: > > * Wenn das so ist, *benötigt man* keine Regierung mehr. (*benötigt \*es*) > * *Benötigt man* die EU noch? (*benötigt \*es*) > * In dieser Region *benötigt man* dringend mehr Regen. (*benötigt \*es*) > > > Dieses *be*-Verb kann wiederum durch *nötig* oder *notwendig sein* ersetzt werden. > > * Wenn das so ist, *ist* keine Regierung mehr *nötig*. (*notwendig*) > * *Ist* die EU noch *nötig*? (*notwendig*) > * In dieser Region *ist* dringend mehr Regen *nötig*. (*notwendig*) > > > Umgangssprachlich würde ich im Norden des Sprachraums eher *man* erwarten, aber ein passendes (Personal-)Pronomen wirkt noch natürlicher: > > * Wenn das so ist, *braucht ihr* keine Regierung mehr. („*brauchta*“; *brauchst du*, „*brauchste*“) > * *Brauchen wir* die EU noch? („*brauchwa*“) > * Hier, in dieser Region, *brauchen sie* dringend mehr Regen. (*brauchen die*, „*brauchense*“) > > > Noch eine Ebene flapsiger wäre *not tun*: > > * Wenn das so ist, *tut* keine Regierung mehr *not*. > * *Tut* die EU noch *not*? > * Hier, in dieser Region, *tut* dringend mehr Regen *not*. > > > Es gibt allerdings Verben (und Phrasen), bei denen *es* ein noch stärkerer Marker für „Süddeutsch“ ist als bei *brauchen*. Man kann *es* allerdings nicht immer durch *man* ersetzen, sondern muss ggf. ein anderes Verb wählen. > > * Hier, in dieser Region, *hat es* nicht genug Regen. (*?hat man* → *gibt es*, *haben sie*) > > > Subjektives Fazit: *braucht es* oder *braucht’s* fällt im direkten Vergleich als süddeutsch auf und wird kaum aktiv verwendet, wirkt aber im niederdeutschen Sprachraum nicht (mehr) so unnatürlich, dass man drüber stolpern würde.
Als jemand aus dem (Süd-) Westen Bayerns, kurz vor der Sprachgrenze zum Schwäbischen, kommt mir *es braucht* überhaupt nicht seltsam vor. Ich bin allerdings auch noch relativ jung, kann also nicht sagen, inwiefern es sich um eine neuartige Entwicklung handelt. In einem Kommentar hat TvF schön den Unterschied zwischen »es braucht« und »man braucht« herausgearbeitet. Beides lässt sich umkehren, wobei aus »man braucht« ein »niemand braucht« würde, während »es braucht« zu »ist nicht nötig« wird. Das *man* in »man braucht« impliziert also stets, dass es um *Menschen* geht, während *es* auch ein rein abstraktes *benötigen* bedeuten kann. Ich denke, dass es sich bei *es* um einen »grammatikalischen Expletiv« handelt. Ich muss kurz ausschweifen, um zu erklären, was ich damit meine. In beiden folgenden Sätzen haben wir es mit einem vergleichbaren *es* zu tun, das in keiner Weise Urheber der dargestellten Handlungen ist. > > Es wird heute gefeiert. > > > Es regnet heute. > > > Weder ist *es* das abstrakte Wetter, das den Regen bringt, noch tut *es* irgendetwas zur Feier dazu. Die beiden *es* sind also [Expletiva](https://de.wikipedia.org/wiki/Expletivum); sie erfüllen rein grammatisch-syntaktische Funktionen. Sie sind aber unterschiedlich, was man an der Umstellung der Sätze sieht: > > Heute wird gefeiert. > > > Heute regnet **es.** > > > Zieht man das *heute* im subjektlosen Passiv ins Vorfeld, verschwindet das *es.* Seine einzige Aufgabe besteht darin, das Vorfeld in Ermangelung eines Subjekts zu besetzen. Das würde ich »syntaktischen Expletiv« nennen. Im Gegensatz dazu ist das *es* in »Heute regnet es« *nicht* entfallen; es dient in diesem Satz als Subjekt, auch wenn es dort ein reiner Platzhalter ist. Weil es grammatikalisch (und nicht rein syntaktisch) notwendig ist, möchte ich es »grammatikalischen Expletiv« nennen. Das *es* in »es braucht« ist, wie man anhand deiner Beispiele sehen kann, grammatikalisch notwendig; es bleibt auch erhalten, wenn es nicht im Vorfeld steht.
34,520
In den letzten Wochen fällt mir immer öfter auf, dass in Sätzen, in denen früher »man braucht« gesagt wurde, seit neuestem »es braucht« verwendet wird. > > früher: »Wenn das so ist, dann braucht *man* keine Regierung mehr. > > heute: »Wenn das so ist, dann braucht *es* keine Regierung mehr. > > > (Soeben in einer Nachrichtensendung im österreichischen Fernsehen gehört.) Andere Beispiele: > > früher: Braucht *man* die EU noch? > > heute: Braucht *es* die EU noch? > > > früher: Hier, in dieser Region, bräuchte *man* dringend mehr Regen. > > heute: Hier, in dieser Region, bräuchte *es* dringend mehr Regen. > > > Mir ist dieses »es braucht« bisher nur im schweizerischen Deutsch aufgefallen. Anscheinend breitet es sich auch in Österreich aus. Wie ist die Situation in anderen Regionen? Wie ist dieses »es« grammatisch zu bewerten? (Generell in solchen Sätzen, und speziell auch im Vergleich mit dem »man«.)
2017/01/25
[ "https://german.stackexchange.com/questions/34520", "https://german.stackexchange.com", "https://german.stackexchange.com/users/1487/" ]
Im geschriebenen Deutsch würde ich immer eher eine Formulierung im Passiv erwarten, die ohne Pronomen auskommt: > > * Wenn das so ist, *wird* keine Regierung mehr *gebraucht*. (*benötigt*) > * *Wird* die EU noch *gebraucht*? (*benötigt*) > * In dieser Region *wird* dringend mehr Regen *gebraucht*. (*benötigt*) > > > Mit dem etwas „feineren“ *benötigen* statt *brauchen*, welches außerdem nicht die missverständliche Nebenbedeutung ‚verwenden‘ aufweist, ist nur *man*, aber nicht *es* möglich: > > * Wenn das so ist, *benötigt man* keine Regierung mehr. (*benötigt \*es*) > * *Benötigt man* die EU noch? (*benötigt \*es*) > * In dieser Region *benötigt man* dringend mehr Regen. (*benötigt \*es*) > > > Dieses *be*-Verb kann wiederum durch *nötig* oder *notwendig sein* ersetzt werden. > > * Wenn das so ist, *ist* keine Regierung mehr *nötig*. (*notwendig*) > * *Ist* die EU noch *nötig*? (*notwendig*) > * In dieser Region *ist* dringend mehr Regen *nötig*. (*notwendig*) > > > Umgangssprachlich würde ich im Norden des Sprachraums eher *man* erwarten, aber ein passendes (Personal-)Pronomen wirkt noch natürlicher: > > * Wenn das so ist, *braucht ihr* keine Regierung mehr. („*brauchta*“; *brauchst du*, „*brauchste*“) > * *Brauchen wir* die EU noch? („*brauchwa*“) > * Hier, in dieser Region, *brauchen sie* dringend mehr Regen. (*brauchen die*, „*brauchense*“) > > > Noch eine Ebene flapsiger wäre *not tun*: > > * Wenn das so ist, *tut* keine Regierung mehr *not*. > * *Tut* die EU noch *not*? > * Hier, in dieser Region, *tut* dringend mehr Regen *not*. > > > Es gibt allerdings Verben (und Phrasen), bei denen *es* ein noch stärkerer Marker für „Süddeutsch“ ist als bei *brauchen*. Man kann *es* allerdings nicht immer durch *man* ersetzen, sondern muss ggf. ein anderes Verb wählen. > > * Hier, in dieser Region, *hat es* nicht genug Regen. (*?hat man* → *gibt es*, *haben sie*) > > > Subjektives Fazit: *braucht es* oder *braucht’s* fällt im direkten Vergleich als süddeutsch auf und wird kaum aktiv verwendet, wirkt aber im niederdeutschen Sprachraum nicht (mehr) so unnatürlich, dass man drüber stolpern würde.
Komme aus Südbaden, nahe der Grenze zur Schweiz. Für mich ist "es braucht" ganz natürlich. Bin noch jünger, kann daher zur Historie nicht so viel beitragen. Mir schwätzet hier alemannische Dialekt (alemannisch bezeichnet nicht nur den Dialekt in Südbaden, sondern ist auch der Oberbegriff für Schweizerdeutsch, Schwäbisch und die Dialekte in Vorarlberg und Liechtenstein). Typische tägliche Ausdrücke wären: "Bruuchts des?" (Braucht es das? = Ist das nötig?). oder z.B.: "Es braucht Wasser und Salz zum Backen der Wecken." Könnte mir vorstellen, dass sich das über Vorarlberg in den restlichen österreichischen Sprachraum eingeschlichen hat.
34,520
In den letzten Wochen fällt mir immer öfter auf, dass in Sätzen, in denen früher »man braucht« gesagt wurde, seit neuestem »es braucht« verwendet wird. > > früher: »Wenn das so ist, dann braucht *man* keine Regierung mehr. > > heute: »Wenn das so ist, dann braucht *es* keine Regierung mehr. > > > (Soeben in einer Nachrichtensendung im österreichischen Fernsehen gehört.) Andere Beispiele: > > früher: Braucht *man* die EU noch? > > heute: Braucht *es* die EU noch? > > > früher: Hier, in dieser Region, bräuchte *man* dringend mehr Regen. > > heute: Hier, in dieser Region, bräuchte *es* dringend mehr Regen. > > > Mir ist dieses »es braucht« bisher nur im schweizerischen Deutsch aufgefallen. Anscheinend breitet es sich auch in Österreich aus. Wie ist die Situation in anderen Regionen? Wie ist dieses »es« grammatisch zu bewerten? (Generell in solchen Sätzen, und speziell auch im Vergleich mit dem »man«.)
2017/01/25
[ "https://german.stackexchange.com/questions/34520", "https://german.stackexchange.com", "https://german.stackexchange.com/users/1487/" ]
Es scheit so, also ob diese Formulierung im südlichen und südwestlichen Sprachraum schon seit langer Zeit verwendet würde: ``` Der Rhein, ist seitwärts Hinweggegangen. Umsonst nicht gehn Im Trocknen die Ströme. Aber wie? Ein Zeichen braucht es, Nichts anderes, schlecht und recht, damit es Sonn Und Mond trag im Gemüt, untrennbar, ``` (Hölderlin, Der Ister, 1804) Nachdem es hier Leute zu geben scheint, denen Hölderlins Sprache nicht repräsentativ genug ist für die deutsche Sprache, noch ein Schiller-Zitat (der dürfte über mehr Zweifel erhaben sein): > > Es braucht der Waffen nicht! > > > (Wallenstein) Genügt das immer noch nicht, nehmen wir halt den Dichterfürsten: > > Alles was es braucht auf dieser Welt ist ein gescheiter Einfall und ein fester Entschluss. > > > Das ist sicher kein Anglizismus, wie in anderen Antworten vermutet (das Englische hat kein solches Konstrukt), sondern möglicherweise durch französischen Spracheinfluß entstanden ("il faut"). In meiner täglichen Spracherfahrung kommt das durchaus täglich vor. Vollkommen gängig ist "Es braucht" z.B. in Ausdrücken wie > > Es wird noch Jahre brauchen, bis sich die Wirtschaft von der Pandemie erholt hat. > > >
"Es braucht" war vor 20 Jahren in Österreich völlig ungebräuchlich, hat sich seither aber epidemieartig ausgebreitet. Meine Theorie ist, dass MAN im Zuge der Suche nach einer "geschlechtsneutralen" Alternative für das ach so maskuline "man" in den alemannischen Dialektraum geschielt hat, wo "es braucht" in seiner Verwandtschaft mit dem französischen "il faut" durchaus plausibel ist. Also: ein mainstream-gender-affiner Import aus Westgermanistan!
34,520
In den letzten Wochen fällt mir immer öfter auf, dass in Sätzen, in denen früher »man braucht« gesagt wurde, seit neuestem »es braucht« verwendet wird. > > früher: »Wenn das so ist, dann braucht *man* keine Regierung mehr. > > heute: »Wenn das so ist, dann braucht *es* keine Regierung mehr. > > > (Soeben in einer Nachrichtensendung im österreichischen Fernsehen gehört.) Andere Beispiele: > > früher: Braucht *man* die EU noch? > > heute: Braucht *es* die EU noch? > > > früher: Hier, in dieser Region, bräuchte *man* dringend mehr Regen. > > heute: Hier, in dieser Region, bräuchte *es* dringend mehr Regen. > > > Mir ist dieses »es braucht« bisher nur im schweizerischen Deutsch aufgefallen. Anscheinend breitet es sich auch in Österreich aus. Wie ist die Situation in anderen Regionen? Wie ist dieses »es« grammatisch zu bewerten? (Generell in solchen Sätzen, und speziell auch im Vergleich mit dem »man«.)
2017/01/25
[ "https://german.stackexchange.com/questions/34520", "https://german.stackexchange.com", "https://german.stackexchange.com/users/1487/" ]
Im geschriebenen Deutsch würde ich immer eher eine Formulierung im Passiv erwarten, die ohne Pronomen auskommt: > > * Wenn das so ist, *wird* keine Regierung mehr *gebraucht*. (*benötigt*) > * *Wird* die EU noch *gebraucht*? (*benötigt*) > * In dieser Region *wird* dringend mehr Regen *gebraucht*. (*benötigt*) > > > Mit dem etwas „feineren“ *benötigen* statt *brauchen*, welches außerdem nicht die missverständliche Nebenbedeutung ‚verwenden‘ aufweist, ist nur *man*, aber nicht *es* möglich: > > * Wenn das so ist, *benötigt man* keine Regierung mehr. (*benötigt \*es*) > * *Benötigt man* die EU noch? (*benötigt \*es*) > * In dieser Region *benötigt man* dringend mehr Regen. (*benötigt \*es*) > > > Dieses *be*-Verb kann wiederum durch *nötig* oder *notwendig sein* ersetzt werden. > > * Wenn das so ist, *ist* keine Regierung mehr *nötig*. (*notwendig*) > * *Ist* die EU noch *nötig*? (*notwendig*) > * In dieser Region *ist* dringend mehr Regen *nötig*. (*notwendig*) > > > Umgangssprachlich würde ich im Norden des Sprachraums eher *man* erwarten, aber ein passendes (Personal-)Pronomen wirkt noch natürlicher: > > * Wenn das so ist, *braucht ihr* keine Regierung mehr. („*brauchta*“; *brauchst du*, „*brauchste*“) > * *Brauchen wir* die EU noch? („*brauchwa*“) > * Hier, in dieser Region, *brauchen sie* dringend mehr Regen. (*brauchen die*, „*brauchense*“) > > > Noch eine Ebene flapsiger wäre *not tun*: > > * Wenn das so ist, *tut* keine Regierung mehr *not*. > * *Tut* die EU noch *not*? > * Hier, in dieser Region, *tut* dringend mehr Regen *not*. > > > Es gibt allerdings Verben (und Phrasen), bei denen *es* ein noch stärkerer Marker für „Süddeutsch“ ist als bei *brauchen*. Man kann *es* allerdings nicht immer durch *man* ersetzen, sondern muss ggf. ein anderes Verb wählen. > > * Hier, in dieser Region, *hat es* nicht genug Regen. (*?hat man* → *gibt es*, *haben sie*) > > > Subjektives Fazit: *braucht es* oder *braucht’s* fällt im direkten Vergleich als süddeutsch auf und wird kaum aktiv verwendet, wirkt aber im niederdeutschen Sprachraum nicht (mehr) so unnatürlich, dass man drüber stolpern würde.
Ich habe die Hälfte meines Lebens (66) an unterschiedlichen Orten in Deutschland gelebt, Süd wie Nord, auch nahe an der Grenze zur Schweiz und zu Österreich. "Es braucht" ist mir dort bis vor rund 15 bis 20 Jahren nicht begegnet. Auch nicht in den jeweiligen Mundarten. Meine Theorie ist, dass "es braucht" ein Anglizismus ist und aus der wörtlichen Übersetzung von "it needs" herrührt, was im Englischen für "es besteht die Notwendigkeit für ..." oder ähnliche Wendungen gebraucht wird.
34,520
In den letzten Wochen fällt mir immer öfter auf, dass in Sätzen, in denen früher »man braucht« gesagt wurde, seit neuestem »es braucht« verwendet wird. > > früher: »Wenn das so ist, dann braucht *man* keine Regierung mehr. > > heute: »Wenn das so ist, dann braucht *es* keine Regierung mehr. > > > (Soeben in einer Nachrichtensendung im österreichischen Fernsehen gehört.) Andere Beispiele: > > früher: Braucht *man* die EU noch? > > heute: Braucht *es* die EU noch? > > > früher: Hier, in dieser Region, bräuchte *man* dringend mehr Regen. > > heute: Hier, in dieser Region, bräuchte *es* dringend mehr Regen. > > > Mir ist dieses »es braucht« bisher nur im schweizerischen Deutsch aufgefallen. Anscheinend breitet es sich auch in Österreich aus. Wie ist die Situation in anderen Regionen? Wie ist dieses »es« grammatisch zu bewerten? (Generell in solchen Sätzen, und speziell auch im Vergleich mit dem »man«.)
2017/01/25
[ "https://german.stackexchange.com/questions/34520", "https://german.stackexchange.com", "https://german.stackexchange.com/users/1487/" ]
Als jemand aus dem (Süd-) Westen Bayerns, kurz vor der Sprachgrenze zum Schwäbischen, kommt mir *es braucht* überhaupt nicht seltsam vor. Ich bin allerdings auch noch relativ jung, kann also nicht sagen, inwiefern es sich um eine neuartige Entwicklung handelt. In einem Kommentar hat TvF schön den Unterschied zwischen »es braucht« und »man braucht« herausgearbeitet. Beides lässt sich umkehren, wobei aus »man braucht« ein »niemand braucht« würde, während »es braucht« zu »ist nicht nötig« wird. Das *man* in »man braucht« impliziert also stets, dass es um *Menschen* geht, während *es* auch ein rein abstraktes *benötigen* bedeuten kann. Ich denke, dass es sich bei *es* um einen »grammatikalischen Expletiv« handelt. Ich muss kurz ausschweifen, um zu erklären, was ich damit meine. In beiden folgenden Sätzen haben wir es mit einem vergleichbaren *es* zu tun, das in keiner Weise Urheber der dargestellten Handlungen ist. > > Es wird heute gefeiert. > > > Es regnet heute. > > > Weder ist *es* das abstrakte Wetter, das den Regen bringt, noch tut *es* irgendetwas zur Feier dazu. Die beiden *es* sind also [Expletiva](https://de.wikipedia.org/wiki/Expletivum); sie erfüllen rein grammatisch-syntaktische Funktionen. Sie sind aber unterschiedlich, was man an der Umstellung der Sätze sieht: > > Heute wird gefeiert. > > > Heute regnet **es.** > > > Zieht man das *heute* im subjektlosen Passiv ins Vorfeld, verschwindet das *es.* Seine einzige Aufgabe besteht darin, das Vorfeld in Ermangelung eines Subjekts zu besetzen. Das würde ich »syntaktischen Expletiv« nennen. Im Gegensatz dazu ist das *es* in »Heute regnet es« *nicht* entfallen; es dient in diesem Satz als Subjekt, auch wenn es dort ein reiner Platzhalter ist. Weil es grammatikalisch (und nicht rein syntaktisch) notwendig ist, möchte ich es »grammatikalischen Expletiv« nennen. Das *es* in »es braucht« ist, wie man anhand deiner Beispiele sehen kann, grammatikalisch notwendig; es bleibt auch erhalten, wenn es nicht im Vorfeld steht.
Komme aus Südbaden, nahe der Grenze zur Schweiz. Für mich ist "es braucht" ganz natürlich. Bin noch jünger, kann daher zur Historie nicht so viel beitragen. Mir schwätzet hier alemannische Dialekt (alemannisch bezeichnet nicht nur den Dialekt in Südbaden, sondern ist auch der Oberbegriff für Schweizerdeutsch, Schwäbisch und die Dialekte in Vorarlberg und Liechtenstein). Typische tägliche Ausdrücke wären: "Bruuchts des?" (Braucht es das? = Ist das nötig?). oder z.B.: "Es braucht Wasser und Salz zum Backen der Wecken." Könnte mir vorstellen, dass sich das über Vorarlberg in den restlichen österreichischen Sprachraum eingeschlichen hat.
34,520
In den letzten Wochen fällt mir immer öfter auf, dass in Sätzen, in denen früher »man braucht« gesagt wurde, seit neuestem »es braucht« verwendet wird. > > früher: »Wenn das so ist, dann braucht *man* keine Regierung mehr. > > heute: »Wenn das so ist, dann braucht *es* keine Regierung mehr. > > > (Soeben in einer Nachrichtensendung im österreichischen Fernsehen gehört.) Andere Beispiele: > > früher: Braucht *man* die EU noch? > > heute: Braucht *es* die EU noch? > > > früher: Hier, in dieser Region, bräuchte *man* dringend mehr Regen. > > heute: Hier, in dieser Region, bräuchte *es* dringend mehr Regen. > > > Mir ist dieses »es braucht« bisher nur im schweizerischen Deutsch aufgefallen. Anscheinend breitet es sich auch in Österreich aus. Wie ist die Situation in anderen Regionen? Wie ist dieses »es« grammatisch zu bewerten? (Generell in solchen Sätzen, und speziell auch im Vergleich mit dem »man«.)
2017/01/25
[ "https://german.stackexchange.com/questions/34520", "https://german.stackexchange.com", "https://german.stackexchange.com/users/1487/" ]
Im geschriebenen Deutsch würde ich immer eher eine Formulierung im Passiv erwarten, die ohne Pronomen auskommt: > > * Wenn das so ist, *wird* keine Regierung mehr *gebraucht*. (*benötigt*) > * *Wird* die EU noch *gebraucht*? (*benötigt*) > * In dieser Region *wird* dringend mehr Regen *gebraucht*. (*benötigt*) > > > Mit dem etwas „feineren“ *benötigen* statt *brauchen*, welches außerdem nicht die missverständliche Nebenbedeutung ‚verwenden‘ aufweist, ist nur *man*, aber nicht *es* möglich: > > * Wenn das so ist, *benötigt man* keine Regierung mehr. (*benötigt \*es*) > * *Benötigt man* die EU noch? (*benötigt \*es*) > * In dieser Region *benötigt man* dringend mehr Regen. (*benötigt \*es*) > > > Dieses *be*-Verb kann wiederum durch *nötig* oder *notwendig sein* ersetzt werden. > > * Wenn das so ist, *ist* keine Regierung mehr *nötig*. (*notwendig*) > * *Ist* die EU noch *nötig*? (*notwendig*) > * In dieser Region *ist* dringend mehr Regen *nötig*. (*notwendig*) > > > Umgangssprachlich würde ich im Norden des Sprachraums eher *man* erwarten, aber ein passendes (Personal-)Pronomen wirkt noch natürlicher: > > * Wenn das so ist, *braucht ihr* keine Regierung mehr. („*brauchta*“; *brauchst du*, „*brauchste*“) > * *Brauchen wir* die EU noch? („*brauchwa*“) > * Hier, in dieser Region, *brauchen sie* dringend mehr Regen. (*brauchen die*, „*brauchense*“) > > > Noch eine Ebene flapsiger wäre *not tun*: > > * Wenn das so ist, *tut* keine Regierung mehr *not*. > * *Tut* die EU noch *not*? > * Hier, in dieser Region, *tut* dringend mehr Regen *not*. > > > Es gibt allerdings Verben (und Phrasen), bei denen *es* ein noch stärkerer Marker für „Süddeutsch“ ist als bei *brauchen*. Man kann *es* allerdings nicht immer durch *man* ersetzen, sondern muss ggf. ein anderes Verb wählen. > > * Hier, in dieser Region, *hat es* nicht genug Regen. (*?hat man* → *gibt es*, *haben sie*) > > > Subjektives Fazit: *braucht es* oder *braucht’s* fällt im direkten Vergleich als süddeutsch auf und wird kaum aktiv verwendet, wirkt aber im niederdeutschen Sprachraum nicht (mehr) so unnatürlich, dass man drüber stolpern würde.
Es scheit so, also ob diese Formulierung im südlichen und südwestlichen Sprachraum schon seit langer Zeit verwendet würde: ``` Der Rhein, ist seitwärts Hinweggegangen. Umsonst nicht gehn Im Trocknen die Ströme. Aber wie? Ein Zeichen braucht es, Nichts anderes, schlecht und recht, damit es Sonn Und Mond trag im Gemüt, untrennbar, ``` (Hölderlin, Der Ister, 1804) Nachdem es hier Leute zu geben scheint, denen Hölderlins Sprache nicht repräsentativ genug ist für die deutsche Sprache, noch ein Schiller-Zitat (der dürfte über mehr Zweifel erhaben sein): > > Es braucht der Waffen nicht! > > > (Wallenstein) Genügt das immer noch nicht, nehmen wir halt den Dichterfürsten: > > Alles was es braucht auf dieser Welt ist ein gescheiter Einfall und ein fester Entschluss. > > > Das ist sicher kein Anglizismus, wie in anderen Antworten vermutet (das Englische hat kein solches Konstrukt), sondern möglicherweise durch französischen Spracheinfluß entstanden ("il faut"). In meiner täglichen Spracherfahrung kommt das durchaus täglich vor. Vollkommen gängig ist "Es braucht" z.B. in Ausdrücken wie > > Es wird noch Jahre brauchen, bis sich die Wirtschaft von der Pandemie erholt hat. > > >
34,520
In den letzten Wochen fällt mir immer öfter auf, dass in Sätzen, in denen früher »man braucht« gesagt wurde, seit neuestem »es braucht« verwendet wird. > > früher: »Wenn das so ist, dann braucht *man* keine Regierung mehr. > > heute: »Wenn das so ist, dann braucht *es* keine Regierung mehr. > > > (Soeben in einer Nachrichtensendung im österreichischen Fernsehen gehört.) Andere Beispiele: > > früher: Braucht *man* die EU noch? > > heute: Braucht *es* die EU noch? > > > früher: Hier, in dieser Region, bräuchte *man* dringend mehr Regen. > > heute: Hier, in dieser Region, bräuchte *es* dringend mehr Regen. > > > Mir ist dieses »es braucht« bisher nur im schweizerischen Deutsch aufgefallen. Anscheinend breitet es sich auch in Österreich aus. Wie ist die Situation in anderen Regionen? Wie ist dieses »es« grammatisch zu bewerten? (Generell in solchen Sätzen, und speziell auch im Vergleich mit dem »man«.)
2017/01/25
[ "https://german.stackexchange.com/questions/34520", "https://german.stackexchange.com", "https://german.stackexchange.com/users/1487/" ]
Es scheit so, also ob diese Formulierung im südlichen und südwestlichen Sprachraum schon seit langer Zeit verwendet würde: ``` Der Rhein, ist seitwärts Hinweggegangen. Umsonst nicht gehn Im Trocknen die Ströme. Aber wie? Ein Zeichen braucht es, Nichts anderes, schlecht und recht, damit es Sonn Und Mond trag im Gemüt, untrennbar, ``` (Hölderlin, Der Ister, 1804) Nachdem es hier Leute zu geben scheint, denen Hölderlins Sprache nicht repräsentativ genug ist für die deutsche Sprache, noch ein Schiller-Zitat (der dürfte über mehr Zweifel erhaben sein): > > Es braucht der Waffen nicht! > > > (Wallenstein) Genügt das immer noch nicht, nehmen wir halt den Dichterfürsten: > > Alles was es braucht auf dieser Welt ist ein gescheiter Einfall und ein fester Entschluss. > > > Das ist sicher kein Anglizismus, wie in anderen Antworten vermutet (das Englische hat kein solches Konstrukt), sondern möglicherweise durch französischen Spracheinfluß entstanden ("il faut"). In meiner täglichen Spracherfahrung kommt das durchaus täglich vor. Vollkommen gängig ist "Es braucht" z.B. in Ausdrücken wie > > Es wird noch Jahre brauchen, bis sich die Wirtschaft von der Pandemie erholt hat. > > >
Ich habe die Hälfte meines Lebens (66) an unterschiedlichen Orten in Deutschland gelebt, Süd wie Nord, auch nahe an der Grenze zur Schweiz und zu Österreich. "Es braucht" ist mir dort bis vor rund 15 bis 20 Jahren nicht begegnet. Auch nicht in den jeweiligen Mundarten. Meine Theorie ist, dass "es braucht" ein Anglizismus ist und aus der wörtlichen Übersetzung von "it needs" herrührt, was im Englischen für "es besteht die Notwendigkeit für ..." oder ähnliche Wendungen gebraucht wird.
34,520
In den letzten Wochen fällt mir immer öfter auf, dass in Sätzen, in denen früher »man braucht« gesagt wurde, seit neuestem »es braucht« verwendet wird. > > früher: »Wenn das so ist, dann braucht *man* keine Regierung mehr. > > heute: »Wenn das so ist, dann braucht *es* keine Regierung mehr. > > > (Soeben in einer Nachrichtensendung im österreichischen Fernsehen gehört.) Andere Beispiele: > > früher: Braucht *man* die EU noch? > > heute: Braucht *es* die EU noch? > > > früher: Hier, in dieser Region, bräuchte *man* dringend mehr Regen. > > heute: Hier, in dieser Region, bräuchte *es* dringend mehr Regen. > > > Mir ist dieses »es braucht« bisher nur im schweizerischen Deutsch aufgefallen. Anscheinend breitet es sich auch in Österreich aus. Wie ist die Situation in anderen Regionen? Wie ist dieses »es« grammatisch zu bewerten? (Generell in solchen Sätzen, und speziell auch im Vergleich mit dem »man«.)
2017/01/25
[ "https://german.stackexchange.com/questions/34520", "https://german.stackexchange.com", "https://german.stackexchange.com/users/1487/" ]
Komme aus Südbaden, nahe der Grenze zur Schweiz. Für mich ist "es braucht" ganz natürlich. Bin noch jünger, kann daher zur Historie nicht so viel beitragen. Mir schwätzet hier alemannische Dialekt (alemannisch bezeichnet nicht nur den Dialekt in Südbaden, sondern ist auch der Oberbegriff für Schweizerdeutsch, Schwäbisch und die Dialekte in Vorarlberg und Liechtenstein). Typische tägliche Ausdrücke wären: "Bruuchts des?" (Braucht es das? = Ist das nötig?). oder z.B.: "Es braucht Wasser und Salz zum Backen der Wecken." Könnte mir vorstellen, dass sich das über Vorarlberg in den restlichen österreichischen Sprachraum eingeschlichen hat.
"Es braucht" war vor 20 Jahren in Österreich völlig ungebräuchlich, hat sich seither aber epidemieartig ausgebreitet. Meine Theorie ist, dass MAN im Zuge der Suche nach einer "geschlechtsneutralen" Alternative für das ach so maskuline "man" in den alemannischen Dialektraum geschielt hat, wo "es braucht" in seiner Verwandtschaft mit dem französischen "il faut" durchaus plausibel ist. Also: ein mainstream-gender-affiner Import aus Westgermanistan!
34,520
In den letzten Wochen fällt mir immer öfter auf, dass in Sätzen, in denen früher »man braucht« gesagt wurde, seit neuestem »es braucht« verwendet wird. > > früher: »Wenn das so ist, dann braucht *man* keine Regierung mehr. > > heute: »Wenn das so ist, dann braucht *es* keine Regierung mehr. > > > (Soeben in einer Nachrichtensendung im österreichischen Fernsehen gehört.) Andere Beispiele: > > früher: Braucht *man* die EU noch? > > heute: Braucht *es* die EU noch? > > > früher: Hier, in dieser Region, bräuchte *man* dringend mehr Regen. > > heute: Hier, in dieser Region, bräuchte *es* dringend mehr Regen. > > > Mir ist dieses »es braucht« bisher nur im schweizerischen Deutsch aufgefallen. Anscheinend breitet es sich auch in Österreich aus. Wie ist die Situation in anderen Regionen? Wie ist dieses »es« grammatisch zu bewerten? (Generell in solchen Sätzen, und speziell auch im Vergleich mit dem »man«.)
2017/01/25
[ "https://german.stackexchange.com/questions/34520", "https://german.stackexchange.com", "https://german.stackexchange.com/users/1487/" ]
"Es braucht" war vor 20 Jahren in Österreich völlig ungebräuchlich, hat sich seither aber epidemieartig ausgebreitet. Meine Theorie ist, dass MAN im Zuge der Suche nach einer "geschlechtsneutralen" Alternative für das ach so maskuline "man" in den alemannischen Dialektraum geschielt hat, wo "es braucht" in seiner Verwandtschaft mit dem französischen "il faut" durchaus plausibel ist. Also: ein mainstream-gender-affiner Import aus Westgermanistan!
Ich habe die Hälfte meines Lebens (66) an unterschiedlichen Orten in Deutschland gelebt, Süd wie Nord, auch nahe an der Grenze zur Schweiz und zu Österreich. "Es braucht" ist mir dort bis vor rund 15 bis 20 Jahren nicht begegnet. Auch nicht in den jeweiligen Mundarten. Meine Theorie ist, dass "es braucht" ein Anglizismus ist und aus der wörtlichen Übersetzung von "it needs" herrührt, was im Englischen für "es besteht die Notwendigkeit für ..." oder ähnliche Wendungen gebraucht wird.
34,520
In den letzten Wochen fällt mir immer öfter auf, dass in Sätzen, in denen früher »man braucht« gesagt wurde, seit neuestem »es braucht« verwendet wird. > > früher: »Wenn das so ist, dann braucht *man* keine Regierung mehr. > > heute: »Wenn das so ist, dann braucht *es* keine Regierung mehr. > > > (Soeben in einer Nachrichtensendung im österreichischen Fernsehen gehört.) Andere Beispiele: > > früher: Braucht *man* die EU noch? > > heute: Braucht *es* die EU noch? > > > früher: Hier, in dieser Region, bräuchte *man* dringend mehr Regen. > > heute: Hier, in dieser Region, bräuchte *es* dringend mehr Regen. > > > Mir ist dieses »es braucht« bisher nur im schweizerischen Deutsch aufgefallen. Anscheinend breitet es sich auch in Österreich aus. Wie ist die Situation in anderen Regionen? Wie ist dieses »es« grammatisch zu bewerten? (Generell in solchen Sätzen, und speziell auch im Vergleich mit dem »man«.)
2017/01/25
[ "https://german.stackexchange.com/questions/34520", "https://german.stackexchange.com", "https://german.stackexchange.com/users/1487/" ]
Als jemand aus dem (Süd-) Westen Bayerns, kurz vor der Sprachgrenze zum Schwäbischen, kommt mir *es braucht* überhaupt nicht seltsam vor. Ich bin allerdings auch noch relativ jung, kann also nicht sagen, inwiefern es sich um eine neuartige Entwicklung handelt. In einem Kommentar hat TvF schön den Unterschied zwischen »es braucht« und »man braucht« herausgearbeitet. Beides lässt sich umkehren, wobei aus »man braucht« ein »niemand braucht« würde, während »es braucht« zu »ist nicht nötig« wird. Das *man* in »man braucht« impliziert also stets, dass es um *Menschen* geht, während *es* auch ein rein abstraktes *benötigen* bedeuten kann. Ich denke, dass es sich bei *es* um einen »grammatikalischen Expletiv« handelt. Ich muss kurz ausschweifen, um zu erklären, was ich damit meine. In beiden folgenden Sätzen haben wir es mit einem vergleichbaren *es* zu tun, das in keiner Weise Urheber der dargestellten Handlungen ist. > > Es wird heute gefeiert. > > > Es regnet heute. > > > Weder ist *es* das abstrakte Wetter, das den Regen bringt, noch tut *es* irgendetwas zur Feier dazu. Die beiden *es* sind also [Expletiva](https://de.wikipedia.org/wiki/Expletivum); sie erfüllen rein grammatisch-syntaktische Funktionen. Sie sind aber unterschiedlich, was man an der Umstellung der Sätze sieht: > > Heute wird gefeiert. > > > Heute regnet **es.** > > > Zieht man das *heute* im subjektlosen Passiv ins Vorfeld, verschwindet das *es.* Seine einzige Aufgabe besteht darin, das Vorfeld in Ermangelung eines Subjekts zu besetzen. Das würde ich »syntaktischen Expletiv« nennen. Im Gegensatz dazu ist das *es* in »Heute regnet es« *nicht* entfallen; es dient in diesem Satz als Subjekt, auch wenn es dort ein reiner Platzhalter ist. Weil es grammatikalisch (und nicht rein syntaktisch) notwendig ist, möchte ich es »grammatikalischen Expletiv« nennen. Das *es* in »es braucht« ist, wie man anhand deiner Beispiele sehen kann, grammatikalisch notwendig; es bleibt auch erhalten, wenn es nicht im Vorfeld steht.
Ich habe die Hälfte meines Lebens (66) an unterschiedlichen Orten in Deutschland gelebt, Süd wie Nord, auch nahe an der Grenze zur Schweiz und zu Österreich. "Es braucht" ist mir dort bis vor rund 15 bis 20 Jahren nicht begegnet. Auch nicht in den jeweiligen Mundarten. Meine Theorie ist, dass "es braucht" ein Anglizismus ist und aus der wörtlichen Übersetzung von "it needs" herrührt, was im Englischen für "es besteht die Notwendigkeit für ..." oder ähnliche Wendungen gebraucht wird.
55,275,032
I am new in PL/SQL for this reason sorry for easy question.I hope you will help me. My goal is add values to table with for loop.If you have a question please replay I will answer as soon as posible. This is my code which do not work. ``` declare cursor c_exam_info is select result1 from exam_info; begin for i IN c_exam_info loop if result1>60 then insert into exam_info(result1) values('pass'); else insert into exam_info(result1) values('fail'); end if; end loop; end; ``` [this is my table](https://i.stack.imgur.com/9K1Vg.png)
2019/03/21
[ "https://Stackoverflow.com/questions/55275032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11075976/" ]
I can't view images. Anyway: `INSERT` seems to be inappropriate - wouldn't `UPDATE` be a better choice? Something like this: ``` begin for i IN (select id, result1 from exam_info) loop update exam_info set result_type = case when c_exam_info.result1 > 60 then 'pass' else 'fail' end where id = c_exam_info.id; end loop; end; ``` Though, the same can be done in a SQL layer, you don't need PL/SQL (unless it is a homework so you're practicing PL/SQL). ``` update exam_info set result_type = case when c_exam_info.result1 > 60 then 'pass' else 'fail' end; ``` It doesn't make much sense updating (or even inserting) the same column with a string ('fail' or 'pass') if that column (`result1`) is a number (e.g. 60). Also, what kind of a table is it - having only one column; what good would such an `INSERT` do (the one you wrote in your code)?
Given that the `result1` column appears to be completely computed data, I might even recommend here that you just use a view: ``` CREATE VIEW your_view AS ( SELECT t.*, CASE WHEN t.result1 > 60 THEN 'pass' ELSE 'fail' END AS result1 FROM exam_info t ) ``` Then, select from this view whenever you want to use the computed column. Computed/derived data should generally not be stored in your SQL tables, and also you should avoid using cursors, as database operations are already set based.
38,680
I'm trying to find an efficient way to compute maximum of a signal using its DFT. More formally: $$\max\left\{ \mathcal F^{-1}\left(X\_k\right)\right\}, X\_k\text{ is the DFT of the signal and } \mathcal F^{-1} \text{ is the IDFT}$$ The original signal $x(n)$ is real, and it has some noise when sometimes there are wide peaks. I'm looking for a solution that is quicker than the actual IFFT since the signal is very long (but we have its DFT).
2017/03/27
[ "https://dsp.stackexchange.com/questions/38680", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/25521/" ]
There is no way to compute the (exact) maximum of the time domain signal directly from its DFT (without doing an IDFT first). Without any further knowledge, the best you can do is $$|x[n]|=\left|\frac{1}{N}\sum\_{k=0}^{N-1}X[k]e^{j2\pi nk/N}\right|\le\frac{1}{N}\sum\_{k=0}^{N-1}|X[k]| $$ which gives you an upper bound. However, this upper bound is usually not very tight, especially for large values of the DFT length $N$.
Generally: There can be no shortcut here – every single element of the (inverse or forward, doesn't matter) DFT needs every element of the input. So, the FFT is already pretty much as fast as you can go. However, you say: > > The original signal $x(n)$ is real, and it has some noise when sometimes there are wide peaks. > > > Aha! That means that your $X$ is (hermitian) symmetric. Which means you might be able to pick an FFT algorithm that benefits from that knowledge and can omit quite a few calculation – but I don't think that'll change the general $\mathcal O(N \log N)$ complexity of the IFFT, nor the $\mathcal O(N)$ of finding the maximum.
38,680
I'm trying to find an efficient way to compute maximum of a signal using its DFT. More formally: $$\max\left\{ \mathcal F^{-1}\left(X\_k\right)\right\}, X\_k\text{ is the DFT of the signal and } \mathcal F^{-1} \text{ is the IDFT}$$ The original signal $x(n)$ is real, and it has some noise when sometimes there are wide peaks. I'm looking for a solution that is quicker than the actual IFFT since the signal is very long (but we have its DFT).
2017/03/27
[ "https://dsp.stackexchange.com/questions/38680", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/25521/" ]
This sounds like a good candidate for the Sparse Fast Fourier Transform (sFFT). Have a look at H. Hassanieh, P. Indyk, D. Katabi, and E. Price, **[sFFT: Sparse Fast Fourier Transform](http://groups.csail.mit.edu/netmit/sFFT/)**, 2012. I don't know details of the algorithm. You have the domains swapped, which should be fine as the discrete Fourier transform (DFT) and its inverse (IDFT) are nearly identical. [sFFT has been discussed](https://dsp.stackexchange.com/questions/2317/what-is-the-sparse-fourier-transform) also here on dsp.stackexchange.com.
There is no way to compute the (exact) maximum of the time domain signal directly from its DFT (without doing an IDFT first). Without any further knowledge, the best you can do is $$|x[n]|=\left|\frac{1}{N}\sum\_{k=0}^{N-1}X[k]e^{j2\pi nk/N}\right|\le\frac{1}{N}\sum\_{k=0}^{N-1}|X[k]| $$ which gives you an upper bound. However, this upper bound is usually not very tight, especially for large values of the DFT length $N$.
38,680
I'm trying to find an efficient way to compute maximum of a signal using its DFT. More formally: $$\max\left\{ \mathcal F^{-1}\left(X\_k\right)\right\}, X\_k\text{ is the DFT of the signal and } \mathcal F^{-1} \text{ is the IDFT}$$ The original signal $x(n)$ is real, and it has some noise when sometimes there are wide peaks. I'm looking for a solution that is quicker than the actual IFFT since the signal is very long (but we have its DFT).
2017/03/27
[ "https://dsp.stackexchange.com/questions/38680", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/25521/" ]
This sounds like a good candidate for the Sparse Fast Fourier Transform (sFFT). Have a look at H. Hassanieh, P. Indyk, D. Katabi, and E. Price, **[sFFT: Sparse Fast Fourier Transform](http://groups.csail.mit.edu/netmit/sFFT/)**, 2012. I don't know details of the algorithm. You have the domains swapped, which should be fine as the discrete Fourier transform (DFT) and its inverse (IDFT) are nearly identical. [sFFT has been discussed](https://dsp.stackexchange.com/questions/2317/what-is-the-sparse-fourier-transform) also here on dsp.stackexchange.com.
Generally: There can be no shortcut here – every single element of the (inverse or forward, doesn't matter) DFT needs every element of the input. So, the FFT is already pretty much as fast as you can go. However, you say: > > The original signal $x(n)$ is real, and it has some noise when sometimes there are wide peaks. > > > Aha! That means that your $X$ is (hermitian) symmetric. Which means you might be able to pick an FFT algorithm that benefits from that knowledge and can omit quite a few calculation – but I don't think that'll change the general $\mathcal O(N \log N)$ complexity of the IFFT, nor the $\mathcal O(N)$ of finding the maximum.
37,441,689
I am working on a simple app for Android. I am having some trouble using the Firebase database since it uses JSON objects and I am used to relational databases. My data will consists of two users that share a value. In relational databases this would be represented in a table like this: ``` **uname1** **uname2** shared_value ``` In which the usernames are the keys. If I wanted the all the values user Bob shares with other users, I could do a simple union statement that would return the rows where: ``` uname1 == Bob or unname == Bob ``` However, in JSON databases, there seems to be a tree-like hierarchy in the data, which is complicated since I would not be able to search for users at the top level. I am looking for help in how to do this or how to structure my database for best efficiency if my most common search will be one similar to the one above. In case this is not enough information, I will elaborate: My database would be structured like this: ``` { 'username': 'Bob' { 'username2': 'Alice' { 'shared_value' = 2 } } 'username': 'Cece' { 'username2': 'Bob' { 'shared_value' = 4 } } ``` As you can see from the example, Bob is included in two relationships, but looking into Bobs node doesn't show that information. (The relationship is commutative, so who is "first" cannot be predicted). The most intuitive way to fix this would be duplicate all data. For example, when we add Bob->Alice->2, also add Alice->Bob->2. In my experience with relational databases, duplication could be a big problem, which is why I haven't done this already. Also, duplication seems like an inefficient fix.
2016/05/25
[ "https://Stackoverflow.com/questions/37441689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3973615/" ]
Is there a reason why you don't invert this? How about a collection like: ``` { "_id": 2, "usernames":[ "Bob", "Alice"]} { "_id": 4, "usernames":[ "Bob", "Cece"]} ``` If you need all the values for "Bob", then index on "usernames". EDIT: If you need the two usernames to be a unique key, then do something like this: ``` { "_id": {"uname1":"Bob", "uname2":"Alice"}, "value": 2 } ``` But this would still permit the creation of: ``` { "_id": {"uname1":"Alice", "uname2":"Bob"}, "value": 78 } ``` (This issue is also present in your as-is relational model, btw. How do you handle it there?) In general, I think implementing an array by creating multiple columns with names like `"attr1"`, `"attr2"`, `"attr3"`, etc. and then having to search them all for a possible value is an artifact of relational table modeling, which does not support array values. If you are converting to a document-oriented storage, these really should be an embedded list of values, and you should use the document paradigm and model them as such, instead of just reimplementing your table rows as documents.
To create a tree-like structure, the best way is to create an "ancestors" array that stores all the ancestors of a particular entry. That way you can query for either ancestors or descendants and all documents that are related to a particular value in the tree. Using your example, you would be able to search for all descendants of Bob's, or any of his ancestors (and related documents). The answer above suggest: ``` { "_id": {"uname1":"Bob", "uname2":"Alice"}, "value": 2 } ``` That is correct. But you don't get to see the relationship between Bob and Cece with this design. My suggestion, which is from Mongo, is to store ancestor keys in an ancestor array. ``` { "_id": {"uname1":"Bob", "uname2":"Alice"}, "value": 2 , "ancestors": [{uname: "Cece"}]} ``` With this design you still get duplicates, which is something that you do not want. I would design it like this: ``` {"username": "Bob", "ancestors": [{"username": "Cece", "shared_value": 4}]} {"username": "Alice", "ancestors": [{"username": "Bob", "shared_value": 2}, {"username": "Cece"}]} ```
37,441,689
I am working on a simple app for Android. I am having some trouble using the Firebase database since it uses JSON objects and I am used to relational databases. My data will consists of two users that share a value. In relational databases this would be represented in a table like this: ``` **uname1** **uname2** shared_value ``` In which the usernames are the keys. If I wanted the all the values user Bob shares with other users, I could do a simple union statement that would return the rows where: ``` uname1 == Bob or unname == Bob ``` However, in JSON databases, there seems to be a tree-like hierarchy in the data, which is complicated since I would not be able to search for users at the top level. I am looking for help in how to do this or how to structure my database for best efficiency if my most common search will be one similar to the one above. In case this is not enough information, I will elaborate: My database would be structured like this: ``` { 'username': 'Bob' { 'username2': 'Alice' { 'shared_value' = 2 } } 'username': 'Cece' { 'username2': 'Bob' { 'shared_value' = 4 } } ``` As you can see from the example, Bob is included in two relationships, but looking into Bobs node doesn't show that information. (The relationship is commutative, so who is "first" cannot be predicted). The most intuitive way to fix this would be duplicate all data. For example, when we add Bob->Alice->2, also add Alice->Bob->2. In my experience with relational databases, duplication could be a big problem, which is why I haven't done this already. Also, duplication seems like an inefficient fix.
2016/05/25
[ "https://Stackoverflow.com/questions/37441689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3973615/" ]
Is there a reason why you don't invert this? How about a collection like: ``` { "_id": 2, "usernames":[ "Bob", "Alice"]} { "_id": 4, "usernames":[ "Bob", "Cece"]} ``` If you need all the values for "Bob", then index on "usernames". EDIT: If you need the two usernames to be a unique key, then do something like this: ``` { "_id": {"uname1":"Bob", "uname2":"Alice"}, "value": 2 } ``` But this would still permit the creation of: ``` { "_id": {"uname1":"Alice", "uname2":"Bob"}, "value": 78 } ``` (This issue is also present in your as-is relational model, btw. How do you handle it there?) In general, I think implementing an array by creating multiple columns with names like `"attr1"`, `"attr2"`, `"attr3"`, etc. and then having to search them all for a possible value is an artifact of relational table modeling, which does not support array values. If you are converting to a document-oriented storage, these really should be an embedded list of values, and you should use the document paradigm and model them as such, instead of just reimplementing your table rows as documents.
You can still have old structure: ``` [ { username: 'Bob', username2: 'Alice', value: 2 }, { username: 'Cece', username2: 'Bob', value: 4 }, ] ``` You may want to create indexes on 'username' and 'username2' for performance. And then just do the same union.
37,441,689
I am working on a simple app for Android. I am having some trouble using the Firebase database since it uses JSON objects and I am used to relational databases. My data will consists of two users that share a value. In relational databases this would be represented in a table like this: ``` **uname1** **uname2** shared_value ``` In which the usernames are the keys. If I wanted the all the values user Bob shares with other users, I could do a simple union statement that would return the rows where: ``` uname1 == Bob or unname == Bob ``` However, in JSON databases, there seems to be a tree-like hierarchy in the data, which is complicated since I would not be able to search for users at the top level. I am looking for help in how to do this or how to structure my database for best efficiency if my most common search will be one similar to the one above. In case this is not enough information, I will elaborate: My database would be structured like this: ``` { 'username': 'Bob' { 'username2': 'Alice' { 'shared_value' = 2 } } 'username': 'Cece' { 'username2': 'Bob' { 'shared_value' = 4 } } ``` As you can see from the example, Bob is included in two relationships, but looking into Bobs node doesn't show that information. (The relationship is commutative, so who is "first" cannot be predicted). The most intuitive way to fix this would be duplicate all data. For example, when we add Bob->Alice->2, also add Alice->Bob->2. In my experience with relational databases, duplication could be a big problem, which is why I haven't done this already. Also, duplication seems like an inefficient fix.
2016/05/25
[ "https://Stackoverflow.com/questions/37441689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3973615/" ]
You can still have old structure: ``` [ { username: 'Bob', username2: 'Alice', value: 2 }, { username: 'Cece', username2: 'Bob', value: 4 }, ] ``` You may want to create indexes on 'username' and 'username2' for performance. And then just do the same union.
To create a tree-like structure, the best way is to create an "ancestors" array that stores all the ancestors of a particular entry. That way you can query for either ancestors or descendants and all documents that are related to a particular value in the tree. Using your example, you would be able to search for all descendants of Bob's, or any of his ancestors (and related documents). The answer above suggest: ``` { "_id": {"uname1":"Bob", "uname2":"Alice"}, "value": 2 } ``` That is correct. But you don't get to see the relationship between Bob and Cece with this design. My suggestion, which is from Mongo, is to store ancestor keys in an ancestor array. ``` { "_id": {"uname1":"Bob", "uname2":"Alice"}, "value": 2 , "ancestors": [{uname: "Cece"}]} ``` With this design you still get duplicates, which is something that you do not want. I would design it like this: ``` {"username": "Bob", "ancestors": [{"username": "Cece", "shared_value": 4}]} {"username": "Alice", "ancestors": [{"username": "Bob", "shared_value": 2}, {"username": "Cece"}]} ```
21,272,847
I have got a terminal app that gets user input stores it in a string then converts it into a int. The problem is if the user inputs anything that is not a number the conversion fails and the script continues without any indication that the string has not converted. Is there a way to check of the string contains any non digit characters. Here is the code: ``` #include <iostream> #include <string> #include <sstream> using namespace std; int main () { string mystr; float price=0; int quantity=0; cout << "Enter price: "; getline (cin,mystr); //gets user input stringstream(mystr) >> price; //converts string: mystr to float: price cout << "Enter quantity: "; getline (cin,mystr); //gets user input stringstream(mystr) >> quantity; //converts string: mystr to int: quantity cout << "Total price: " << price*quantity << endl; return 0; } ``` Just before the conversion here: `stringstream(mystr) >> price;` I want it to print a line to the console if the string is Not a Number.
2014/01/22
[ "https://Stackoverflow.com/questions/21272847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558108/" ]
You can find out if a read of an `int` has been successful or not by checking the `fail()` bit of your input stream: ``` getline (cin,mystr); //gets user input stringstream priceStream(mystr); priceStream >> price; if (priceStream.fail()) { cerr << "The price you have entered is not a valid number." << endl; } ``` [Demo on ideone.](http://ideone.com/Qh2qVr)
If your want to check if the price user inputs is a float, you can use `boost::lexical_cast<double>(mystr);`, if it throws an exception then your string is not a float.
21,272,847
I have got a terminal app that gets user input stores it in a string then converts it into a int. The problem is if the user inputs anything that is not a number the conversion fails and the script continues without any indication that the string has not converted. Is there a way to check of the string contains any non digit characters. Here is the code: ``` #include <iostream> #include <string> #include <sstream> using namespace std; int main () { string mystr; float price=0; int quantity=0; cout << "Enter price: "; getline (cin,mystr); //gets user input stringstream(mystr) >> price; //converts string: mystr to float: price cout << "Enter quantity: "; getline (cin,mystr); //gets user input stringstream(mystr) >> quantity; //converts string: mystr to int: quantity cout << "Total price: " << price*quantity << endl; return 0; } ``` Just before the conversion here: `stringstream(mystr) >> price;` I want it to print a line to the console if the string is Not a Number.
2014/01/22
[ "https://Stackoverflow.com/questions/21272847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558108/" ]
You can find out if a read of an `int` has been successful or not by checking the `fail()` bit of your input stream: ``` getline (cin,mystr); //gets user input stringstream priceStream(mystr); priceStream >> price; if (priceStream.fail()) { cerr << "The price you have entered is not a valid number." << endl; } ``` [Demo on ideone.](http://ideone.com/Qh2qVr)
It's going to add a bit to your code, but you can parse mystr with isdigit from cctype. The library's functions are [here](http://www.cplusplus.com/reference/cctype/). isdigit(mystr[index]) will return a false if that character in the string isn't a number.
22,492,338
I am working on a Chrome extension that will add content to a particular set of pages. From my research, it sounds like what I want is a [content script](https://developer.chrome.com/extensions/content_scripts) that will execute for the appropriate pages. I can specify the "appropriate pages" using the `content_script.matches` manifest.json field. However, the problem I'm running into is that content scripts run in an isolated world, [separate from the rest of your extension](https://developer.chrome.com/extensions/overview#contentScripts). How I had envisioned my extension was a set of [UI pages](https://developer.chrome.com/extensions/overview#pages) that would be embedded on the appropriate pages by the content script. The [background page](https://developer.chrome.com/extensions/overview#background_page) would contain the code for build the content of the UI pages. The background page, and by extension, the UI pages, would need access to the various Chrome APIs (e.g., local storage), as well as being able to make cross-domain requests to retrieve their data. However, it seems this is not possible, since the content scripts run in an isolated world, and don't have access to the Chrome APIs that I need. [Message passing](http://developer.chrome.com/extensions/messaging) allows a content script to send and receive data from the background page, but doesn't allow you to take a UI page and embed it on the current webpage. I initially thought I was making some headway on this when I was able to make a [jQuery AJAX request from my content script for an UI page](https://stackoverflow.com/questions/22315091/can-a-chrome-extension-content-script-make-an-jquery-ajax-request-for-an-html-fi), but that only gets me the HTML file itself. My UI pages depend on code to programmatically build the content--it's not just a static HTML page. And that "build the page" JavaScript code depends on Chrome APIs that are not available to the content script. So, if I just tried to make all my UI pages and JavaScript resources [web\_accessible\_resources](http://developer.chrome.com/extensions/manifest/web_accessible_resources), I could inject them into the page but they wouldn't be able to run. Which brings me to my question: how can a content script pull down, or embed, [UI pages](https://developer.chrome.com/extensions/overview#pages) that can invoke code in the background page?
2014/03/18
[ "https://Stackoverflow.com/questions/22492338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450668/" ]
By far the best choice is to rename the function parameter so it does not conflict with the global variable, so there is no need for circumventions. Assuming the rename option is not acceptable, use `::foo` to refer to `foo` at the global scope: ``` #include <iostream> int foo = 100; int bar(int foo) { int sum = foo + ::foo; // sum adds local variable and a global variable return sum; } int main() { int result = bar(12); cout << result << "\n"; return 0; } ``` Collisions between local and global names are bad — they lead to confusion — so it is worth avoiding them. You can use the `-Wshadow` option with GCC (`g++`, and with `gcc` for C code) to report problems with shadowing declarations; in conjunction with `-Werror`, it stops the code compiling.
Use `::foo` - but REALLY don't do that. It will confuse everyone, and you really shouldn't do those sort things. Instead, rename one or the other variable. It's a TERRIBLE idea to use the `::` prefix to solve this problem.
22,492,338
I am working on a Chrome extension that will add content to a particular set of pages. From my research, it sounds like what I want is a [content script](https://developer.chrome.com/extensions/content_scripts) that will execute for the appropriate pages. I can specify the "appropriate pages" using the `content_script.matches` manifest.json field. However, the problem I'm running into is that content scripts run in an isolated world, [separate from the rest of your extension](https://developer.chrome.com/extensions/overview#contentScripts). How I had envisioned my extension was a set of [UI pages](https://developer.chrome.com/extensions/overview#pages) that would be embedded on the appropriate pages by the content script. The [background page](https://developer.chrome.com/extensions/overview#background_page) would contain the code for build the content of the UI pages. The background page, and by extension, the UI pages, would need access to the various Chrome APIs (e.g., local storage), as well as being able to make cross-domain requests to retrieve their data. However, it seems this is not possible, since the content scripts run in an isolated world, and don't have access to the Chrome APIs that I need. [Message passing](http://developer.chrome.com/extensions/messaging) allows a content script to send and receive data from the background page, but doesn't allow you to take a UI page and embed it on the current webpage. I initially thought I was making some headway on this when I was able to make a [jQuery AJAX request from my content script for an UI page](https://stackoverflow.com/questions/22315091/can-a-chrome-extension-content-script-make-an-jquery-ajax-request-for-an-html-fi), but that only gets me the HTML file itself. My UI pages depend on code to programmatically build the content--it's not just a static HTML page. And that "build the page" JavaScript code depends on Chrome APIs that are not available to the content script. So, if I just tried to make all my UI pages and JavaScript resources [web\_accessible\_resources](http://developer.chrome.com/extensions/manifest/web_accessible_resources), I could inject them into the page but they wouldn't be able to run. Which brings me to my question: how can a content script pull down, or embed, [UI pages](https://developer.chrome.com/extensions/overview#pages) that can invoke code in the background page?
2014/03/18
[ "https://Stackoverflow.com/questions/22492338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450668/" ]
Use `::foo` - but REALLY don't do that. It will confuse everyone, and you really shouldn't do those sort things. Instead, rename one or the other variable. It's a TERRIBLE idea to use the `::` prefix to solve this problem.
Best practice is to always name global variables with a leading lower case "g" as in gX gY. It is never clear what you should name your variables at the beginning though. ::foo . That's a cool trick.
22,492,338
I am working on a Chrome extension that will add content to a particular set of pages. From my research, it sounds like what I want is a [content script](https://developer.chrome.com/extensions/content_scripts) that will execute for the appropriate pages. I can specify the "appropriate pages" using the `content_script.matches` manifest.json field. However, the problem I'm running into is that content scripts run in an isolated world, [separate from the rest of your extension](https://developer.chrome.com/extensions/overview#contentScripts). How I had envisioned my extension was a set of [UI pages](https://developer.chrome.com/extensions/overview#pages) that would be embedded on the appropriate pages by the content script. The [background page](https://developer.chrome.com/extensions/overview#background_page) would contain the code for build the content of the UI pages. The background page, and by extension, the UI pages, would need access to the various Chrome APIs (e.g., local storage), as well as being able to make cross-domain requests to retrieve their data. However, it seems this is not possible, since the content scripts run in an isolated world, and don't have access to the Chrome APIs that I need. [Message passing](http://developer.chrome.com/extensions/messaging) allows a content script to send and receive data from the background page, but doesn't allow you to take a UI page and embed it on the current webpage. I initially thought I was making some headway on this when I was able to make a [jQuery AJAX request from my content script for an UI page](https://stackoverflow.com/questions/22315091/can-a-chrome-extension-content-script-make-an-jquery-ajax-request-for-an-html-fi), but that only gets me the HTML file itself. My UI pages depend on code to programmatically build the content--it's not just a static HTML page. And that "build the page" JavaScript code depends on Chrome APIs that are not available to the content script. So, if I just tried to make all my UI pages and JavaScript resources [web\_accessible\_resources](http://developer.chrome.com/extensions/manifest/web_accessible_resources), I could inject them into the page but they wouldn't be able to run. Which brings me to my question: how can a content script pull down, or embed, [UI pages](https://developer.chrome.com/extensions/overview#pages) that can invoke code in the background page?
2014/03/18
[ "https://Stackoverflow.com/questions/22492338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450668/" ]
By far the best choice is to rename the function parameter so it does not conflict with the global variable, so there is no need for circumventions. Assuming the rename option is not acceptable, use `::foo` to refer to `foo` at the global scope: ``` #include <iostream> int foo = 100; int bar(int foo) { int sum = foo + ::foo; // sum adds local variable and a global variable return sum; } int main() { int result = bar(12); cout << result << "\n"; return 0; } ``` Collisions between local and global names are bad — they lead to confusion — so it is worth avoiding them. You can use the `-Wshadow` option with GCC (`g++`, and with `gcc` for C code) to report problems with shadowing declarations; in conjunction with `-Werror`, it stops the code compiling.
Best practice is to always name global variables with a leading lower case "g" as in gX gY. It is never clear what you should name your variables at the beginning though. ::foo . That's a cool trick.
31,306,027
I'm working on an FAQ type project using AngularJS. I have a number of questions and answers I need to import into the page and thought it would be a good idea to use a service/directive to load the content in dynamically from JSON. The text strings are quite unwieldily (639+ characters) and the overall hesitation I have is adding HTML into the JSON object to format the text (Line breaks etc). Is pulling HTML from JSON considered bad practice practice, and is there a better way to solve this? I'd prefer to avoid using multiple templates but it's starting to seem like a better approach. Thanks
2015/07/09
[ "https://Stackoverflow.com/questions/31306027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4933483/" ]
I replaced ``` var listeRef = from r in db.refAnomalies select r; ``` with ``` String sql = @"select * from refAnomalie"; List<refAnomalie> listeRefference = new List<refAnomalie>(); var con = new SqlConnection("data source=(LocalDb)\\MSSQLLocalDB;initial catalog=Banque;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"); using (var command= new SqlCommand(sql,con)){ con.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) listeRefference.Add(new refAnomalie { code_anomalie = reader.GetInt32(0), libelle_anomalie = reader.GetString(1), score_anomalie = reader.GetInt32(2), classe_anomalie = reader.GetString(3) }); } } ``` and it worked fine
The error message is quite clear: EF evidently generates a query simliar to... ``` select ..., rapportAnomalie_code_rapport, ... from refAnomalie ``` ...and the error tells you that there is no `rapportAnomalie_code_rapport` column in `refAnomalie`. You need to take a look at the class that EF generates for `refAnomalie`. There is probably a reference to that mysterious column somewhere in there.
31,306,027
I'm working on an FAQ type project using AngularJS. I have a number of questions and answers I need to import into the page and thought it would be a good idea to use a service/directive to load the content in dynamically from JSON. The text strings are quite unwieldily (639+ characters) and the overall hesitation I have is adding HTML into the JSON object to format the text (Line breaks etc). Is pulling HTML from JSON considered bad practice practice, and is there a better way to solve this? I'd prefer to avoid using multiple templates but it's starting to seem like a better approach. Thanks
2015/07/09
[ "https://Stackoverflow.com/questions/31306027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4933483/" ]
I replaced ``` var listeRef = from r in db.refAnomalies select r; ``` with ``` String sql = @"select * from refAnomalie"; List<refAnomalie> listeRefference = new List<refAnomalie>(); var con = new SqlConnection("data source=(LocalDb)\\MSSQLLocalDB;initial catalog=Banque;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"); using (var command= new SqlCommand(sql,con)){ con.Open(); using (var reader = command.ExecuteReader()) { while (reader.Read()) listeRefference.Add(new refAnomalie { code_anomalie = reader.GetInt32(0), libelle_anomalie = reader.GetString(1), score_anomalie = reader.GetInt32(2), classe_anomalie = reader.GetString(3) }); } } ``` and it worked fine
@Omar, Changing the complete approach is not the solution of the problem. The way I see this problem is you're having naming convention issue with Navigation properties. Which sometime confuses the EF and results in generating a "Guessed" column name which doesn't exist. I would recommend to thoroughly go through this [Discussion](https://stackoverflow.com/questions/11079863/entity-framework-navigation-property-generation-rules/11081568#11081568) about navigation property and name generations. Also check how to overcome this using [InverseProperty](https://stackoverflow.com/questions/24454938/invalid-column-name-error-when-trying-to-associate-objects-with-entityframework) attribute. Since We don't have complete details of your EF code first entities it's really hard to point out the problem area. But hope above suggestions will help you re-visit your code and identify the problem.
29,042,618
The app has a controller, that uses a service to create an instance of video player. The video player triggers events to show progress every few seconds. When the video reaches to a certain point, I want to show a widget on top of the video player. The view has the widget wrapped in ng-show directive. It takes more then 60 seconds for the dom element to receive the signal to remove the ng-hide class after the event has been triggered and the values have been populated. If I try to implement this using the plain dom menthod (like document.getElementById(eleId).innerHTML = newHTML), the update is instant. What am I doing wrong? Here is the complete sequence in code: Controller: ``` MyApp.controller('SectionController', ['$scope', 'PlayerService'], function($scope, PlayerService){ $scope.createPlayer = function() { PlayerService.createPlayer($scope, wrapperId); }}); ``` Service: ``` MyApp.service('PlayerService', [], function(){ this.createPlayer=function(controllerScope, playerWrapper){ PLAYER_SCRIPT.create(playerWrapper) { wrapper : playerWrapper, otherParam : value, onCreate : function(player) { player.subscribe(PLAY_TIME_CHANGE, function(duration){ showWidget(controllerScope, duration); }) } } } function showWidget(controllerScope, duration) { if(duration>CERTAIN_TIME) { $rootScope.widgetData = {some:data} $rootScope.showWidget = true; } }}); ``` View: ``` <div ng-show="showWidget"> <div class="wdgt">{{widgetData.stuff}}</div> </div> ```
2015/03/13
[ "https://Stackoverflow.com/questions/29042618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/979535/" ]
Solved it! $scope.$apply() did the trick. My guess is, due to other complex logic ad bindings inside the app, there was a delay in computing the change by angular the default way. @floribon Thanks for the subtle hint about "complex angular stuff". The code inside the service function changed to: ``` function showWidget(controllerScope, duration) { if(duration>CERTAIN_TIME) { $rootScope.widgetData = {some:data} $rootScope.showWidget = true; $rootScope.$apply(); }} ```
Do you have complex angular stuff within your hidden view? You should try to use `ng-if` instead of `ng-show`, the difference being that when the condition is false, `ng-if` will remove the element from the DOM instead of just hidding it (which is also what you do in vanilla JS). When the view is simply hidden using `ng-show` however, all the watchers and bindings within it keep being computed by Angular. Let us know if `ng-if` solve your problem, otherwise I'll edit my answer.
19,291,746
I have a string: `{2013/05/01},{2013/05/02},{2013/05/03}` I want to append a { at the beginning and a } at the end. The output should be: `{{2013/05/01},{2013/05/02},{2013/05/03}}` However, in my shell script when I concatenate the curly braces to the beginning and end of the string, the output is as follows: `{2013/05/01} {2013/05/02} {2013/05/03}` Why does this happen? How can I achieve my result? Am sure there is a simple solution to this but I am a unix newbie, thus would appreciate some help. Test script: ``` #!/usr/bin/ksh valid_data_range="{2013/05/01},{2013/05/02},{2013/05/03}" finalDates="{"$valid_data_range"}" print $finalDates ```
2013/10/10
[ "https://Stackoverflow.com/questions/19291746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2844037/" ]
The problem is that when you have a list in braces outside quotes, the shell performs [Brace Expansion](http://www.gnu.org/software/bash/manual/bash.html#Brace-Expansion) (`bash` manual, but [`ksh`](http://www2.research.att.com/sw/download/man/man1/ksh.html) will be similar). Since the 'outside quotes' bit is important, it also tells you how to avoid the problem — enclose the string in quotes when printing: ``` #!/usr/bin/ksh valid_data_range="{2013/05/01},{2013/05/02},{2013/05/03}" finalDates="{$valid_data_range}" print "$finalDates" ``` (The `print` command is specific to `ksh` and is not present in `bash`. The change in the assignment line is more cosmetic than functional.) Also, the brace expansion would not occur in `bash`; it only occurs when the braces are written directly. This bilingual script (`ksh` and `bash`): ``` valid_data_range="{2013/05/01},{2013/05/02},{2013/05/03}" finalDates="{$valid_data_range}" printf "%s\n" "$finalDates" printf "%s\n" $finalDates ``` produces: 1. `ksh` ``` {{2013/05/01},{2013/05/02},{2013/05/03}} {2013/05/01} {2013/05/02} {2013/05/03} ``` 2. `bash` (also `zsh`) ``` {{2013/05/01},{2013/05/02},{2013/05/03}} {{2013/05/01},{2013/05/02},{2013/05/03}} ``` Thus, when you need to use the variable `$finalDates`, ensure it is inside double quotes: ``` other_command "$finalDates" if [ "$finalDates" = "$otherString" ] then : whatever else : something fi ``` Etc — using your preferred layout for whatever you don't like about mine.
You can say: ``` finalDates=$'{'"$valid_data_range"$'}' ```
19,291,746
I have a string: `{2013/05/01},{2013/05/02},{2013/05/03}` I want to append a { at the beginning and a } at the end. The output should be: `{{2013/05/01},{2013/05/02},{2013/05/03}}` However, in my shell script when I concatenate the curly braces to the beginning and end of the string, the output is as follows: `{2013/05/01} {2013/05/02} {2013/05/03}` Why does this happen? How can I achieve my result? Am sure there is a simple solution to this but I am a unix newbie, thus would appreciate some help. Test script: ``` #!/usr/bin/ksh valid_data_range="{2013/05/01},{2013/05/02},{2013/05/03}" finalDates="{"$valid_data_range"}" print $finalDates ```
2013/10/10
[ "https://Stackoverflow.com/questions/19291746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2844037/" ]
The problem is that when you have a list in braces outside quotes, the shell performs [Brace Expansion](http://www.gnu.org/software/bash/manual/bash.html#Brace-Expansion) (`bash` manual, but [`ksh`](http://www2.research.att.com/sw/download/man/man1/ksh.html) will be similar). Since the 'outside quotes' bit is important, it also tells you how to avoid the problem — enclose the string in quotes when printing: ``` #!/usr/bin/ksh valid_data_range="{2013/05/01},{2013/05/02},{2013/05/03}" finalDates="{$valid_data_range}" print "$finalDates" ``` (The `print` command is specific to `ksh` and is not present in `bash`. The change in the assignment line is more cosmetic than functional.) Also, the brace expansion would not occur in `bash`; it only occurs when the braces are written directly. This bilingual script (`ksh` and `bash`): ``` valid_data_range="{2013/05/01},{2013/05/02},{2013/05/03}" finalDates="{$valid_data_range}" printf "%s\n" "$finalDates" printf "%s\n" $finalDates ``` produces: 1. `ksh` ``` {{2013/05/01},{2013/05/02},{2013/05/03}} {2013/05/01} {2013/05/02} {2013/05/03} ``` 2. `bash` (also `zsh`) ``` {{2013/05/01},{2013/05/02},{2013/05/03}} {{2013/05/01},{2013/05/02},{2013/05/03}} ``` Thus, when you need to use the variable `$finalDates`, ensure it is inside double quotes: ``` other_command "$finalDates" if [ "$finalDates" = "$otherString" ] then : whatever else : something fi ``` Etc — using your preferred layout for whatever you don't like about mine.
The problem is that the shell is performing brace expansion. This allows you to generate a series of similar strings: ``` $ echo {a,b,c} a b c ``` That's not very impressive, but consider ``` $ echo a{b,c,d}e abc ace ade ``` In order to suppress brace expansion, you can use the `set` command to turn it off temporarily ``` $ set +B $ echo a{b,c,d}e a{b,c,d}e $ set -B $ echo a{b,c,d}e abe ace ade ```
7,056,634
I'd like to read and write window registry in **window xp and 7** by using **vb6**. I'm not much strong in vb6. I tried this below ``` Dim str As String str = GetSetting("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines", "Text", "ImportMixedTypes") ``` My coding doesn't work. Please point out my missing.
2011/08/14
[ "https://Stackoverflow.com/questions/7056634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305732/" ]
You can't use `GetSetting` for that setting. That method is only for reading/writing configuration settings for your own application. If you want to read anywhere in the registry you have to use the Windows API function [RegOpenKeyEx](http://msdn.microsoft.com/en-us/library/ms724897%28v=vs.85%29.aspx) and friends. Here's a Microsoft support article that explains how to do this (with sample code): [How To Use the Registry API to Save and Retrieve Setting](http://support.microsoft.com/kb/145679) Note that you will have to have permission to read the relevant place in the registry, I'm not sure if you'll have access to that key so you'll have to try it out.
HKEY\_LOCAL\_MACHINE can cause permission problems. described in these article [Microsoft API article](https://support.microsoft.com/ru-ru/kb/145679) procedures works well if you will change HKEY\_LOCAL\_MACHINE to CURRENT\_USER.
74,514,734
I want to fit parent div height to fit it's child that means I want height of parent div to fit red color and green part will hide <https://jsfiddle.net/zfpwb54L/> ``` <style> .container { margin-left: auto; margin-right: auto; padding-left: 15px; padding-right: 15px; width: 100%; } .section { padding: 20px 0; position: relative; } .style_content { color: #27272a; max-width: 700px; position: relative; text-align: center; z-index: 9; } </style> <div id="parent" style="background-color:green; position: relative; direction: rtl;width:fit-content;"> <div style="position: absolute; inset: 0px;"></div> <div style="width: 280px;; "> <div id="child" style="background:red;flex: 0 0 auto; width: 1400px; transform-origin: right top 0px; transform: matrix(0.2, 0, 0, 0.2, 0, 0);"> <section class="section"> <div class="style_content container"> <div><h1>Hello</h1></div> <div><p>that is for test.that is for test.that is for test.that is for test.that is for test. that is for test.that is for test.that is for test.that is for test.that is for test.that is for test.that is for test.that is for test.</p></div> <a href="#" target="_blank">click me</a> </div> </section> </div> </div> </div> ```
2022/11/21
[ "https://Stackoverflow.com/questions/74514734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9779942/" ]
For testing your agent in a custom environment alter the endpoint URL to `https://dialogflow.googleapis.com/v2/projects/my-project-id/agent/environments/<env-name>/users/-/sessions/123456789:detectIntent` curl command: ``` curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "x-goog-user-project: PROJECT_ID" \ -H "Content-Type: application/json; charset=utf-8" \ -d @request.json \ "https://dialogflow.googleapis.com/v2/projects/my-project-id/agent/environments/<env-name>/users/-/sessions/123456789:detectIntent" ```
Like [@SakshiGat](https://stackoverflow.com/users/15750473/sakshi-gatyan) mentioned, the curl URL was invalid. Invalid URL: "https://dialogflow.googleapis.com/v2/projects/<project\_name>/agent/environments/DEV/sessions/<session\_id>:detectIntent" Valid URL: "https://dialogflow.googleapis.com/v2/projects/**<project\_id>**/agent/environments/DEV/**users/-**/sessions/<session\_id>:detectIntent"
20,365
I cannot open a SQLConnection to a SQL vectorwise database and I assume the JDBC driver is the problem. A JAR file was provided to me - the only info additionally provided to me was the java class: **com.ingres.jdbc.IngresDriver** What would I have to do to add it to the JDBCDrivers that Mathematica can use? Hope this is sufficient information - please let me know, if more information is required. Thanks and regards Patrick
2013/02/27
[ "https://mathematica.stackexchange.com/questions/20365", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/5797/" ]
Finally found the answer on how to connect MM to Actian vectorwise via SQL :) ``` Needs["JLink`"] AddToClassPath["C:\\Users\\Desktop\\iijdbc.jar"]; Needs["DatabaseLink`"]; OpenSQLConnection[ JDBC["com.ingres.jdbc.IngresDriver", "jdbc:ingres://HOST:VW7/DATABASE;user=xxx;password=yyy"]] ``` Feeling good! Pat
In the case where you want to use an *updated* driver in preference to an older one shipped with Mathematica, `AddToClassPath[ ...path..., Prepend -> True]`. For instance to use xerial's up-to-date SQLite driver: ``` Needs["JLink`"]; Needs["DatabaseLink`"]; ReinstallJava[]; jdbcdriver = FindFile["my-path-to/sqlite-jdbc-3.32.3.2.jar"] AddToClassPath[jdbcdriver, Prepend -> True]; ```
7,377,628
I have a table of 5700 records. The primary key is an integer. Now I noticed that some values are missing. Like this: ``` 100 data 101 data 102 data 104 data ``` `103` is missing. How I can update all the rows so that the order becomes correct (`104` becomes `103` in my example) in one SQL command?
2011/09/11
[ "https://Stackoverflow.com/questions/7377628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616129/" ]
There is no point in doing this. IDs from deleted records are not re-used on purpose - to make sure that references from other tables to previously deleted records don't suddenly point to the *wrong* record, for example. It is not a good idea to try to change this. If you want a numbered list that has no holes, create a second `int` column that you re-order in your client program whenever necessary (i.e. when a record is deleted).
I'd advise against messing with your PKs unless you really have no choice, it can cause breakage all over the place when that id column is referred by other tables. If the PK really tolerates no gaps, maybe the choice of PK was not ideal... If you really think you should do this (and are sure nothing will break in other tables): * create a table with the same structure as the original one, but use type serial for id * copy data without id into that copy table - you'll now have a copy of original with thanks to serial a nice gapless id field * empty original table (or faster, create an identical copy and drop original) * copy data from copy table into original table including id
7,377,628
I have a table of 5700 records. The primary key is an integer. Now I noticed that some values are missing. Like this: ``` 100 data 101 data 102 data 104 data ``` `103` is missing. How I can update all the rows so that the order becomes correct (`104` becomes `103` in my example) in one SQL command?
2011/09/11
[ "https://Stackoverflow.com/questions/7377628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616129/" ]
Not sure about one command, but you can do it in four commands: ``` CREATE TABLE `temp` SELECT * FROM `orig_tbl`; TRUNCATE `orig_tbl`; -- counter doesn't reset in some old versions ALTER TABLE `orig_tbl` AUTO_INCREMENT = 1; -- now we omit primary key column to let it seal the holes INSERT INTO `orig_tbl` (`col1`, `col2`) SELECT `col1`, `col2` FROM `temp`; ``` Unless you're doing this to make it easier to select records randomly, you really should rethink your approach.
There is no point in doing this. IDs from deleted records are not re-used on purpose - to make sure that references from other tables to previously deleted records don't suddenly point to the *wrong* record, for example. It is not a good idea to try to change this. If you want a numbered list that has no holes, create a second `int` column that you re-order in your client program whenever necessary (i.e. when a record is deleted).
7,377,628
I have a table of 5700 records. The primary key is an integer. Now I noticed that some values are missing. Like this: ``` 100 data 101 data 102 data 104 data ``` `103` is missing. How I can update all the rows so that the order becomes correct (`104` becomes `103` in my example) in one SQL command?
2011/09/11
[ "https://Stackoverflow.com/questions/7377628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616129/" ]
Try this: ``` SET @var:=0; UPDATE `table` SET `id`=(@var:=@var+1); ALTER TABLE `table` AUTO_INCREMENT=1; ```
There is no point in doing this. IDs from deleted records are not re-used on purpose - to make sure that references from other tables to previously deleted records don't suddenly point to the *wrong* record, for example. It is not a good idea to try to change this. If you want a numbered list that has no holes, create a second `int` column that you re-order in your client program whenever necessary (i.e. when a record is deleted).
7,377,628
I have a table of 5700 records. The primary key is an integer. Now I noticed that some values are missing. Like this: ``` 100 data 101 data 102 data 104 data ``` `103` is missing. How I can update all the rows so that the order becomes correct (`104` becomes `103` in my example) in one SQL command?
2011/09/11
[ "https://Stackoverflow.com/questions/7377628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616129/" ]
There is no point in doing this. IDs from deleted records are not re-used on purpose - to make sure that references from other tables to previously deleted records don't suddenly point to the *wrong* record, for example. It is not a good idea to try to change this. If you want a numbered list that has no holes, create a second `int` column that you re-order in your client program whenever necessary (i.e. when a record is deleted).
Another way, without truncating whole table: ``` -- Make Backup of original table's content CREATE TABLE `orig_tbl_backup` SELECT * FROM `orig_tbl`; -- Drop needed column. ALTER TABLE `orig_tbl` DROP `id`; -- Re-create it ALTER TABLE `orig_tbl` AUTO_INCREMENT = 1; ALTER TABLE `orig_tbl` ADD `id` int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST; ```
7,377,628
I have a table of 5700 records. The primary key is an integer. Now I noticed that some values are missing. Like this: ``` 100 data 101 data 102 data 104 data ``` `103` is missing. How I can update all the rows so that the order becomes correct (`104` becomes `103` in my example) in one SQL command?
2011/09/11
[ "https://Stackoverflow.com/questions/7377628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616129/" ]
Not sure about one command, but you can do it in four commands: ``` CREATE TABLE `temp` SELECT * FROM `orig_tbl`; TRUNCATE `orig_tbl`; -- counter doesn't reset in some old versions ALTER TABLE `orig_tbl` AUTO_INCREMENT = 1; -- now we omit primary key column to let it seal the holes INSERT INTO `orig_tbl` (`col1`, `col2`) SELECT `col1`, `col2` FROM `temp`; ``` Unless you're doing this to make it easier to select records randomly, you really should rethink your approach.
I'd advise against messing with your PKs unless you really have no choice, it can cause breakage all over the place when that id column is referred by other tables. If the PK really tolerates no gaps, maybe the choice of PK was not ideal... If you really think you should do this (and are sure nothing will break in other tables): * create a table with the same structure as the original one, but use type serial for id * copy data without id into that copy table - you'll now have a copy of original with thanks to serial a nice gapless id field * empty original table (or faster, create an identical copy and drop original) * copy data from copy table into original table including id
7,377,628
I have a table of 5700 records. The primary key is an integer. Now I noticed that some values are missing. Like this: ``` 100 data 101 data 102 data 104 data ``` `103` is missing. How I can update all the rows so that the order becomes correct (`104` becomes `103` in my example) in one SQL command?
2011/09/11
[ "https://Stackoverflow.com/questions/7377628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616129/" ]
Try this: ``` SET @var:=0; UPDATE `table` SET `id`=(@var:=@var+1); ALTER TABLE `table` AUTO_INCREMENT=1; ```
I'd advise against messing with your PKs unless you really have no choice, it can cause breakage all over the place when that id column is referred by other tables. If the PK really tolerates no gaps, maybe the choice of PK was not ideal... If you really think you should do this (and are sure nothing will break in other tables): * create a table with the same structure as the original one, but use type serial for id * copy data without id into that copy table - you'll now have a copy of original with thanks to serial a nice gapless id field * empty original table (or faster, create an identical copy and drop original) * copy data from copy table into original table including id
7,377,628
I have a table of 5700 records. The primary key is an integer. Now I noticed that some values are missing. Like this: ``` 100 data 101 data 102 data 104 data ``` `103` is missing. How I can update all the rows so that the order becomes correct (`104` becomes `103` in my example) in one SQL command?
2011/09/11
[ "https://Stackoverflow.com/questions/7377628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616129/" ]
Try this: ``` SET @var:=0; UPDATE `table` SET `id`=(@var:=@var+1); ALTER TABLE `table` AUTO_INCREMENT=1; ```
Not sure about one command, but you can do it in four commands: ``` CREATE TABLE `temp` SELECT * FROM `orig_tbl`; TRUNCATE `orig_tbl`; -- counter doesn't reset in some old versions ALTER TABLE `orig_tbl` AUTO_INCREMENT = 1; -- now we omit primary key column to let it seal the holes INSERT INTO `orig_tbl` (`col1`, `col2`) SELECT `col1`, `col2` FROM `temp`; ``` Unless you're doing this to make it easier to select records randomly, you really should rethink your approach.
7,377,628
I have a table of 5700 records. The primary key is an integer. Now I noticed that some values are missing. Like this: ``` 100 data 101 data 102 data 104 data ``` `103` is missing. How I can update all the rows so that the order becomes correct (`104` becomes `103` in my example) in one SQL command?
2011/09/11
[ "https://Stackoverflow.com/questions/7377628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616129/" ]
Not sure about one command, but you can do it in four commands: ``` CREATE TABLE `temp` SELECT * FROM `orig_tbl`; TRUNCATE `orig_tbl`; -- counter doesn't reset in some old versions ALTER TABLE `orig_tbl` AUTO_INCREMENT = 1; -- now we omit primary key column to let it seal the holes INSERT INTO `orig_tbl` (`col1`, `col2`) SELECT `col1`, `col2` FROM `temp`; ``` Unless you're doing this to make it easier to select records randomly, you really should rethink your approach.
Another way, without truncating whole table: ``` -- Make Backup of original table's content CREATE TABLE `orig_tbl_backup` SELECT * FROM `orig_tbl`; -- Drop needed column. ALTER TABLE `orig_tbl` DROP `id`; -- Re-create it ALTER TABLE `orig_tbl` AUTO_INCREMENT = 1; ALTER TABLE `orig_tbl` ADD `id` int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST; ```
7,377,628
I have a table of 5700 records. The primary key is an integer. Now I noticed that some values are missing. Like this: ``` 100 data 101 data 102 data 104 data ``` `103` is missing. How I can update all the rows so that the order becomes correct (`104` becomes `103` in my example) in one SQL command?
2011/09/11
[ "https://Stackoverflow.com/questions/7377628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/616129/" ]
Try this: ``` SET @var:=0; UPDATE `table` SET `id`=(@var:=@var+1); ALTER TABLE `table` AUTO_INCREMENT=1; ```
Another way, without truncating whole table: ``` -- Make Backup of original table's content CREATE TABLE `orig_tbl_backup` SELECT * FROM `orig_tbl`; -- Drop needed column. ALTER TABLE `orig_tbl` DROP `id`; -- Re-create it ALTER TABLE `orig_tbl` AUTO_INCREMENT = 1; ALTER TABLE `orig_tbl` ADD `id` int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST; ```
44,811,928
I'm looking to make a method which detects if the following value in an array is a duplicate, and deletes it if so. It should work for both strings and integers. For example, given the Array: ``` arr = ["A", "B", "B", "C", "c", "A", "D", "D"] ``` Return: ``` arr = ["A", "B", "C", "c", "A", "D"] ``` I tried creating an empty Array `a`, and shovelling the values in, providing the following value was not equal to the current one. I attempted this like so: ``` arr.each do |x| following_value = arr.index(x) + 1 a << x unless x == arr[following_value] end ``` Unfortunately, instead of shovelling one of the duplicate values into the array, it shovelled neither. ``` arr = ["A", "C", "c", "A"] ``` Can anybody help? Bonus points for telling me exactly what went wrong with my method. Thanks!
2017/06/28
[ "https://Stackoverflow.com/questions/44811928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6831572/" ]
First at all, here is simpler solution: ``` > arr.delete_if.with_index { |e, ind| e == arr[ind+1] } #=> ["A", "B", "C", "c", "A", "D"] ``` But, this solution will mutate `arr`. Here are one-line solutions without mutates: ``` arr.each_with_index.with_object([]) { |(e, ind), res| res << e if e != arr[ind+1] } arr.each_with_object([]) { |e, res| res << e if res.last != e } ``` Your problem in this line: `a << x unless x == arr[following_value]` You say: put this `element` into `result` if `next element` isn't equal to it. So, instead, you can say something like: *put this element to result if the last element of the result isn't equal to it*: ``` arr.each do |x| a << x unless a.last == x end ```
I would use [select](https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-select), so you could do something like: ``` a = ["A", "B", "B", "C", "c", "A", "D", "D"] # without mutation b = a.select.with_index { |e, i| a[i+1] != e } a #=> ["A", "B", "B", "C", "c", "A", "D", "D"] b #=> ["A", "B", "C", "c", "A", "D"] # with mutation a.select!.with_index { |e, i| a[i+1] != e } a #=> ["A", "B", "C", "c", "A", "D"] ``` BTW your method is not working because `arr.index(x)` [returns index of first object for which block is true](https://apidock.com/ruby/Array/index): ``` arr = ["A", "B", "B", "C", "c", "A", "D", "D"] arr.each do |x| puts "#{x} has index #{arr.index(x)}" end A has index 0 B has index 1 B has index 1 # you were expecting 2 C has index 3 c has index 4 A has index 0 # you were expecting 5 D has index 6 D has index 6 # you were expecting 7 ```