qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
19,084,382
Using RStudio --> CompilePDF In a .Rnw document to be processed with pdflatex, I'd like to get a list of all user (me) packages loaded via library() or require() in the document. I tried to use sessionInfo(), as in ``` \AtEndDocument{ \medskip \textbf{Packages used}: \Sexpr{names(sessionInfo()$loadedOnly)}. } ``` however, what this prints is just the list of packages used by knitr itself, > > Packages used: digest, evaluate, formatR, highr, stringr, tools. > > > not those I explicitly referred to. I believe this is because knitr runs the code chunks within an internal environment, but I don't know how to access that. I know about the file cache/\_\_packages that is created with cache=TRUE; is there any way to generate this automatically without caching?
2013/09/29
[ "https://Stackoverflow.com/questions/19084382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1873697/" ]
The problem with this approach is that the \Sexpr{} within the \AtEndDocument{} block in the preamble is evaluated at knit-time (the beginning of the .Rnw file, so it returns an empty list. In the generated .tex file, this appears as ``` \AtEndDocument{ \medskip \textbf{Packages used}: . } ``` The only way this will work is to include the code to generate this text explicitly at the end of the .Rnw file (which in my case is a child documenht, e.g., ``` ... \bibliography{graphics,statistics} Inside child document: \textbf{Packages used}: \Sexpr{setdiff(.packages(), c("knitr", "stats", "graphics", "grDevices", "utils", "datasets", "methods", "base"))}. ```
A somewhat different, perhaps more explicit and detailed approach, expanding on answers given previously. This would appear in the `\backmatter` of a book. The value `nColOut` is the number of columns of the printed table containing the list of packages used. ``` \cleardoublepage \printindex \cleardoublepage \chapter*{Packages} <<packages, cache = FALSE, echo = FALSE, warning = FALSE, results = "asis">>= nColOut = 7 packsAll <- unique(c(.packages(), loadedNamespaces(), readLines('cache/__packages'))) packsReduced <- setdiff(packsAll, c("knitr", "stats", "graphics", "grDevices", "utils", "datasets", "methods", "base")) howManyPacks <- packsReduced %>% length() numLines <- tibble(numPacks = howManyPacks + 0:(nColOut - 1), n = numPacks %% nColOut) howManyToAdd <- numLines %>% filter(n == 0) %>% mutate(diff = numPacks - howManyPacks) %>% pull(diff) packsReduced %>% sort() %>% as_tibble() %>% add_row(value = rep('', howManyToAdd)) %>% mutate(id = rep(1:(length(value) / nColOut), nColOut), col = rep(letters[1 : nColOut], each = length(value) / nColOut)) %>% pivot_wider(names_from = col, values_from = value) %>% select(-id) %>% kable("latex", booktabs = TRUE, longtable = TRUE) %>% kable_styling(latex_options = "repeat_header") %>% row_spec(0, align = "c") @ ```
32,990,711
In Emacs, when a buffer is killed, it is still displayed on the buffer list (though it's empty after opening it from the list). Is is possible to remove the buffer from the buffer list?
2015/10/07
[ "https://Stackoverflow.com/questions/32990711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853300/" ]
Just refresh the buffer list by pressing `g`.
You can define a function to achieve it automatically: ``` (defun my-kill-buffer () (interactive) (kill-buffer) (if (get-buffer "*Buffer List*") (save-excursion (set-buffer "*Buffer List*") (revert-buffer)) )) ```
40,172
A friend in the business sector recently asked me for advice on "IT security in a large charity". Being a developer not specialized in security, I could see his difficulty in finding someone qualified to hire to counsel him. Struggling for answers, the only example I could advance was the following: if you're seriously asked to give out your password for an audit to be conducted (and this not being a "test", of course), you're probably dealing with someone who doesn't know what they're doing. What are some helpful tips and pointers you could give a non-technical manager in choosing a competent / avoiding choosing (and hiring) an incompetent professional? I am aware this question might be off-topic, but the purpose of this question is to give some general resources to non-technical decision makers to hire someone qualified.
2013/08/06
[ "https://security.stackexchange.com/questions/40172", "https://security.stackexchange.com", "https://security.stackexchange.com/users/21642/" ]
**No**, *longer* is not *stronger*. What makes a password strong is its *entropy*: how much unknown the password is to the attacker. Adding a "non-entropic" suffix to the password does not add to the entropy (by definition) so it does not increase the hardness of the task for the attacker. It *does* increase the hardness for the normal user, though, since that means more keys to type in. Adding a known suffix or prefix does not *lower* security either, except in the indirect effect of encouraging the user to choose a less entropic password to make his job easier. *Unless* the password processing makes something dumb, of course. For instance, suppose that passwords are truncated to their first eight characters (typical of old DES-based [Unix `crypt()`](http://en.wikipedia.org/wiki/Crypt_%28C%29)) and that you add a fixed 6-letter *prefix* to your password, turning "`o7843vD!`" into "`123456o7`": in *that* case, the prefix makes the attack much easier.
Length does complicate brute force attacks; a longer password is stronger. High entropy passwords are stronger than low entropy passwords. Even if the attack is based on rainbow tables, rainbow tables for short passwords are cheaper to calculate, store, and manage. If the attacker is stealing the password from some other plaintext source, then the length and complexity are both meaningless; if the attacker is trying any form of a brute force attack, then the complexity of the attack is related to both entropy and length. The relative value of an increment in complexity vs an increment in length would be interesting, but is probably related to specifics of the attack technique. For example, if you extend length by adding a digit to a password, (XXX vs XXX1), the increment is negligible, because most password crackers will automatically test every password with each digit appended, and the time to do 10 additional tests is imperceptible.
36,540
Just as we have the genesis block which is block 0, is there a special name for the block currently at the head of the chain? Obviously such a block would be observer dependent and never absolute but I am curious all the same.
2015/03/21
[ "https://bitcoin.stackexchange.com/questions/36540", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/24780/" ]
The Bitcoin source code refers to it as the 'tip,' e.g., `UpdateTip`, `SetTip`, `ConnectTip`. It's sometimes referred to as the latest block; that's not totally accurate, since the latest block is not always the tip.
Nothing formal, but "latest block" pretty much describes it.
33,369,748
I want to define a one-to-many relationship between my Student model and my Formation model: 1 student belongs to 1 formation and a formation can be composed of N students. My needs are: * be able to populate a Formation document with its students * easily retrieve the Formation of a Student So I wrote: ``` let student = new Schema({ firstName: { type: String }, lastName: { type: String }, formation : { type: Schema.Types.ObjectId, ref: 'Formation' } }); let formation = new Schema({ title: { type: String }, students: [{ type: Schema.Types.ObjectId, ref: 'Student' }] } ``` When I'm searching for documentation about the one-to-many relation with mongodb/mongoose, I'm surprised to see that when I want to create a Student document (and add it to a formation), I must not only set its "formation" field with the formation id and also push it to the formation document "students" field. Does it imply that when I want to replace the formation of a student with another formation, I'll need to 1/ update its formation field 2/ remove myself the student id from the formation "students" field and re-add it to the students field of the new formation? It seems a little redundant to me. Am I missing something?
2015/10/27
[ "https://Stackoverflow.com/questions/33369748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25888/" ]
Having `students` on the Formation model is both bad practice and redundant. Potentially infinite arrays are a poor design as they can lead to hitting document size limits. In regards to being redundant, you only have two queries in this situation: 1) You have a `student` in memory, and you want to find their formation: ``` Formation.findOne({_id: student.formation},callback); ``` 2) You have a `formation` in memory, and want to find all students in that formation: ``` Student.find({formation: formation._id}, callback); ``` Neither of which require having `students` on the Formation schema.
It is in fact redundant because the way you have defined your schemas is redundant. The array of students should be a property of the formation, **but not the other way around**. Subdocuments can be searched like normal collections. If you change your schema to: ``` let student = new Schema({ firstName: { type: String }, lastName: { type: String } }); let formation = new Schema({ title: { type: String }, students: [{ type: Schema.Types.ObjectId, ref: 'Student' }] } ``` You should be able to accomplish your needs with fairly short commands. Assuming formations and students are your collection names: 1: Generating a student and saving both the formation and student documents. ``` var stud = new student({name: "Sally"}); //Assuming you modeled to student stud.save(function (err, student) { formations.findOne({}, function (err, form) { //Dont know how you find formations, I assume you know form.students.push(stud._id); form.save(callback); } }); ``` 2. Retrieving the formation of a student with a given ID: ``` formations.findOne({"students" : { $elemMatch: {_id: id}}}, function (err, doc) {}) ``` 3. Even moving a student is relatively simple. `formNew.students.push (` `formOld.students.pop(formOld.students.indexOf(formOld.students.findOne( //elemMatch like above )))` Sorry about the weird formatting.
4,240,184
I've got a little problem, and i don't see it. I retrieve Json data (the `JSONArray`) and i wanted to make a `List` of all the names in the `JSONArray`, something like this. ``` List list = new ArrayList<String>(); for(int i=0;i < data.length();i++){ list.add(data.getJSONObject(i).getString("names").toString()); } ``` And i wanted to take this list in an `ListView' so i did this : ``` ArrayList<String> test = history_share.list; names_list = (String[]) test.toArray(); ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, names_list); setListAdapter(adapter); ``` (history\_share is one of the method i created to take json data from an api . Eclipse doesn't see any error, and me neither. Can somebody help me please ?
2010/11/21
[ "https://Stackoverflow.com/questions/4240184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439058/" ]
Your problem has nothing to do with ASCII or character sets. In Java, a `char` is just a 16-bit integer. When casting ints (which are 32-bit integers) to chars, the only thing you are doing is keeping the 16 least significant bits of the int, and discarding the upper 16 bits. This is called a *narrowing conversion*. References: * <http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#20232> * <http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363>
The conversion between characters and integers uses the [Unicode](http://en.wikipedia.org/wiki/Unicode) values, of which ASCII is a subset. If you are handling binary data you should avoid characters and strings and instead use an integer array - note that Java doesn't have unsigned 8-bit integers.
4,240,184
I've got a little problem, and i don't see it. I retrieve Json data (the `JSONArray`) and i wanted to make a `List` of all the names in the `JSONArray`, something like this. ``` List list = new ArrayList<String>(); for(int i=0;i < data.length();i++){ list.add(data.getJSONObject(i).getString("names").toString()); } ``` And i wanted to take this list in an `ListView' so i did this : ``` ArrayList<String> test = history_share.list; names_list = (String[]) test.toArray(); ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, names_list); setListAdapter(adapter); ``` (history\_share is one of the method i created to take json data from an api . Eclipse doesn't see any error, and me neither. Can somebody help me please ?
2010/11/21
[ "https://Stackoverflow.com/questions/4240184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439058/" ]
The conversion between characters and integers uses the [Unicode](http://en.wikipedia.org/wiki/Unicode) values, of which ASCII is a subset. If you are handling binary data you should avoid characters and strings and instead use an integer array - note that Java doesn't have unsigned 8-bit integers.
What you search for in not a cast, it's a conversion. There is a String constructor that takes an array of byte and a charset encoding. This should help you.
4,240,184
I've got a little problem, and i don't see it. I retrieve Json data (the `JSONArray`) and i wanted to make a `List` of all the names in the `JSONArray`, something like this. ``` List list = new ArrayList<String>(); for(int i=0;i < data.length();i++){ list.add(data.getJSONObject(i).getString("names").toString()); } ``` And i wanted to take this list in an `ListView' so i did this : ``` ArrayList<String> test = history_share.list; names_list = (String[]) test.toArray(); ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, names_list); setListAdapter(adapter); ``` (history\_share is one of the method i created to take json data from an api . Eclipse doesn't see any error, and me neither. Can somebody help me please ?
2010/11/21
[ "https://Stackoverflow.com/questions/4240184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439058/" ]
The conversion between characters and integers uses the [Unicode](http://en.wikipedia.org/wiki/Unicode) values, of which ASCII is a subset. If you are handling binary data you should avoid characters and strings and instead use an integer array - note that Java doesn't have unsigned 8-bit integers.
> > I'm working on a project in which I > read in a string of binary characters, > convert it into chunks, and convert > the chunks into their values in > decimal, ints, which I then cast as > chars. I then need to be able to > "expand" the resulting compressed > characters back to binary by reversing > the process. > > > You don't mention *why* you are doing that, and (to be honest) it's a little hard to follow what you're trying to describe (for one thing, I don't see why the resulting characters would be "compressed" in any way. If you just want to represent binary data as text, there are plenty of [standard ways](http://en.wikipedia.org/wiki/Binary-to-text_encoding) of accomplishing that. But it sounds like you may be after something else?
4,240,184
I've got a little problem, and i don't see it. I retrieve Json data (the `JSONArray`) and i wanted to make a `List` of all the names in the `JSONArray`, something like this. ``` List list = new ArrayList<String>(); for(int i=0;i < data.length();i++){ list.add(data.getJSONObject(i).getString("names").toString()); } ``` And i wanted to take this list in an `ListView' so i did this : ``` ArrayList<String> test = history_share.list; names_list = (String[]) test.toArray(); ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, names_list); setListAdapter(adapter); ``` (history\_share is one of the method i created to take json data from an api . Eclipse doesn't see any error, and me neither. Can somebody help me please ?
2010/11/21
[ "https://Stackoverflow.com/questions/4240184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439058/" ]
Your problem has nothing to do with ASCII or character sets. In Java, a `char` is just a 16-bit integer. When casting ints (which are 32-bit integers) to chars, the only thing you are doing is keeping the 16 least significant bits of the int, and discarding the upper 16 bits. This is called a *narrowing conversion*. References: * <http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#20232> * <http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363>
What you search for in not a cast, it's a conversion. There is a String constructor that takes an array of byte and a charset encoding. This should help you.
4,240,184
I've got a little problem, and i don't see it. I retrieve Json data (the `JSONArray`) and i wanted to make a `List` of all the names in the `JSONArray`, something like this. ``` List list = new ArrayList<String>(); for(int i=0;i < data.length();i++){ list.add(data.getJSONObject(i).getString("names").toString()); } ``` And i wanted to take this list in an `ListView' so i did this : ``` ArrayList<String> test = history_share.list; names_list = (String[]) test.toArray(); ArrayAdapter<String> adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, names_list); setListAdapter(adapter); ``` (history\_share is one of the method i created to take json data from an api . Eclipse doesn't see any error, and me neither. Can somebody help me please ?
2010/11/21
[ "https://Stackoverflow.com/questions/4240184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439058/" ]
Your problem has nothing to do with ASCII or character sets. In Java, a `char` is just a 16-bit integer. When casting ints (which are 32-bit integers) to chars, the only thing you are doing is keeping the 16 least significant bits of the int, and discarding the upper 16 bits. This is called a *narrowing conversion*. References: * <http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#20232> * <http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#25363>
> > I'm working on a project in which I > read in a string of binary characters, > convert it into chunks, and convert > the chunks into their values in > decimal, ints, which I then cast as > chars. I then need to be able to > "expand" the resulting compressed > characters back to binary by reversing > the process. > > > You don't mention *why* you are doing that, and (to be honest) it's a little hard to follow what you're trying to describe (for one thing, I don't see why the resulting characters would be "compressed" in any way. If you just want to represent binary data as text, there are plenty of [standard ways](http://en.wikipedia.org/wiki/Binary-to-text_encoding) of accomplishing that. But it sounds like you may be after something else?
10,996,461
Spring 3 has such a nice feature as type conversion. It provides a converter SPI(`Converter<S, T>`) to be used to implement differenet conversion logic. The subclass of Converter type allow to define one-way conversion(only from S to T), so if I want a conversion also to be performed from T to S I need to define another converter class that implement `Converter<T, S>`. If I have many classes which are subject to conversion, i need to define many converters. Is there any posibility to define two-way conversion logic(from S to T and from T to S) in one converter? and how it will be used? PS. now I'm using my converters via `ConversionServiceFactoryBean` defining/injecting them in configuration file
2012/06/12
[ "https://Stackoverflow.com/questions/10996461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/491790/" ]
You are correct, if you want to use the `org.springframework.core.convert.converter.Converter` interface directly, you'll need to implement two converters, one for each direction. But spring 3 has a couple of other options: 1. If your conversion is not object-to-object but rather object-to-string (and back), then you can implement a `org.springframework.format.Formatter` instead. Formatters get registered as GenericConverters (see <http://static.springsource.org/spring-webflow/docs/2.3.x/reference/html/ch05s07.html#converter-upgrade-to-spring-3>) 2. Otherwise you could implement your own `org.springframework.core.convert.converter.GenericConverter`, which makes it easy to create TwoWayConverter implementations using reflection. ``` public abstract class AbstractTwoWayConverter<S, T> implements GenericConverter { private Class<S> classOfS; private Class<T> classOfT; protected AbstractTwoWayConverter() { Type typeA = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]; Type typeB = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]; this.classOfS = (Class) typeA; this.classOfT = (Class) typeB; } public Set<ConvertiblePair> getConvertibleTypes() { Set<ConvertiblePair> convertiblePairs = new HashSet<ConvertiblePair>(); convertiblePairs.add(new ConvertiblePair(classOfS, classOfT)); convertiblePairs.add(new ConvertiblePair(classOfT, classOfS)); return convertiblePairs; } public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (classOfS.equals(sourceType.getType())) { return this.convert((S) source); } else { return this.convertBack((T) source); } } protected abstract T convert(S source); protected abstract S convertBack(T target); } /** * converter to convert between a userId and user. * this class can be registered like so: * conversionService.addConverter(new UserIdConverter (userDao)); */ public class UserIdConverter extends AbstractTwoWayConverter<String, User> { private final UserDao userDao; @Autowired public UserIdConverter(UserDao userDao) { this.userDao = userDao; } @Override protected User convert(String userId) { return userDao.load(userId); } @Override protected String convertBack(User target) { return target.getUserId(); } } ```
Spring has just such an interface for this purpose: TwoWayConverter. see the following: <http://static.springsource.org/spring-webflow/docs/2.0.x/javadoc-api/org/springframework/binding/convert/converters/TwoWayConverter.html>
10,996,461
Spring 3 has such a nice feature as type conversion. It provides a converter SPI(`Converter<S, T>`) to be used to implement differenet conversion logic. The subclass of Converter type allow to define one-way conversion(only from S to T), so if I want a conversion also to be performed from T to S I need to define another converter class that implement `Converter<T, S>`. If I have many classes which are subject to conversion, i need to define many converters. Is there any posibility to define two-way conversion logic(from S to T and from T to S) in one converter? and how it will be used? PS. now I'm using my converters via `ConversionServiceFactoryBean` defining/injecting them in configuration file
2012/06/12
[ "https://Stackoverflow.com/questions/10996461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/491790/" ]
Spring has just such an interface for this purpose: TwoWayConverter. see the following: <http://static.springsource.org/spring-webflow/docs/2.0.x/javadoc-api/org/springframework/binding/convert/converters/TwoWayConverter.html>
You can use [Spring Formatter](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#format-Formatter-SPI) to format object of type T to String and vice versa. ``` package org.springframework.format; public interface Formatter<T> extends Printer<T>, Parser<T> { } ``` Using this interface you can achieve the same as the Barry Pitman says but with less code and this is the preferable way by the Spring documentation if you waht to format to String and vice versa. So the Barry's UserIdConverter class is going to look like this: ``` public class UserIdConverter implements Formatter<User> { private final UserDao userDao; @Autowired public UserIdConverter(UserDao userDao) { this.userDao = userDao; } @Override public User parse(String userId, Locale locale) { return userDao.load(userId); } @Override public String print(User target, Locale locale) { return target.getUserId(); } } ``` [To register this Formatter](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-conversion) you should include this in your XML config: ``` ... <mvc:annotation-driven conversion-service="conversionService"/> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" > <property name="formatters"> <set> <bean class="com.x.UserIdConverter"/> </set> </property> </bean> ... ``` ! NOTE that this class can be used only for formatting from some type T to String and vice versa. You can not format from type T to some other type T1 for example. If you have this case you should go with the Spring GenericConverter and use the Barry Pitman answer: ``` public abstract class AbstractTwoWayConverter<S, T> implements GenericConverter { private Class<S> classOfS; private Class<T> classOfT; protected AbstractTwoWayConverter() { Type typeA = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]; Type typeB = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]; this.classOfS = (Class) typeA; this.classOfT = (Class) typeB; } public Set<ConvertiblePair> getConvertibleTypes() { Set<ConvertiblePair> convertiblePairs = new HashSet<ConvertiblePair>(); convertiblePairs.add(new ConvertiblePair(classOfS, classOfT)); convertiblePairs.add(new ConvertiblePair(classOfT, classOfS)); return convertiblePairs; } public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (classOfS.equals(sourceType.getType())) { return this.convert((S) source); } else { return this.convertBack((T) source); } } protected abstract T convert(S source); protected abstract S convertBack(T target); } /** * converter to convert between a userId and user. * this class can be registered like so: * conversionService.addConverter(new UserIdConverter (userDao)); */ public class UserIdConverter extends AbstractTwoWayConverter<String, User> { private final UserDao userDao; @Autowired public UserIdConverter(UserDao userDao) { this.userDao = userDao; } @Override protected User convert(String userId) { return userDao.load(userId); } @Override protected String convertBack(User target) { return target.getUserId(); } } ``` And add to your XML config: ``` ... <mvc:annotation-driven conversion-service="conversionService"/> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean" > <property name="converters"> <set> <bean class="com.x.y.UserIdConverter"/> </set> </property> </bean> ... ```
10,996,461
Spring 3 has such a nice feature as type conversion. It provides a converter SPI(`Converter<S, T>`) to be used to implement differenet conversion logic. The subclass of Converter type allow to define one-way conversion(only from S to T), so if I want a conversion also to be performed from T to S I need to define another converter class that implement `Converter<T, S>`. If I have many classes which are subject to conversion, i need to define many converters. Is there any posibility to define two-way conversion logic(from S to T and from T to S) in one converter? and how it will be used? PS. now I'm using my converters via `ConversionServiceFactoryBean` defining/injecting them in configuration file
2012/06/12
[ "https://Stackoverflow.com/questions/10996461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/491790/" ]
You are correct, if you want to use the `org.springframework.core.convert.converter.Converter` interface directly, you'll need to implement two converters, one for each direction. But spring 3 has a couple of other options: 1. If your conversion is not object-to-object but rather object-to-string (and back), then you can implement a `org.springframework.format.Formatter` instead. Formatters get registered as GenericConverters (see <http://static.springsource.org/spring-webflow/docs/2.3.x/reference/html/ch05s07.html#converter-upgrade-to-spring-3>) 2. Otherwise you could implement your own `org.springframework.core.convert.converter.GenericConverter`, which makes it easy to create TwoWayConverter implementations using reflection. ``` public abstract class AbstractTwoWayConverter<S, T> implements GenericConverter { private Class<S> classOfS; private Class<T> classOfT; protected AbstractTwoWayConverter() { Type typeA = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]; Type typeB = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]; this.classOfS = (Class) typeA; this.classOfT = (Class) typeB; } public Set<ConvertiblePair> getConvertibleTypes() { Set<ConvertiblePair> convertiblePairs = new HashSet<ConvertiblePair>(); convertiblePairs.add(new ConvertiblePair(classOfS, classOfT)); convertiblePairs.add(new ConvertiblePair(classOfT, classOfS)); return convertiblePairs; } public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (classOfS.equals(sourceType.getType())) { return this.convert((S) source); } else { return this.convertBack((T) source); } } protected abstract T convert(S source); protected abstract S convertBack(T target); } /** * converter to convert between a userId and user. * this class can be registered like so: * conversionService.addConverter(new UserIdConverter (userDao)); */ public class UserIdConverter extends AbstractTwoWayConverter<String, User> { private final UserDao userDao; @Autowired public UserIdConverter(UserDao userDao) { this.userDao = userDao; } @Override protected User convert(String userId) { return userDao.load(userId); } @Override protected String convertBack(User target) { return target.getUserId(); } } ```
You can use [Spring Formatter](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#format-Formatter-SPI) to format object of type T to String and vice versa. ``` package org.springframework.format; public interface Formatter<T> extends Printer<T>, Parser<T> { } ``` Using this interface you can achieve the same as the Barry Pitman says but with less code and this is the preferable way by the Spring documentation if you waht to format to String and vice versa. So the Barry's UserIdConverter class is going to look like this: ``` public class UserIdConverter implements Formatter<User> { private final UserDao userDao; @Autowired public UserIdConverter(UserDao userDao) { this.userDao = userDao; } @Override public User parse(String userId, Locale locale) { return userDao.load(userId); } @Override public String print(User target, Locale locale) { return target.getUserId(); } } ``` [To register this Formatter](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-conversion) you should include this in your XML config: ``` ... <mvc:annotation-driven conversion-service="conversionService"/> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" > <property name="formatters"> <set> <bean class="com.x.UserIdConverter"/> </set> </property> </bean> ... ``` ! NOTE that this class can be used only for formatting from some type T to String and vice versa. You can not format from type T to some other type T1 for example. If you have this case you should go with the Spring GenericConverter and use the Barry Pitman answer: ``` public abstract class AbstractTwoWayConverter<S, T> implements GenericConverter { private Class<S> classOfS; private Class<T> classOfT; protected AbstractTwoWayConverter() { Type typeA = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]; Type typeB = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[1]; this.classOfS = (Class) typeA; this.classOfT = (Class) typeB; } public Set<ConvertiblePair> getConvertibleTypes() { Set<ConvertiblePair> convertiblePairs = new HashSet<ConvertiblePair>(); convertiblePairs.add(new ConvertiblePair(classOfS, classOfT)); convertiblePairs.add(new ConvertiblePair(classOfT, classOfS)); return convertiblePairs; } public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (classOfS.equals(sourceType.getType())) { return this.convert((S) source); } else { return this.convertBack((T) source); } } protected abstract T convert(S source); protected abstract S convertBack(T target); } /** * converter to convert between a userId and user. * this class can be registered like so: * conversionService.addConverter(new UserIdConverter (userDao)); */ public class UserIdConverter extends AbstractTwoWayConverter<String, User> { private final UserDao userDao; @Autowired public UserIdConverter(UserDao userDao) { this.userDao = userDao; } @Override protected User convert(String userId) { return userDao.load(userId); } @Override protected String convertBack(User target) { return target.getUserId(); } } ``` And add to your XML config: ``` ... <mvc:annotation-driven conversion-service="conversionService"/> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean" > <property name="converters"> <set> <bean class="com.x.y.UserIdConverter"/> </set> </property> </bean> ... ```
3,437,537
I was wondering if some one enters a tag like `ruby on rails` is there a way I can add a hyphen to the white spaces between the words for example `ruby-on-rails` using PHP.
2010/08/09
[ "https://Stackoverflow.com/questions/3437537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/414611/" ]
I suspect you're asking a different question, but lacking more context ... ``` $string = 'ruby on rails'; $string_with_dashes = str_replace(' ','-',$string); ``` should get you where you want to go.
It's as simple as this: ``` $tag = 'ruby on rails'; $newTag = str_replace(' ', '-', trim($tag)); ```
3,437,537
I was wondering if some one enters a tag like `ruby on rails` is there a way I can add a hyphen to the white spaces between the words for example `ruby-on-rails` using PHP.
2010/08/09
[ "https://Stackoverflow.com/questions/3437537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/414611/" ]
It's as simple as this: ``` $tag = 'ruby on rails'; $newTag = str_replace(' ', '-', trim($tag)); ```
Let me guess ``` $s = strtolower(trim($s)); $s = str_replace(" ","-",$s); $s = preg_replace('![^a-z0-9-]!',"",$s); $s = preg_replace('!\-+!',"-",$s); ```
3,437,537
I was wondering if some one enters a tag like `ruby on rails` is there a way I can add a hyphen to the white spaces between the words for example `ruby-on-rails` using PHP.
2010/08/09
[ "https://Stackoverflow.com/questions/3437537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/414611/" ]
I suspect you're asking a different question, but lacking more context ... ``` $string = 'ruby on rails'; $string_with_dashes = str_replace(' ','-',$string); ``` should get you where you want to go.
``` $str = 'ruby on rails'; // your entered tag $myTag = trim($str); // remove extra spaces from beginning and end $hyphenTag = str_replace( ' ', '-', $myTag ); // place '-' between words echo $hyphenTag; // print result ```
3,437,537
I was wondering if some one enters a tag like `ruby on rails` is there a way I can add a hyphen to the white spaces between the words for example `ruby-on-rails` using PHP.
2010/08/09
[ "https://Stackoverflow.com/questions/3437537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/414611/" ]
I suspect you're asking a different question, but lacking more context ... ``` $string = 'ruby on rails'; $string_with_dashes = str_replace(' ','-',$string); ``` should get you where you want to go.
Let me guess ``` $s = strtolower(trim($s)); $s = str_replace(" ","-",$s); $s = preg_replace('![^a-z0-9-]!',"",$s); $s = preg_replace('!\-+!',"-",$s); ```
3,437,537
I was wondering if some one enters a tag like `ruby on rails` is there a way I can add a hyphen to the white spaces between the words for example `ruby-on-rails` using PHP.
2010/08/09
[ "https://Stackoverflow.com/questions/3437537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/414611/" ]
``` $str = 'ruby on rails'; // your entered tag $myTag = trim($str); // remove extra spaces from beginning and end $hyphenTag = str_replace( ' ', '-', $myTag ); // place '-' between words echo $hyphenTag; // print result ```
Let me guess ``` $s = strtolower(trim($s)); $s = str_replace(" ","-",$s); $s = preg_replace('![^a-z0-9-]!',"",$s); $s = preg_replace('!\-+!',"-",$s); ```
46,975,851
I've a dataframe with following schema - ``` |-- ID: string (nullable = true) |-- VALUES: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- _v1: string (nullable = true) | | |-- _v2: string (nullable = true) ``` VALUES are like - ``` [["1","a"],["2","b"],["3","c"],["4","d"]] [["4","g"]] [["3","e"],["4","f"]] ``` I want to take the VALUES with the lowest integer i.e. The result df should look like - (which will be StructType now, not Array[Struct]) ``` ["1","a"] ["4","g"] ["3","e"] ``` Can someone please guide me how can I approach this problem by creating a udf ? Thanks in advance.
2017/10/27
[ "https://Stackoverflow.com/questions/46975851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6419722/" ]
You don't need a UDF for that. Just use `sort_array` and pick the first element. ``` df.show +--------------------+ | data_arr| +--------------------+ |[[4,a], [2,b], [1...| | [[1,a]]| | [[3,b], [1,v]]| +--------------------+ df.printSchema root |-- data_arr: array (nullable = false) | |-- element: struct (containsNull = false) | | |-- col1: string (nullable = false) | | |-- col2: string (nullable = false) import org.apache.spark.sql.functions.sort_array df.withColumn("first_asc", sort_array($"data_arr")(0)).show +--------------------+---------+ | data_arr|first_asc| +--------------------+---------+ |[[4,a], [2,b], [1...| [1,c]| | [[1,a]]| [1,a]| | [[3,b], [1,v]]| [1,v]| +--------------------+---------+ ```
Using the same dataframe as in the example: ``` val findSmallest = udf((rows: Seq[Row]) => { rows.map(row => (row.getAs[String](0), row.getAs[String](1))).sorted.head }) df.withColumn("SMALLEST", findSmallest($"VALUES")) ``` Will give a result like this: ``` +---+--------------------+--------+ | ID| VALUES|SMALLEST| +---+--------------------+--------+ | 1|[[1,a], [2,b], [3...| [1,2]| | 2| [[4,e]]| [4,g]| | 3| [[3,g], [4,f]]| [3,g]| +---+--------------------+--------+ ``` If you only want the final values use `select("SMALLEST)`.
1,040,563
I have this limit that I tried and failed to solve: $$ \lim\_{n \to \infty}\frac{\sqrt{n^2-n+2}-n}{\sqrt{1+\frac1n}}=\lim\_{n \to \infty}\frac{\sqrt{n^2(1-\frac1n+\frac{2}{n^2})}-n}{\sqrt{1+\frac1n}}=\lim\_{n \to \infty}\frac{n\times\sqrt{1-\frac1n+\frac{2}{n^2}}-1}{\sqrt{1+\frac1n}}=\infty\times0$$ My solution is undefined and I'm unsure how to fix it.
2014/11/27
[ "https://math.stackexchange.com/questions/1040563", "https://math.stackexchange.com", "https://math.stackexchange.com/users/189913/" ]
**Hint**: $$\sqrt{n^2-n+2}-n=\frac{(n^2-n+2)-n^2}{\sqrt{n^2-n+2}+n}\ .$$
The numerator is of the form $\infty - \infty$: that tells you that you need a better approximation. More precisely, it looks like $(n + \text{ smaller stuff}) - n$, and you need to cancel out the most significant terms. The simplest more precise approximation you can use is the differential approximation: $$f(x) = f(a) + f'(a) (x-a) + d(x)(x-a)$$ where $$ \lim\_{x \to a} d(x) = 0 $$ or maybe it's easier for you to think in terms of the mean value theorem $$ f(x) = f(a) + f'(c) (x-a) $$ for some $c \in [a,x]$. With luck, whatever is leftover can be easily handled. (or, you can just take an even better approximation, such as a degree $2$ Taylor series)
1,040,563
I have this limit that I tried and failed to solve: $$ \lim\_{n \to \infty}\frac{\sqrt{n^2-n+2}-n}{\sqrt{1+\frac1n}}=\lim\_{n \to \infty}\frac{\sqrt{n^2(1-\frac1n+\frac{2}{n^2})}-n}{\sqrt{1+\frac1n}}=\lim\_{n \to \infty}\frac{n\times\sqrt{1-\frac1n+\frac{2}{n^2}}-1}{\sqrt{1+\frac1n}}=\infty\times0$$ My solution is undefined and I'm unsure how to fix it.
2014/11/27
[ "https://math.stackexchange.com/questions/1040563", "https://math.stackexchange.com", "https://math.stackexchange.com/users/189913/" ]
**Hint**: $$\sqrt{n^2-n+2}-n=\frac{(n^2-n+2)-n^2}{\sqrt{n^2-n+2}+n}\ .$$
Let us look at the different pieces of the expression $$\frac{\sqrt{n^2-n+2}-n}{\sqrt{1+\frac1n}}=\frac{\sqrt{n^2(1-\frac1n+\frac{2}{n^2})}-n}{\sqrt{1+\frac1n}}=n\frac{\sqrt{1-(\frac1n-\frac{2}{n^2})}-1}{\sqrt{1+\frac1n}}=n \frac AB$$ and now use the fact that for small values of $x$, $$\sqrt{1+x}=1+\frac{x}{2}-\frac{x^2}{8}+\frac{x^3}{16}+O\left(x^4\right)$$ In the numerator, replace $x$ by $(-\frac1n+\frac{2}{n^2})$ and in the denominator replave $x$ by $\frac1n$. After expansion and simplification, the numerator is $$A=1-\frac{1}{2 n}+\frac{7}{8 n^2}+\frac{7}{16 n^3}+O\left(\left(\frac{1}{n}\right)^4\right)-1=-\frac{1}{2 n}+\frac{7}{8 n^2}+\frac{7}{16 n^3}+O\left(\left(\frac{1}{n}\right)^4\right)$$ and the denominator is $$B=1+\frac{1}{2 n}-\frac{1}{8 n^2}+\frac{1}{16 n^3}+O\left(\left(\frac{1}{n}\right)^4\right)$$ and, so, $$n \frac AB=n\frac{-\frac{1}{2 n}+\frac{7}{8 n^2}+\frac{7}{16 n^3}+O\left(\left(\frac{1}{n}\right)^4\right)}{1+\frac{1}{2 n}-\frac{1}{8 n^2}+\frac{1}{16 n^3}+O\left(\left(\frac{1}{n}\right)^4\right)}$$ Performing the long division, you should arrive to $$\frac{\sqrt{n^2-n+2}-n}{\sqrt{1+\frac1n}} \approx -\frac{1}{2}+\frac{9}{8 n}-\frac{3}{16 n^2}+O\left(\left(\frac{1}{n}\right)^3\right)$$ which not only shows the limit but also how it is approached.
1,040,563
I have this limit that I tried and failed to solve: $$ \lim\_{n \to \infty}\frac{\sqrt{n^2-n+2}-n}{\sqrt{1+\frac1n}}=\lim\_{n \to \infty}\frac{\sqrt{n^2(1-\frac1n+\frac{2}{n^2})}-n}{\sqrt{1+\frac1n}}=\lim\_{n \to \infty}\frac{n\times\sqrt{1-\frac1n+\frac{2}{n^2}}-1}{\sqrt{1+\frac1n}}=\infty\times0$$ My solution is undefined and I'm unsure how to fix it.
2014/11/27
[ "https://math.stackexchange.com/questions/1040563", "https://math.stackexchange.com", "https://math.stackexchange.com/users/189913/" ]
The numerator is of the form $\infty - \infty$: that tells you that you need a better approximation. More precisely, it looks like $(n + \text{ smaller stuff}) - n$, and you need to cancel out the most significant terms. The simplest more precise approximation you can use is the differential approximation: $$f(x) = f(a) + f'(a) (x-a) + d(x)(x-a)$$ where $$ \lim\_{x \to a} d(x) = 0 $$ or maybe it's easier for you to think in terms of the mean value theorem $$ f(x) = f(a) + f'(c) (x-a) $$ for some $c \in [a,x]$. With luck, whatever is leftover can be easily handled. (or, you can just take an even better approximation, such as a degree $2$ Taylor series)
Let us look at the different pieces of the expression $$\frac{\sqrt{n^2-n+2}-n}{\sqrt{1+\frac1n}}=\frac{\sqrt{n^2(1-\frac1n+\frac{2}{n^2})}-n}{\sqrt{1+\frac1n}}=n\frac{\sqrt{1-(\frac1n-\frac{2}{n^2})}-1}{\sqrt{1+\frac1n}}=n \frac AB$$ and now use the fact that for small values of $x$, $$\sqrt{1+x}=1+\frac{x}{2}-\frac{x^2}{8}+\frac{x^3}{16}+O\left(x^4\right)$$ In the numerator, replace $x$ by $(-\frac1n+\frac{2}{n^2})$ and in the denominator replave $x$ by $\frac1n$. After expansion and simplification, the numerator is $$A=1-\frac{1}{2 n}+\frac{7}{8 n^2}+\frac{7}{16 n^3}+O\left(\left(\frac{1}{n}\right)^4\right)-1=-\frac{1}{2 n}+\frac{7}{8 n^2}+\frac{7}{16 n^3}+O\left(\left(\frac{1}{n}\right)^4\right)$$ and the denominator is $$B=1+\frac{1}{2 n}-\frac{1}{8 n^2}+\frac{1}{16 n^3}+O\left(\left(\frac{1}{n}\right)^4\right)$$ and, so, $$n \frac AB=n\frac{-\frac{1}{2 n}+\frac{7}{8 n^2}+\frac{7}{16 n^3}+O\left(\left(\frac{1}{n}\right)^4\right)}{1+\frac{1}{2 n}-\frac{1}{8 n^2}+\frac{1}{16 n^3}+O\left(\left(\frac{1}{n}\right)^4\right)}$$ Performing the long division, you should arrive to $$\frac{\sqrt{n^2-n+2}-n}{\sqrt{1+\frac1n}} \approx -\frac{1}{2}+\frac{9}{8 n}-\frac{3}{16 n^2}+O\left(\left(\frac{1}{n}\right)^3\right)$$ which not only shows the limit but also how it is approached.
67,045,257
I try to create a new ASP.NET Core project that target the classic .NET Framework. The template [web](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new#web) and [webapi](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new#webapi) have the option `framework`, but this don't accept .NET Framework value like : ``` dotnet new web --name MyWebProject --framework net48 ``` > > Error: Invalid parameter(s): > > --framework net48 > > 'net48' is not a valid value for --framework (Framework). > > > How create ASP.NET Core project that targets .NET Framework from DotNet CLI? If it isn't possible, do you know a solution to do this in command line? PS : I know the Visual Studio template `ASP.NET Core empty` let select .NET Framework. I search a solution from command line, preferably with DotNet CLI.
2021/04/11
[ "https://Stackoverflow.com/questions/67045257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2703673/" ]
I used this to create ASP.NET Core empty Web App that targets 4.7.1: ```sh dotnet new web --target-framework-override net471 ``` I saw it [there](https://github.com/dotnet/templating/issues/1406). The generated project file looks like this: ```xml <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net471</TargetFramework> </PropertyGroup> <ItemGroup> <Folder Include="wwwroot\" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore" Version="2.1.7" /> </ItemGroup> </Project> ```
There is no option to set .net frameworks with a default template. You can view the framework's options by running: **dotnet new web --help**: [image](https://i.stack.imgur.com/Voada.png)
36,591,802
In my project I am using WebView that show all page but not load this page, <https://sarathi.nic.in:8443/nrportal/sarathi/Browser/Help_LLNew.html> Need to know `android WebView` support JSP?
2016/04/13
[ "https://Stackoverflow.com/questions/36591802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4590447/" ]
> > Is CTI still valid as approach? > > > I think that if the number of the categories are in the order of tenth, and not of hundredth, then yes. > > How could I assign the correct attributes set to a product? > > > You could add to each category row the table name of corresponding table of attributes, and for each attribute table, the id of the row will be the id of the corresponding product (so that you can define it as a foreign key for the products table).
In almost all situations it is "wrong" to have 55 tables with identical schema. Making it 1 table is better. But then it gets you into the nightmare called "Entity-Attribute-Value". Pick a few "attributes" that you usually need to search on. Put the rest into a JSON string in a single column. [More details](http://mysql.rjweb.org/doc.php/eav) Your schema is not quite EAV. It is an interesting variant; what does it stand for? I don't think I have seen this as an alternative to EAV. I don't yet have an opinion on whether this replaces the set of problems that EAV has with a different set of problems. Or maybe it is better. What client language will you be using? You will need to turn `category.name` into `attr_laptop` in order to `SELECT ... from attr_laptop ...` This implies dynamically creating the queries. (This is quite easy in most client languages. It is also possible, though a little clumsy, in Stored Routines.)
157,116
After booting Ubuntu 12.04 64 bit, I am not able to connect to Wifi, until I disconnect and reconnect. This has been happening for a while but I am finally getting tired of reconnecting after a boot, so Im trying to fix it. In my efforts to troubleshoot here is what I have so far: * When Wifi is not working I can not ping local network addresses * I get the same behavior logged in as a different user * Changing IPv6 settings to "ignore" has no effect, despite `IPv6 Configure Timeout` (see log below). * Here is what I get from `grep Network /var/log/syslog` when the Wifi is not working : ``` NetworkManager[1132]: <info> (wlan0): using nl80211 for WiFi device control NetworkManager[1132]: <info> (wlan0): new 802.11 WiFi device (driver: 'iwlwifi' ifindex: 3) NetworkManager[1132]: <info> (wlan0): exported as /org/freedesktop/NetworkManager/Devices/1 NetworkManager[1132]: <info> (wlan0): now managed NetworkManager[1132]: <info> (wlan0): device state change: unmanaged -> unavailable (reason 'managed') [10 20 2] NetworkManager[1132]: <info> (wlan0): bringing up device. NetworkManager[1132]: <info> (wlan0): preparing device. NetworkManager[1132]: <info> (wlan0): deactivating device (reason 'managed') [2] NetworkManager[1132]: <warn> /sys/devices/virtual/net/lxcbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> wpa_supplicant started NetworkManager[1132]: SCPlugin-Ifupdown: devices added (path: /sys/devices/virtual/net/lxcbr0, iface: lxcbr0) NetworkManager[1132]: SCPlugin-Ifupdown: device added (path: /sys/devices/virtual/net/lxcbr0, iface: lxcbr0): no ifupdown configuration found. NetworkManager[1132]: <warn> /sys/devices/virtual/net/lxcbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> (wlan0): supplicant interface state: starting -> ready NetworkManager[1132]: <info> (wlan0): device state change: unavailable -> disconnected (reason 'supplicant-available') [20 30 42] NetworkManager[1132]: <info> (wlan0): supplicant interface state: ready -> inactive NetworkManager[1132]: <warn> Trying to remove a non-existant call id. NetworkManager[1132]: SCPlugin-Ifupdown: devices added (path: /sys/devices/virtual/net/virbr0, iface: virbr0) NetworkManager[1132]: SCPlugin-Ifupdown: device added (path: /sys/devices/virtual/net/virbr0, iface: virbr0): no ifupdown configuration found. NetworkManager[1132]: <warn> /sys/devices/virtual/net/virbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> Auto-activating connection 'Skylab'. NetworkManager[1132]: <info> Activation (wlan0) starting connection 'Skylab' NetworkManager[1132]: <info> (wlan0): device state change: disconnected -> prepare (reason 'none') [30 40 0] NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) started... NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) complete. NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) starting... NetworkManager[1132]: <info> (wlan0): device state change: prepare -> config (reason 'none') [40 50 0] NetworkManager[1132]: <info> Activation (wlan0/wireless): connection 'Skylab' has security, and secrets exist. No new secrets needed. NetworkManager[1132]: <info> Config: added 'ssid' value 'Skylab' NetworkManager[1132]: <info> Config: added 'scan_ssid' value '1' NetworkManager[1132]: <info> Config: added 'key_mgmt' value 'WPA-PSK' NetworkManager[1132]: <info> Config: added 'psk' value '<omitted>' NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) complete. NetworkManager[1132]: <info> Config: set interface ap_scan to 1 NetworkManager[1132]: <info> (wlan0): supplicant interface state: inactive -> scanning NetworkManager[1132]: <info> (wlan0): supplicant interface state: scanning -> associating NetworkManager[1132]: <info> (wlan0): supplicant interface state: associating -> associated NetworkManager[1132]: <info> (wlan0): supplicant interface state: associated -> 4-way handshake NetworkManager[1132]: <info> (wlan0): supplicant interface state: 4-way handshake -> completed NetworkManager[1132]: <info> Activation (wlan0/wireless) Stage 2 of 5 (Device Configure) successful. Connected to wireless network 'Skylab'. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) scheduled. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) started... NetworkManager[1132]: <info> (wlan0): device state change: config -> ip-config (reason 'none') [50 70 0] NetworkManager[1132]: <info> Activation (wlan0) Beginning DHCPv4 transaction (timeout in 45 seconds) NetworkManager[1132]: <info> dhclient started with pid 2157 NetworkManager[1132]: <info> Activation (wlan0) Beginning IP6 addrconf. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) complete. NetworkManager[1132]: <info> (wlan0): DHCPv4 state changed nbi -> preinit NetworkManager[1132]: <info> (wlan0): DHCPv4 state changed preinit -> reboot NetworkManager[1132]: <info> address 192.168.2.9 NetworkManager[1132]: <info> prefix 24 (255.255.255.0) NetworkManager[1132]: <info> gateway 192.168.2.1 NetworkManager[1132]: <info> nameserver '192.168.2.1' NetworkManager[1132]: <info> domain name 'Belkin' NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Configure Commit) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) started... NetworkManager[1132]: <info> DNS: starting dnsmasq... NetworkManager[1132]: <info> (wlan0): writing resolv.conf to /sbin/resolvconf NetworkManager[1132]: <info> (wlan0): device state change: ip-config -> activated (reason 'none') [70 100 0] NetworkManager[1132]: <info> Policy set 'Skylab' (wlan0) as default for IPv4 routing and DNS. NetworkManager[1132]: <info> Activation (wlan0) successful, device activated. NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) complete. NetworkManager[1132]: <info> (wlan0): IP6 addrconf timed out or failed. NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) started... NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) complete. ``` The rest is only present when Wifi is not working: ``` NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Configure Commit) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) started... NetworkManager[1132]: <info> DNS: starting dnsmasq... NetworkManager[1132]: <info> (wlan0): writing resolv.conf to /sbin/resolvconf NetworkManager[1132]: <info> (wlan0): device state change: ip-config -> activated (reason 'none') [70 100 0] NetworkManager[1132]: <info> Policy set 'Skylab' (wlan0) as default for IPv4 routing and DNS. NetworkManager[1132]: <info> Activation (wlan0) successful, device activated. NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) complete. ``` * Here is the info on my wireless card from lspci -v : ``` 08:00.0 Network controller: Intel Corporation Centrino Wireless-N 1000 Subsystem: Intel Corporation Centrino Wireless-N 1000 BGN Flags: bus master, fast devsel, latency 0, IRQ 44 Memory at d1d00000 (64-bit, non-prefetchable) [size=8K] Capabilities: [c8] Power Management version 3 Capabilities: [d0] MSI: Enable+ Count=1/1 Maskable- 64bit+ Capabilities: [e0] Express Endpoint, MSI 00 Capabilities: [100] Advanced Error Reporting Capabilities: [140] Device Serial Number 74-e5-0b-ff-ff-7d-3a-38 Kernel driver in use: iwlwifi Kernel modules: iwlwifi ``` Not sure where to go with this, any help is appreciated, including tips on troubleshooting. Thanks in advance.
2012/06/28
[ "https://askubuntu.com/questions/157116", "https://askubuntu.com", "https://askubuntu.com/users/54187/" ]
set default shell in vim ``` :set shell=/bin/bash ``` Thanks to [Ubuntu Forum](http://forum.ubuntu.org.cn/viewtopic.php?f=48&t=379312)
have you installed zsh? Install it from here [zsh](http://apt.ubuntu.com/p/zsh) [![Install zsh](https://hostmar.co/software-small)](http://apt.ubuntu.com/p/zsh)
157,116
After booting Ubuntu 12.04 64 bit, I am not able to connect to Wifi, until I disconnect and reconnect. This has been happening for a while but I am finally getting tired of reconnecting after a boot, so Im trying to fix it. In my efforts to troubleshoot here is what I have so far: * When Wifi is not working I can not ping local network addresses * I get the same behavior logged in as a different user * Changing IPv6 settings to "ignore" has no effect, despite `IPv6 Configure Timeout` (see log below). * Here is what I get from `grep Network /var/log/syslog` when the Wifi is not working : ``` NetworkManager[1132]: <info> (wlan0): using nl80211 for WiFi device control NetworkManager[1132]: <info> (wlan0): new 802.11 WiFi device (driver: 'iwlwifi' ifindex: 3) NetworkManager[1132]: <info> (wlan0): exported as /org/freedesktop/NetworkManager/Devices/1 NetworkManager[1132]: <info> (wlan0): now managed NetworkManager[1132]: <info> (wlan0): device state change: unmanaged -> unavailable (reason 'managed') [10 20 2] NetworkManager[1132]: <info> (wlan0): bringing up device. NetworkManager[1132]: <info> (wlan0): preparing device. NetworkManager[1132]: <info> (wlan0): deactivating device (reason 'managed') [2] NetworkManager[1132]: <warn> /sys/devices/virtual/net/lxcbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> wpa_supplicant started NetworkManager[1132]: SCPlugin-Ifupdown: devices added (path: /sys/devices/virtual/net/lxcbr0, iface: lxcbr0) NetworkManager[1132]: SCPlugin-Ifupdown: device added (path: /sys/devices/virtual/net/lxcbr0, iface: lxcbr0): no ifupdown configuration found. NetworkManager[1132]: <warn> /sys/devices/virtual/net/lxcbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> (wlan0): supplicant interface state: starting -> ready NetworkManager[1132]: <info> (wlan0): device state change: unavailable -> disconnected (reason 'supplicant-available') [20 30 42] NetworkManager[1132]: <info> (wlan0): supplicant interface state: ready -> inactive NetworkManager[1132]: <warn> Trying to remove a non-existant call id. NetworkManager[1132]: SCPlugin-Ifupdown: devices added (path: /sys/devices/virtual/net/virbr0, iface: virbr0) NetworkManager[1132]: SCPlugin-Ifupdown: device added (path: /sys/devices/virtual/net/virbr0, iface: virbr0): no ifupdown configuration found. NetworkManager[1132]: <warn> /sys/devices/virtual/net/virbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> Auto-activating connection 'Skylab'. NetworkManager[1132]: <info> Activation (wlan0) starting connection 'Skylab' NetworkManager[1132]: <info> (wlan0): device state change: disconnected -> prepare (reason 'none') [30 40 0] NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) started... NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) complete. NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) starting... NetworkManager[1132]: <info> (wlan0): device state change: prepare -> config (reason 'none') [40 50 0] NetworkManager[1132]: <info> Activation (wlan0/wireless): connection 'Skylab' has security, and secrets exist. No new secrets needed. NetworkManager[1132]: <info> Config: added 'ssid' value 'Skylab' NetworkManager[1132]: <info> Config: added 'scan_ssid' value '1' NetworkManager[1132]: <info> Config: added 'key_mgmt' value 'WPA-PSK' NetworkManager[1132]: <info> Config: added 'psk' value '<omitted>' NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) complete. NetworkManager[1132]: <info> Config: set interface ap_scan to 1 NetworkManager[1132]: <info> (wlan0): supplicant interface state: inactive -> scanning NetworkManager[1132]: <info> (wlan0): supplicant interface state: scanning -> associating NetworkManager[1132]: <info> (wlan0): supplicant interface state: associating -> associated NetworkManager[1132]: <info> (wlan0): supplicant interface state: associated -> 4-way handshake NetworkManager[1132]: <info> (wlan0): supplicant interface state: 4-way handshake -> completed NetworkManager[1132]: <info> Activation (wlan0/wireless) Stage 2 of 5 (Device Configure) successful. Connected to wireless network 'Skylab'. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) scheduled. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) started... NetworkManager[1132]: <info> (wlan0): device state change: config -> ip-config (reason 'none') [50 70 0] NetworkManager[1132]: <info> Activation (wlan0) Beginning DHCPv4 transaction (timeout in 45 seconds) NetworkManager[1132]: <info> dhclient started with pid 2157 NetworkManager[1132]: <info> Activation (wlan0) Beginning IP6 addrconf. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) complete. NetworkManager[1132]: <info> (wlan0): DHCPv4 state changed nbi -> preinit NetworkManager[1132]: <info> (wlan0): DHCPv4 state changed preinit -> reboot NetworkManager[1132]: <info> address 192.168.2.9 NetworkManager[1132]: <info> prefix 24 (255.255.255.0) NetworkManager[1132]: <info> gateway 192.168.2.1 NetworkManager[1132]: <info> nameserver '192.168.2.1' NetworkManager[1132]: <info> domain name 'Belkin' NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Configure Commit) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) started... NetworkManager[1132]: <info> DNS: starting dnsmasq... NetworkManager[1132]: <info> (wlan0): writing resolv.conf to /sbin/resolvconf NetworkManager[1132]: <info> (wlan0): device state change: ip-config -> activated (reason 'none') [70 100 0] NetworkManager[1132]: <info> Policy set 'Skylab' (wlan0) as default for IPv4 routing and DNS. NetworkManager[1132]: <info> Activation (wlan0) successful, device activated. NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) complete. NetworkManager[1132]: <info> (wlan0): IP6 addrconf timed out or failed. NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) started... NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) complete. ``` The rest is only present when Wifi is not working: ``` NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Configure Commit) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) started... NetworkManager[1132]: <info> DNS: starting dnsmasq... NetworkManager[1132]: <info> (wlan0): writing resolv.conf to /sbin/resolvconf NetworkManager[1132]: <info> (wlan0): device state change: ip-config -> activated (reason 'none') [70 100 0] NetworkManager[1132]: <info> Policy set 'Skylab' (wlan0) as default for IPv4 routing and DNS. NetworkManager[1132]: <info> Activation (wlan0) successful, device activated. NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) complete. ``` * Here is the info on my wireless card from lspci -v : ``` 08:00.0 Network controller: Intel Corporation Centrino Wireless-N 1000 Subsystem: Intel Corporation Centrino Wireless-N 1000 BGN Flags: bus master, fast devsel, latency 0, IRQ 44 Memory at d1d00000 (64-bit, non-prefetchable) [size=8K] Capabilities: [c8] Power Management version 3 Capabilities: [d0] MSI: Enable+ Count=1/1 Maskable- 64bit+ Capabilities: [e0] Express Endpoint, MSI 00 Capabilities: [100] Advanced Error Reporting Capabilities: [140] Device Serial Number 74-e5-0b-ff-ff-7d-3a-38 Kernel driver in use: iwlwifi Kernel modules: iwlwifi ``` Not sure where to go with this, any help is appreciated, including tips on troubleshooting. Thanks in advance.
2012/06/28
[ "https://askubuntu.com/questions/157116", "https://askubuntu.com", "https://askubuntu.com/users/54187/" ]
have you installed zsh? Install it from here [zsh](http://apt.ubuntu.com/p/zsh) [![Install zsh](https://hostmar.co/software-small)](http://apt.ubuntu.com/p/zsh)
How do you propose using Zsh if you don't have it installed?! You still do have to install it with: `sudo apt-get install zsh` even if you don't make it your default shell, which is what I suspect you meant.
157,116
After booting Ubuntu 12.04 64 bit, I am not able to connect to Wifi, until I disconnect and reconnect. This has been happening for a while but I am finally getting tired of reconnecting after a boot, so Im trying to fix it. In my efforts to troubleshoot here is what I have so far: * When Wifi is not working I can not ping local network addresses * I get the same behavior logged in as a different user * Changing IPv6 settings to "ignore" has no effect, despite `IPv6 Configure Timeout` (see log below). * Here is what I get from `grep Network /var/log/syslog` when the Wifi is not working : ``` NetworkManager[1132]: <info> (wlan0): using nl80211 for WiFi device control NetworkManager[1132]: <info> (wlan0): new 802.11 WiFi device (driver: 'iwlwifi' ifindex: 3) NetworkManager[1132]: <info> (wlan0): exported as /org/freedesktop/NetworkManager/Devices/1 NetworkManager[1132]: <info> (wlan0): now managed NetworkManager[1132]: <info> (wlan0): device state change: unmanaged -> unavailable (reason 'managed') [10 20 2] NetworkManager[1132]: <info> (wlan0): bringing up device. NetworkManager[1132]: <info> (wlan0): preparing device. NetworkManager[1132]: <info> (wlan0): deactivating device (reason 'managed') [2] NetworkManager[1132]: <warn> /sys/devices/virtual/net/lxcbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> wpa_supplicant started NetworkManager[1132]: SCPlugin-Ifupdown: devices added (path: /sys/devices/virtual/net/lxcbr0, iface: lxcbr0) NetworkManager[1132]: SCPlugin-Ifupdown: device added (path: /sys/devices/virtual/net/lxcbr0, iface: lxcbr0): no ifupdown configuration found. NetworkManager[1132]: <warn> /sys/devices/virtual/net/lxcbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> (wlan0): supplicant interface state: starting -> ready NetworkManager[1132]: <info> (wlan0): device state change: unavailable -> disconnected (reason 'supplicant-available') [20 30 42] NetworkManager[1132]: <info> (wlan0): supplicant interface state: ready -> inactive NetworkManager[1132]: <warn> Trying to remove a non-existant call id. NetworkManager[1132]: SCPlugin-Ifupdown: devices added (path: /sys/devices/virtual/net/virbr0, iface: virbr0) NetworkManager[1132]: SCPlugin-Ifupdown: device added (path: /sys/devices/virtual/net/virbr0, iface: virbr0): no ifupdown configuration found. NetworkManager[1132]: <warn> /sys/devices/virtual/net/virbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> Auto-activating connection 'Skylab'. NetworkManager[1132]: <info> Activation (wlan0) starting connection 'Skylab' NetworkManager[1132]: <info> (wlan0): device state change: disconnected -> prepare (reason 'none') [30 40 0] NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) started... NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) complete. NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) starting... NetworkManager[1132]: <info> (wlan0): device state change: prepare -> config (reason 'none') [40 50 0] NetworkManager[1132]: <info> Activation (wlan0/wireless): connection 'Skylab' has security, and secrets exist. No new secrets needed. NetworkManager[1132]: <info> Config: added 'ssid' value 'Skylab' NetworkManager[1132]: <info> Config: added 'scan_ssid' value '1' NetworkManager[1132]: <info> Config: added 'key_mgmt' value 'WPA-PSK' NetworkManager[1132]: <info> Config: added 'psk' value '<omitted>' NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) complete. NetworkManager[1132]: <info> Config: set interface ap_scan to 1 NetworkManager[1132]: <info> (wlan0): supplicant interface state: inactive -> scanning NetworkManager[1132]: <info> (wlan0): supplicant interface state: scanning -> associating NetworkManager[1132]: <info> (wlan0): supplicant interface state: associating -> associated NetworkManager[1132]: <info> (wlan0): supplicant interface state: associated -> 4-way handshake NetworkManager[1132]: <info> (wlan0): supplicant interface state: 4-way handshake -> completed NetworkManager[1132]: <info> Activation (wlan0/wireless) Stage 2 of 5 (Device Configure) successful. Connected to wireless network 'Skylab'. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) scheduled. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) started... NetworkManager[1132]: <info> (wlan0): device state change: config -> ip-config (reason 'none') [50 70 0] NetworkManager[1132]: <info> Activation (wlan0) Beginning DHCPv4 transaction (timeout in 45 seconds) NetworkManager[1132]: <info> dhclient started with pid 2157 NetworkManager[1132]: <info> Activation (wlan0) Beginning IP6 addrconf. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) complete. NetworkManager[1132]: <info> (wlan0): DHCPv4 state changed nbi -> preinit NetworkManager[1132]: <info> (wlan0): DHCPv4 state changed preinit -> reboot NetworkManager[1132]: <info> address 192.168.2.9 NetworkManager[1132]: <info> prefix 24 (255.255.255.0) NetworkManager[1132]: <info> gateway 192.168.2.1 NetworkManager[1132]: <info> nameserver '192.168.2.1' NetworkManager[1132]: <info> domain name 'Belkin' NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Configure Commit) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) started... NetworkManager[1132]: <info> DNS: starting dnsmasq... NetworkManager[1132]: <info> (wlan0): writing resolv.conf to /sbin/resolvconf NetworkManager[1132]: <info> (wlan0): device state change: ip-config -> activated (reason 'none') [70 100 0] NetworkManager[1132]: <info> Policy set 'Skylab' (wlan0) as default for IPv4 routing and DNS. NetworkManager[1132]: <info> Activation (wlan0) successful, device activated. NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) complete. NetworkManager[1132]: <info> (wlan0): IP6 addrconf timed out or failed. NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) started... NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) complete. ``` The rest is only present when Wifi is not working: ``` NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Configure Commit) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) started... NetworkManager[1132]: <info> DNS: starting dnsmasq... NetworkManager[1132]: <info> (wlan0): writing resolv.conf to /sbin/resolvconf NetworkManager[1132]: <info> (wlan0): device state change: ip-config -> activated (reason 'none') [70 100 0] NetworkManager[1132]: <info> Policy set 'Skylab' (wlan0) as default for IPv4 routing and DNS. NetworkManager[1132]: <info> Activation (wlan0) successful, device activated. NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) complete. ``` * Here is the info on my wireless card from lspci -v : ``` 08:00.0 Network controller: Intel Corporation Centrino Wireless-N 1000 Subsystem: Intel Corporation Centrino Wireless-N 1000 BGN Flags: bus master, fast devsel, latency 0, IRQ 44 Memory at d1d00000 (64-bit, non-prefetchable) [size=8K] Capabilities: [c8] Power Management version 3 Capabilities: [d0] MSI: Enable+ Count=1/1 Maskable- 64bit+ Capabilities: [e0] Express Endpoint, MSI 00 Capabilities: [100] Advanced Error Reporting Capabilities: [140] Device Serial Number 74-e5-0b-ff-ff-7d-3a-38 Kernel driver in use: iwlwifi Kernel modules: iwlwifi ``` Not sure where to go with this, any help is appreciated, including tips on troubleshooting. Thanks in advance.
2012/06/28
[ "https://askubuntu.com/questions/157116", "https://askubuntu.com", "https://askubuntu.com/users/54187/" ]
set default shell in vim ``` :set shell=/bin/bash ``` Thanks to [Ubuntu Forum](http://forum.ubuntu.org.cn/viewtopic.php?f=48&t=379312)
To install zsh type the following in a terminal ``` sudo apt-get update sudo apt-get install zsh ```
157,116
After booting Ubuntu 12.04 64 bit, I am not able to connect to Wifi, until I disconnect and reconnect. This has been happening for a while but I am finally getting tired of reconnecting after a boot, so Im trying to fix it. In my efforts to troubleshoot here is what I have so far: * When Wifi is not working I can not ping local network addresses * I get the same behavior logged in as a different user * Changing IPv6 settings to "ignore" has no effect, despite `IPv6 Configure Timeout` (see log below). * Here is what I get from `grep Network /var/log/syslog` when the Wifi is not working : ``` NetworkManager[1132]: <info> (wlan0): using nl80211 for WiFi device control NetworkManager[1132]: <info> (wlan0): new 802.11 WiFi device (driver: 'iwlwifi' ifindex: 3) NetworkManager[1132]: <info> (wlan0): exported as /org/freedesktop/NetworkManager/Devices/1 NetworkManager[1132]: <info> (wlan0): now managed NetworkManager[1132]: <info> (wlan0): device state change: unmanaged -> unavailable (reason 'managed') [10 20 2] NetworkManager[1132]: <info> (wlan0): bringing up device. NetworkManager[1132]: <info> (wlan0): preparing device. NetworkManager[1132]: <info> (wlan0): deactivating device (reason 'managed') [2] NetworkManager[1132]: <warn> /sys/devices/virtual/net/lxcbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> wpa_supplicant started NetworkManager[1132]: SCPlugin-Ifupdown: devices added (path: /sys/devices/virtual/net/lxcbr0, iface: lxcbr0) NetworkManager[1132]: SCPlugin-Ifupdown: device added (path: /sys/devices/virtual/net/lxcbr0, iface: lxcbr0): no ifupdown configuration found. NetworkManager[1132]: <warn> /sys/devices/virtual/net/lxcbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> (wlan0): supplicant interface state: starting -> ready NetworkManager[1132]: <info> (wlan0): device state change: unavailable -> disconnected (reason 'supplicant-available') [20 30 42] NetworkManager[1132]: <info> (wlan0): supplicant interface state: ready -> inactive NetworkManager[1132]: <warn> Trying to remove a non-existant call id. NetworkManager[1132]: SCPlugin-Ifupdown: devices added (path: /sys/devices/virtual/net/virbr0, iface: virbr0) NetworkManager[1132]: SCPlugin-Ifupdown: device added (path: /sys/devices/virtual/net/virbr0, iface: virbr0): no ifupdown configuration found. NetworkManager[1132]: <warn> /sys/devices/virtual/net/virbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> Auto-activating connection 'Skylab'. NetworkManager[1132]: <info> Activation (wlan0) starting connection 'Skylab' NetworkManager[1132]: <info> (wlan0): device state change: disconnected -> prepare (reason 'none') [30 40 0] NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) started... NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) complete. NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) starting... NetworkManager[1132]: <info> (wlan0): device state change: prepare -> config (reason 'none') [40 50 0] NetworkManager[1132]: <info> Activation (wlan0/wireless): connection 'Skylab' has security, and secrets exist. No new secrets needed. NetworkManager[1132]: <info> Config: added 'ssid' value 'Skylab' NetworkManager[1132]: <info> Config: added 'scan_ssid' value '1' NetworkManager[1132]: <info> Config: added 'key_mgmt' value 'WPA-PSK' NetworkManager[1132]: <info> Config: added 'psk' value '<omitted>' NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) complete. NetworkManager[1132]: <info> Config: set interface ap_scan to 1 NetworkManager[1132]: <info> (wlan0): supplicant interface state: inactive -> scanning NetworkManager[1132]: <info> (wlan0): supplicant interface state: scanning -> associating NetworkManager[1132]: <info> (wlan0): supplicant interface state: associating -> associated NetworkManager[1132]: <info> (wlan0): supplicant interface state: associated -> 4-way handshake NetworkManager[1132]: <info> (wlan0): supplicant interface state: 4-way handshake -> completed NetworkManager[1132]: <info> Activation (wlan0/wireless) Stage 2 of 5 (Device Configure) successful. Connected to wireless network 'Skylab'. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) scheduled. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) started... NetworkManager[1132]: <info> (wlan0): device state change: config -> ip-config (reason 'none') [50 70 0] NetworkManager[1132]: <info> Activation (wlan0) Beginning DHCPv4 transaction (timeout in 45 seconds) NetworkManager[1132]: <info> dhclient started with pid 2157 NetworkManager[1132]: <info> Activation (wlan0) Beginning IP6 addrconf. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) complete. NetworkManager[1132]: <info> (wlan0): DHCPv4 state changed nbi -> preinit NetworkManager[1132]: <info> (wlan0): DHCPv4 state changed preinit -> reboot NetworkManager[1132]: <info> address 192.168.2.9 NetworkManager[1132]: <info> prefix 24 (255.255.255.0) NetworkManager[1132]: <info> gateway 192.168.2.1 NetworkManager[1132]: <info> nameserver '192.168.2.1' NetworkManager[1132]: <info> domain name 'Belkin' NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Configure Commit) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) started... NetworkManager[1132]: <info> DNS: starting dnsmasq... NetworkManager[1132]: <info> (wlan0): writing resolv.conf to /sbin/resolvconf NetworkManager[1132]: <info> (wlan0): device state change: ip-config -> activated (reason 'none') [70 100 0] NetworkManager[1132]: <info> Policy set 'Skylab' (wlan0) as default for IPv4 routing and DNS. NetworkManager[1132]: <info> Activation (wlan0) successful, device activated. NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) complete. NetworkManager[1132]: <info> (wlan0): IP6 addrconf timed out or failed. NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) started... NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) complete. ``` The rest is only present when Wifi is not working: ``` NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Configure Commit) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) started... NetworkManager[1132]: <info> DNS: starting dnsmasq... NetworkManager[1132]: <info> (wlan0): writing resolv.conf to /sbin/resolvconf NetworkManager[1132]: <info> (wlan0): device state change: ip-config -> activated (reason 'none') [70 100 0] NetworkManager[1132]: <info> Policy set 'Skylab' (wlan0) as default for IPv4 routing and DNS. NetworkManager[1132]: <info> Activation (wlan0) successful, device activated. NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) complete. ``` * Here is the info on my wireless card from lspci -v : ``` 08:00.0 Network controller: Intel Corporation Centrino Wireless-N 1000 Subsystem: Intel Corporation Centrino Wireless-N 1000 BGN Flags: bus master, fast devsel, latency 0, IRQ 44 Memory at d1d00000 (64-bit, non-prefetchable) [size=8K] Capabilities: [c8] Power Management version 3 Capabilities: [d0] MSI: Enable+ Count=1/1 Maskable- 64bit+ Capabilities: [e0] Express Endpoint, MSI 00 Capabilities: [100] Advanced Error Reporting Capabilities: [140] Device Serial Number 74-e5-0b-ff-ff-7d-3a-38 Kernel driver in use: iwlwifi Kernel modules: iwlwifi ``` Not sure where to go with this, any help is appreciated, including tips on troubleshooting. Thanks in advance.
2012/06/28
[ "https://askubuntu.com/questions/157116", "https://askubuntu.com", "https://askubuntu.com/users/54187/" ]
To install zsh type the following in a terminal ``` sudo apt-get update sudo apt-get install zsh ```
How do you propose using Zsh if you don't have it installed?! You still do have to install it with: `sudo apt-get install zsh` even if you don't make it your default shell, which is what I suspect you meant.
157,116
After booting Ubuntu 12.04 64 bit, I am not able to connect to Wifi, until I disconnect and reconnect. This has been happening for a while but I am finally getting tired of reconnecting after a boot, so Im trying to fix it. In my efforts to troubleshoot here is what I have so far: * When Wifi is not working I can not ping local network addresses * I get the same behavior logged in as a different user * Changing IPv6 settings to "ignore" has no effect, despite `IPv6 Configure Timeout` (see log below). * Here is what I get from `grep Network /var/log/syslog` when the Wifi is not working : ``` NetworkManager[1132]: <info> (wlan0): using nl80211 for WiFi device control NetworkManager[1132]: <info> (wlan0): new 802.11 WiFi device (driver: 'iwlwifi' ifindex: 3) NetworkManager[1132]: <info> (wlan0): exported as /org/freedesktop/NetworkManager/Devices/1 NetworkManager[1132]: <info> (wlan0): now managed NetworkManager[1132]: <info> (wlan0): device state change: unmanaged -> unavailable (reason 'managed') [10 20 2] NetworkManager[1132]: <info> (wlan0): bringing up device. NetworkManager[1132]: <info> (wlan0): preparing device. NetworkManager[1132]: <info> (wlan0): deactivating device (reason 'managed') [2] NetworkManager[1132]: <warn> /sys/devices/virtual/net/lxcbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> wpa_supplicant started NetworkManager[1132]: SCPlugin-Ifupdown: devices added (path: /sys/devices/virtual/net/lxcbr0, iface: lxcbr0) NetworkManager[1132]: SCPlugin-Ifupdown: device added (path: /sys/devices/virtual/net/lxcbr0, iface: lxcbr0): no ifupdown configuration found. NetworkManager[1132]: <warn> /sys/devices/virtual/net/lxcbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> (wlan0): supplicant interface state: starting -> ready NetworkManager[1132]: <info> (wlan0): device state change: unavailable -> disconnected (reason 'supplicant-available') [20 30 42] NetworkManager[1132]: <info> (wlan0): supplicant interface state: ready -> inactive NetworkManager[1132]: <warn> Trying to remove a non-existant call id. NetworkManager[1132]: SCPlugin-Ifupdown: devices added (path: /sys/devices/virtual/net/virbr0, iface: virbr0) NetworkManager[1132]: SCPlugin-Ifupdown: device added (path: /sys/devices/virtual/net/virbr0, iface: virbr0): no ifupdown configuration found. NetworkManager[1132]: <warn> /sys/devices/virtual/net/virbr0: couldn't determine device driver; ignoring... NetworkManager[1132]: <info> Auto-activating connection 'Skylab'. NetworkManager[1132]: <info> Activation (wlan0) starting connection 'Skylab' NetworkManager[1132]: <info> (wlan0): device state change: disconnected -> prepare (reason 'none') [30 40 0] NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) started... NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 1 of 5 (Device Prepare) complete. NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) starting... NetworkManager[1132]: <info> (wlan0): device state change: prepare -> config (reason 'none') [40 50 0] NetworkManager[1132]: <info> Activation (wlan0/wireless): connection 'Skylab' has security, and secrets exist. No new secrets needed. NetworkManager[1132]: <info> Config: added 'ssid' value 'Skylab' NetworkManager[1132]: <info> Config: added 'scan_ssid' value '1' NetworkManager[1132]: <info> Config: added 'key_mgmt' value 'WPA-PSK' NetworkManager[1132]: <info> Config: added 'psk' value '<omitted>' NetworkManager[1132]: <info> Activation (wlan0) Stage 2 of 5 (Device Configure) complete. NetworkManager[1132]: <info> Config: set interface ap_scan to 1 NetworkManager[1132]: <info> (wlan0): supplicant interface state: inactive -> scanning NetworkManager[1132]: <info> (wlan0): supplicant interface state: scanning -> associating NetworkManager[1132]: <info> (wlan0): supplicant interface state: associating -> associated NetworkManager[1132]: <info> (wlan0): supplicant interface state: associated -> 4-way handshake NetworkManager[1132]: <info> (wlan0): supplicant interface state: 4-way handshake -> completed NetworkManager[1132]: <info> Activation (wlan0/wireless) Stage 2 of 5 (Device Configure) successful. Connected to wireless network 'Skylab'. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) scheduled. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) started... NetworkManager[1132]: <info> (wlan0): device state change: config -> ip-config (reason 'none') [50 70 0] NetworkManager[1132]: <info> Activation (wlan0) Beginning DHCPv4 transaction (timeout in 45 seconds) NetworkManager[1132]: <info> dhclient started with pid 2157 NetworkManager[1132]: <info> Activation (wlan0) Beginning IP6 addrconf. NetworkManager[1132]: <info> Activation (wlan0) Stage 3 of 5 (IP Configure Start) complete. NetworkManager[1132]: <info> (wlan0): DHCPv4 state changed nbi -> preinit NetworkManager[1132]: <info> (wlan0): DHCPv4 state changed preinit -> reboot NetworkManager[1132]: <info> address 192.168.2.9 NetworkManager[1132]: <info> prefix 24 (255.255.255.0) NetworkManager[1132]: <info> gateway 192.168.2.1 NetworkManager[1132]: <info> nameserver '192.168.2.1' NetworkManager[1132]: <info> domain name 'Belkin' NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Configure Commit) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) started... NetworkManager[1132]: <info> DNS: starting dnsmasq... NetworkManager[1132]: <info> (wlan0): writing resolv.conf to /sbin/resolvconf NetworkManager[1132]: <info> (wlan0): device state change: ip-config -> activated (reason 'none') [70 100 0] NetworkManager[1132]: <info> Policy set 'Skylab' (wlan0) as default for IPv4 routing and DNS. NetworkManager[1132]: <info> Activation (wlan0) successful, device activated. NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) complete. NetworkManager[1132]: <info> (wlan0): IP6 addrconf timed out or failed. NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) started... NetworkManager[1132]: <info> Activation (wlan0) Stage 4 of 5 (IPv6 Configure Timeout) complete. ``` The rest is only present when Wifi is not working: ``` NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Configure Commit) scheduled... NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) started... NetworkManager[1132]: <info> DNS: starting dnsmasq... NetworkManager[1132]: <info> (wlan0): writing resolv.conf to /sbin/resolvconf NetworkManager[1132]: <info> (wlan0): device state change: ip-config -> activated (reason 'none') [70 100 0] NetworkManager[1132]: <info> Policy set 'Skylab' (wlan0) as default for IPv4 routing and DNS. NetworkManager[1132]: <info> Activation (wlan0) successful, device activated. NetworkManager[1132]: <info> Activation (wlan0) Stage 5 of 5 (IPv4 Commit) complete. ``` * Here is the info on my wireless card from lspci -v : ``` 08:00.0 Network controller: Intel Corporation Centrino Wireless-N 1000 Subsystem: Intel Corporation Centrino Wireless-N 1000 BGN Flags: bus master, fast devsel, latency 0, IRQ 44 Memory at d1d00000 (64-bit, non-prefetchable) [size=8K] Capabilities: [c8] Power Management version 3 Capabilities: [d0] MSI: Enable+ Count=1/1 Maskable- 64bit+ Capabilities: [e0] Express Endpoint, MSI 00 Capabilities: [100] Advanced Error Reporting Capabilities: [140] Device Serial Number 74-e5-0b-ff-ff-7d-3a-38 Kernel driver in use: iwlwifi Kernel modules: iwlwifi ``` Not sure where to go with this, any help is appreciated, including tips on troubleshooting. Thanks in advance.
2012/06/28
[ "https://askubuntu.com/questions/157116", "https://askubuntu.com", "https://askubuntu.com/users/54187/" ]
set default shell in vim ``` :set shell=/bin/bash ``` Thanks to [Ubuntu Forum](http://forum.ubuntu.org.cn/viewtopic.php?f=48&t=379312)
How do you propose using Zsh if you don't have it installed?! You still do have to install it with: `sudo apt-get install zsh` even if you don't make it your default shell, which is what I suspect you meant.
3,535,412
I've been using ComponentSoftware's [CS-RCS Basic](http://www.componentsoftware.com/products/docman/index.htm) for many years now to manage my various single-developer projects. It's worked very well for me, but now I want to migrate to a modern revision-control system, and after studying my options I decided on Mercurial. The problem is that I've always used a central repository for CS-RCS, and I'd now like to use individual Mercurial repositories for individual projects, keeping the history from my RCS repository. After some in-depth Googling I concluded that the only way to do this is to convert my RCS repository to individual CVS repositories, then convert those to Mercurial. These two sites were probably the most helpful: * [Converting a directory from RCS to Mercurial](http://utcc.utoronto.ca/~cks/space/blog/sysadmin/RCStoMercurial) * [Convert Extension for Mercurial](https://www.mercurial-scm.org/wiki/ConvertExtension#Converting_to_Mercurial) In keeping with Jeff Atwood's idea of asking and answering my own question, I'm going to answer this for anyone else stuck in this situation, and in case I have to find it again later. As you'll see, though I did find a solution, it's clunky and has at least one significant problem. If anyone else has any better method I'd certainly like to hear about it.
2010/08/20
[ "https://Stackoverflow.com/questions/3535412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264721/" ]
Here's the method I came up with, warts and all. It's a bit 'cargo culty', since I basically know nothing about CVS and not much (yet) about Mercurial: I have a Windows XP virtual machine that I can take snapshots of, so I did that and then installed CVSNT and the Windows command-line version of Mercurial (I use TortoiseHg on my main machine). I did this in a VM so I could easily get rid of CVSNT, Mercurial, and anything else I had to create while doing this one-time migration. Yeah, I probably didn't have to do this, but the VM was already available and I've already got enough odd bits of apps left over from install/uninstall cycles over the years. :-) As far as I could tell, CVSNT was the only program available that could easily set up a CVS server on a Windows machine. It seems that this was free at one time but the owner's [current site](http://www.march-hare.com/cvspro/) now asks for money. That's not a bad thing, but I really couldn't justify spending money just to do a one-time conversion. I did eventually track down an older version of CVSNT with a Google search and installed that without problems. Here are the notes I took while learning how to make this conversion work: The Long Version ---------------- Copy the source-code folder you need from the main computer's drive to the VM's drive. Copy the various ",v" files from the C:\RCS folder structure to this same source-code folder on the VM. Just copy the ,v files from the corresponding folder in C:\RCS. Open a Command Prompt box on the VM and type the following: ``` path %PATH%;C:\Program Files\cvsnt mkdir \cvs-repo [or clean the folder out if it already exists] cvs -d \cvs-repo init [A DIR of \cvs-repo should show a CVSROOT folder in there.] ``` Make a copy of your source code folder in `\cvs-repo`. `\cvs-repo` should now just have two folders: CVSROOT and your new folder. Copy in the appropriate ",v" files as well. ``` mkdir \cvs-checkout [or clean that folder out if it already exists] cd \cvs-checkout cvs -d \cvs-repo co name_of_your_source_code_folder ``` A DIR of "\cvs-checkout\name\_of\_your\_source\_code\_folder" should show all of your source code files, which are now checked out of CVS. If you haven't already done so, download Mercurial from <https://www.mercurial-scm.org/> and install it. Open a copy of Notepad and drag the file "C:\Program Files\Mercurial\hgrc.d\Mercurial.rc" into it. Under "[extensions]", remove the semicolon at the start of the line "`;convert =`". Save the file to "C:\Documents and Settings\user\_name\Mercurial.ini" Back at the VM command line: ``` path %PATH%;C:\Program Files\Mercurial mkdir \my-repo.hg [or clean that folder out if it already exists] hg convert --datesort \cvs-checkout\source_code_folder_name \my-repo.hg cd \my-repo.hg [A DIR of \my-repo.hg should show a new ".hg" folder.] hg update [A DIR should now show the ".hg" folder and all the checked-out files.] ``` Copy the ".hg" folder from \my-repo to the source code folder on your main computer's hard drive. The destination folder will now show up in TortoiseHg with all of the appropriate change history, but all files marked as Changed (icon overlay of an exclamation mark in a red circle). This is because the new Mercurial repository thinks the files were checked in with Unix line endings (0x0A) instead of Windows (0x0D,0x0A). This seems to happen in the "hg convert" process, and I haven't found any way around it. The Short Version ----------------- Once everything's set up in the VM, here's what to do: * Delete everything in \cvs-repo, \cvs-checkout, and \my-repo.hg. * At the command line, `cvs -d \cvs-repo init`. * Back on your main machine, copy the source-code folder into your Virtual Machine's shared folder (that's how you do it in VirtualBox; other VM software might let you just drag-and-drop the folder into the VM). * Copy the appropriate ",v" files into the source-code folder in the Virtual Machine shared folder. * Back in the VM, move the source-code folder to \cvs-repo. * `cd \cvs-checkout` * `cvs -d \cvs-repo co name_of_your_source_code_folder` * `hg convert --datesort \cvs-checkout\name_of_your_source_code_folder \my-repo.hg` * `cd \my-repo.hg` * `hg update` * Copy the .hg folder from \my-repo to the L: drive on the VM (L is the mapped drive letter of my VM shared folder). * Move that folder from the Virtual Machine transfer folder to the final source-code folder on the host computer. Handy Batch File ---------------- Once I got this working, I set up this batch file on the VM to automate the process as much as possible: ``` @echo off rem Converts source code under RCS control to a Mercurial repository. rem This batch takes one argument: the name of the source-code folder (in quotes if necessary). rem rem This is for a VirtualBox VM that already has CVSNT and Mercurial installed, and has a Shared Folder mapped to drive L. @echo On the host, copy the source-code folder into the Virtual Machine Transfer folder. Copy the appropriate ",v" files into the source-code folder in the Virtual Machine Transfer folder. pause @echo on cd \ rmdir /S/Q \cvs-repo mkdir \cvs-repo rmdir /S/Q \cvs-checkout mkdir \cvs-checkout rmdir /S/Q \my-repo.hg mkdir \my-repo.hg cvs -d \cvs-repo init xcopy L:\%1 \cvs-repo\%1 /E/I cd \cvs-checkout cvs -d \cvs-repo co %1 hg convert --datesort %1 \my-repo.hg cd \my-repo.hg hg update xcopy \my-repo.hg\.hg L:\.hg /E/I ``` Conclusion ---------- So, this all worked but left me with files that had the wrong line endings. Looking at [this question](https://stackoverflow.com/questions/2754281/cvs-to-mercurial-conversion-end-of-line-problem), I see I'm not the only one with this problem. I can live with this, but I'd still like to fix it if anyone knows of a solution.
If Mercurial has fast-import/fast-export support, and if your multi-file repositories do not use branches, you can probably try using my rcs-fast-export tool (available @ <http://git.oblomov.eu/rcs-fast-export> ). Although I've only used it to export from RCS to git so far, I am not aware of any git-specific fast-export commands being used so it might work.
12,042,129
How do you pass an httpcontext.current object to a web service and use that object in the service, I get an error saying that it is expecting a string - surly this must be possible? ``` Imports System.Web Imports System.Web.Services Imports System.Web.Services.Protocols <WebService(Namespace:="http://tempuri.org/")> _ <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Public Class WebService Inherits System.Web.Services.WebService <WebMethod()> _ Public Sub doThis(ByVal HC As HttpContext) 'do something End Sub End Class Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim s As test2.WebService = New test2.WebService s.doThis(HttpContext.Current) End Sub ```
2012/08/20
[ "https://Stackoverflow.com/questions/12042129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1477816/" ]
The HttpContext is not serilazible, so it can't be sent as a string. HttpContext is an complex object with other complex properties, so it would be rather big if you would serialize it (which means it would be alot slower sending the data). I believe it's better to encapsulate the information you need in a custom class instead and send that to the service. That is, create a class with simple types that can be serialized (string, int, double, etc.) and fill it with the information you need.
You cannot pass an `HttpContext` `ByVal`. `ByVal` means by value, which means that the `HttpContext`'s value needs to be copied in order to be passed to your method. Since it's a [complex] object, you can't do that. Instead you need to pass it `ByRef`, which means pass a reference to the object to your method and work off of that reference.
21,666,196
So I am working on a problem set in a MIT Free Course. The problem is to create a word game and I have downloaded a list of 84,000 words that will serve as a dictionary. The file is located in my desktop and I have tried entering the specific location in PyCharm but for some reason it can not find the file. I have tried storing the file in different places and forms but it can not locate it. Here is the error traceback: ``` File "/Users/ksorenson/PycharmProjects/Word Game/ps5cheat_sheet.py", line 241, in <module> word_list = load_words() File "/Users/ksorenson/PycharmProjects/Word Game/ps5cheat_sheet.py", line 33, in load_words inFile = open(WORDLIST_FILENAME, 'r', 0) FileNotFoundError: [Errno 2] No such file or directory: 'words.txt' ``` Here is some of the code: ``` # Problem Set 5: 6.00 Word Game # Name: # Collaborators: # Time: # import random import string VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } # ----------------------------------- # Helper code # (you don't need to understand this helper code) WORDLIST_FILENAME = "words.txt" *************HERE IS THE FILE THAT I CANNOT LOCATE********* def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # wordlist: list of strings wordlist = [] for line in inFile: wordlist.append(line.strip().lower()) print(" ", len(wordlist), "words loaded.") return wordlist ```
2014/02/09
[ "https://Stackoverflow.com/questions/21666196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2423505/" ]
Try this instead: ``` import os WORDLIST_FILENAME = os.path.expanduser("~/Desktop/words.txt") ```
I agree with Cfreak. It's trying to open `words.txt`, which it interprets to be a relative path, and, because there are not directory specifications in the path, the script expects to be in the current working directory (often the same one as the script). Either modify the script the way wim suggests or move `words.txt` into the same directory as the script.
13,639,219
This is for a computer science assignment using Python, does anybody know where I would begin to create an algorithm to create a square or box that rolls across the screen? And I do indeed mean roll, not slide. It does not necessarily have to be using python, I just need a general idea as to how the coordinates would work and a general algorithm.
2012/11/30
[ "https://Stackoverflow.com/questions/13639219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1859071/" ]
If a unit square starts out with one side resting on the x-axis, and the lower right corner at (xs, 0), then after a quarter turn clockwise it will again have one side resting on the x-axis, and the lower right corner now at (xs+1, 0). Before it turns, label the lower left corner a; the upper left, b; and the upper right, c. Corners a and c move along arcs of a unit circle as the square turns. Corner b moves with radius d = sqrt(2). This leads to the following method: Step angle t from 0 to pi/2 (ie 90°), letting • xa = xs - cos t • ya = sin t • xb = xs - d\*cos(t+pi/4) • yb = d\*sin(t+pi/4) • xc = xs + sin t • yc = cos t At each time step, erase the old square by drawing background-colored lines, compute new (xa,ya,xb,yb,xc,yc) from equations, draw new square with lines from (xs,0) to (xa,yb) to (xc,yc) to (xd,yd) to (xs,0), and then delay appropriate amount. Each time t gets up to pi/2, set t back to 0 and add 1 to xs. Note, instead of erasing the whole square and then drawing the new, one might try erasing one old line and drawing one new line in turn for the four sides.
I would approach this by first thinking about the box pivoting on one corner from one side to the next, and then combine those steps in a sequence. That is, if you have a box like ``` A ---- B | | C ---- D ``` Rolling to the right, then first the whole thing pivots about D until you have ``` C - A | | | | | | | | D - B ``` That step is a straightforward clockwise rotation of all the points around the origin D by an angle theta between 0 and 90 degrees. I'll leave figuring that out to the asker and/or wikipedia ;). Once you have figured that step out, the next part of the rotation is the same, except now you are rotating around B instead of D. This brings you to ``` D ---- C | | B ---- A ``` So at a high level, I would compute the locations of the corners at time t by first figuring out the most recent "flat" configuration, then figure out which corner is in the front, then rotating the points about the front corner based on how much time has elapsed since the square was in that flat state. As a bonus hint, divmod is a nice function in python for breaking the timestamp into a pair of (which step am I on, how far am I into that step).
13,639,219
This is for a computer science assignment using Python, does anybody know where I would begin to create an algorithm to create a square or box that rolls across the screen? And I do indeed mean roll, not slide. It does not necessarily have to be using python, I just need a general idea as to how the coordinates would work and a general algorithm.
2012/11/30
[ "https://Stackoverflow.com/questions/13639219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1859071/" ]
If a unit square starts out with one side resting on the x-axis, and the lower right corner at (xs, 0), then after a quarter turn clockwise it will again have one side resting on the x-axis, and the lower right corner now at (xs+1, 0). Before it turns, label the lower left corner a; the upper left, b; and the upper right, c. Corners a and c move along arcs of a unit circle as the square turns. Corner b moves with radius d = sqrt(2). This leads to the following method: Step angle t from 0 to pi/2 (ie 90°), letting • xa = xs - cos t • ya = sin t • xb = xs - d\*cos(t+pi/4) • yb = d\*sin(t+pi/4) • xc = xs + sin t • yc = cos t At each time step, erase the old square by drawing background-colored lines, compute new (xa,ya,xb,yb,xc,yc) from equations, draw new square with lines from (xs,0) to (xa,yb) to (xc,yc) to (xd,yd) to (xs,0), and then delay appropriate amount. Each time t gets up to pi/2, set t back to 0 and add 1 to xs. Note, instead of erasing the whole square and then drawing the new, one might try erasing one old line and drawing one new line in turn for the four sides.
You could alternatively completely break the spirit of the assignment by using pybox2d, pymunk or another physics engine to do all the calculations for you. Then you could have lots of boxes rolling around and bouncing off each other :D
13,361,335
So I have several .jsp files: one of the files has the head tag and has the title of the page: ``` <%@ page pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>${param.title}</title> </head> ``` The other files include the first one and pass to it a param using jsp:param: ``` <%@ page pageEncoding="UTF-8"%> <jsp:include page="consoleheader.jsp"> <jsp:param name="title" value="Título"/> </jsp:include> <body> ... </body> </html> ``` Any non-ASCII characters that I pass using jsp:param are getting garbled when I do this (the í in Título for instance). Everywhere else it works fine. All jsp files are encoded using UTF-8. I have not set any charset configurations on my JVM. Anyone knows how to fix this without setting the JVM encoding by hand?
2012/11/13
[ "https://Stackoverflow.com/questions/13361335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3485/" ]
Using JSTL worked here. It's more verbose though: "head": ``` <%@ page pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>${title}</title> </head> ``` "body": ``` <%@ page pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:set var="title" scope="request" value="Título"/> <jsp:include page="consoleheader.jsp"> <body> ... </body> </html> ```
Could the param value be dinamic? . If not, replace "í" for `&#237;`
13,361,335
So I have several .jsp files: one of the files has the head tag and has the title of the page: ``` <%@ page pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>${param.title}</title> </head> ``` The other files include the first one and pass to it a param using jsp:param: ``` <%@ page pageEncoding="UTF-8"%> <jsp:include page="consoleheader.jsp"> <jsp:param name="title" value="Título"/> </jsp:include> <body> ... </body> </html> ``` Any non-ASCII characters that I pass using jsp:param are getting garbled when I do this (the í in Título for instance). Everywhere else it works fine. All jsp files are encoded using UTF-8. I have not set any charset configurations on my JVM. Anyone knows how to fix this without setting the JVM encoding by hand?
2012/11/13
[ "https://Stackoverflow.com/questions/13361335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3485/" ]
I had a similar problem with jsp params and hacked it in the following way: main.jsp: ``` <%@ page pageEncoding="UTF-8"%> <html> <head/> <body> <jsp:include page="other.jsp"> <%-- í = &iacute; --%> <jsp:param name="title" value="T&iacute;tulo"/> </jsp:include> </body> </html> ``` other.jsp ``` <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page pageEncoding="UTF-8"%> <h1><c:out value="${param.title}" escapeXml="false"/></h1> ``` --- I know it is not the best solution, but it worked for me. --- ### Edit I found an [other solution](https://groups.google.com/forum/#!topic/omaha-java-users-group/SBVal1wEj98) that is could work for you too: > > Adding the setCharacterEncoding line below before the jsp:include does the trick. > `<% request.setCharacterEncoding("utf-8"); %>` > > >
Could the param value be dinamic? . If not, replace "í" for `&#237;`
41,209,578
Is there a concise way in Swift of creating an array by applying a binary operation on the elements of two other arrays? For example: ``` let a = [1, 2, 3] let b = [4, 5, 6] let c = (0..<3).map{a[$0]+b[$0]} // c = [5, 7, 9] ```
2016/12/18
[ "https://Stackoverflow.com/questions/41209578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125997/" ]
If you use [zip](https://developer.apple.com/reference/swift/1541125-zip) to combine the elements, you can refer to `+` with just `+`: ``` let a = [1, 2, 3] let b = [4, 5, 6] let c = zip(a, b).map(+) // [5, 7, 9] ```
**Update:** You can use `indices` like this: ``` for index in a.indices{ sum.append(a[index] + b[index]) } print(sum)// [5, 7, 9] ``` (Thanks to Alexander's comment this is better, because we don't have to deal with the `element` itself and we just deal with the `index`) **Old answer:** you can enumerate to get the index: ``` var sum = [Int]() for (index, _) in a.enumerated(){ sum.append(a[index] + b[index]) } print(sum)// [5, 7, 9] ```
21,479,100
I have Bootstrap datepicker with default format **mm/dd/yyyy**, and I have select where I can change format **from mm/dd/yyyy** to **dd/mm/yyyy** and reverse. On select change I want to my datepicker change format. I tried ``` find('#options-date_format').on('change', function(){ $("#picker").datepicker({format: formatDate}) }); ``` but It's not working, and I can't find way of doing this. Also tried to remove / destroy datepicker but I got javascript error.
2014/01/31
[ "https://Stackoverflow.com/questions/21479100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548374/" ]
I think the below approach is working, 1, Whenever changing the format, de-attach and then re-attach back to the element. ``` $("#dp3").datepicker(); // initialization $('select').on('change', function () { var d = $('select option:selected').text(); if (d == 2) { $("#dp3").datepicker('remove'); //detach $("#dp3").datepicker({ //re attach format: "dd/mm/yyyy" }) } else { $("#dp3").datepicker('remove'); //detach $("#dp3").datepicker({ //re attach format: "mm/dd/yyyy" }) } }); ``` [**JSFiddle**](http://jsfiddle.net/praveen_jegan/YY5rh/1/) ----------------------------------------------------------
Ok I resolve this extending bootstra-datepicker.js ``` setFormat: function(format) { this.format = DPGlobal.parseFormat(format); } ``` And call that function ``` find('#options-date_format').on('change', function(){ $("#picker").datepicker('setFormat', newFormat); }); ```
21,479,100
I have Bootstrap datepicker with default format **mm/dd/yyyy**, and I have select where I can change format **from mm/dd/yyyy** to **dd/mm/yyyy** and reverse. On select change I want to my datepicker change format. I tried ``` find('#options-date_format').on('change', function(){ $("#picker").datepicker({format: formatDate}) }); ``` but It's not working, and I can't find way of doing this. Also tried to remove / destroy datepicker but I got javascript error.
2014/01/31
[ "https://Stackoverflow.com/questions/21479100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548374/" ]
I think the below approach is working, 1, Whenever changing the format, de-attach and then re-attach back to the element. ``` $("#dp3").datepicker(); // initialization $('select').on('change', function () { var d = $('select option:selected').text(); if (d == 2) { $("#dp3").datepicker('remove'); //detach $("#dp3").datepicker({ //re attach format: "dd/mm/yyyy" }) } else { $("#dp3").datepicker('remove'); //detach $("#dp3").datepicker({ //re attach format: "mm/dd/yyyy" }) } }); ``` [**JSFiddle**](http://jsfiddle.net/praveen_jegan/YY5rh/1/) ----------------------------------------------------------
When you have many date pickers, the you can use a class selector and reset all of them, and initialize using the class. Code sample below. In the example, all the input elements will have the class `date-picker` ``` function resetDatePickers(){ $('.date-picker').each(function(index){ $(this).datepicker('remove'); }); $('.date-picker').datepicker({ format: "dd/mm/yyyy", startView: 2, orientation: "top auto" }); } resetDatePickers(); ```
21,479,100
I have Bootstrap datepicker with default format **mm/dd/yyyy**, and I have select where I can change format **from mm/dd/yyyy** to **dd/mm/yyyy** and reverse. On select change I want to my datepicker change format. I tried ``` find('#options-date_format').on('change', function(){ $("#picker").datepicker({format: formatDate}) }); ``` but It's not working, and I can't find way of doing this. Also tried to remove / destroy datepicker but I got javascript error.
2014/01/31
[ "https://Stackoverflow.com/questions/21479100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548374/" ]
Ok I resolve this extending bootstra-datepicker.js ``` setFormat: function(format) { this.format = DPGlobal.parseFormat(format); } ``` And call that function ``` find('#options-date_format').on('change', function(){ $("#picker").datepicker('setFormat', newFormat); }); ```
When you have many date pickers, the you can use a class selector and reset all of them, and initialize using the class. Code sample below. In the example, all the input elements will have the class `date-picker` ``` function resetDatePickers(){ $('.date-picker').each(function(index){ $(this).datepicker('remove'); }); $('.date-picker').datepicker({ format: "dd/mm/yyyy", startView: 2, orientation: "top auto" }); } resetDatePickers(); ```
5,939
Prior to the events of the season 3 finale of *Fringe*, the Broyles from Over There (i.e. Col. Broyles) died. After the events of that finale, a character was wiped from history. Col. Broyles was killed and used as the mass sent Over Here to replace the Olivia from Over There (i.e. Fauxlivia) when they brought her back Over There. It seemed like his death was a key part of the events of the escalating conflict between the two Earths. But in S4E2, *One Night in October*, we see Col. Broyles alive and well. We also know Fauxlivia still went on her mission Over Here, thanks to Walter saying as much. So is Col. Broyles still alive, and if so how? We know that the now-missing character's disappearance altered the history we've seen over the past 3 seasons, how did the events around Broyles' death change in this new history?
2011/10/01
[ "https://scifi.stackexchange.com/questions/5939", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
This really bothers me because either way, Fauxlivia would have had to be replaced mass wise with something from the other side. There's no way Olivia could have escaped without col. Broyles help, so the events don't seem to have changed even with / without the missing character.
We know that 'Over There' they are far more advanced technologically and medically. In the first episode of season 4 we see Walter reanimate a dead bird which briefly flies around the lab. Perhaps they sent Colonel Broyles back soon enough so they were able to save him?
5,939
Prior to the events of the season 3 finale of *Fringe*, the Broyles from Over There (i.e. Col. Broyles) died. After the events of that finale, a character was wiped from history. Col. Broyles was killed and used as the mass sent Over Here to replace the Olivia from Over There (i.e. Fauxlivia) when they brought her back Over There. It seemed like his death was a key part of the events of the escalating conflict between the two Earths. But in S4E2, *One Night in October*, we see Col. Broyles alive and well. We also know Fauxlivia still went on her mission Over Here, thanks to Walter saying as much. So is Col. Broyles still alive, and if so how? We know that the now-missing character's disappearance altered the history we've seen over the past 3 seasons, how did the events around Broyles' death change in this new history?
2011/10/01
[ "https://scifi.stackexchange.com/questions/5939", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
Maybe, just maybe, Walternate replaced Broyles on his side with a shape shifter because I seem to recall his team thought he just disappeared As I watch the episode, SE4 The Consultant, the idea of shape shifters is viable ONLY if they take on the emotions of the 'bodies' they inhabit. Remember, in last week's episode, the shape shifter who took on (and killed) multiple victims, STILL carried the picture of his 'real' son. Nothing suggested he had any emotional attachment to the loves ones of the victims he inhabited. With that in mind, it is not consistant for Col. Broyles body to have been occupied by a shape shifter because Col. Broyles is acting as a mole to save his son. A shape shifter would have no love for that child. For these reasons, the reappearance of Col. Broyles, 'back from the dead,' remains unexplained.
We know that 'Over There' they are far more advanced technologically and medically. In the first episode of season 4 we see Walter reanimate a dead bird which briefly flies around the lab. Perhaps they sent Colonel Broyles back soon enough so they were able to save him?
5,939
Prior to the events of the season 3 finale of *Fringe*, the Broyles from Over There (i.e. Col. Broyles) died. After the events of that finale, a character was wiped from history. Col. Broyles was killed and used as the mass sent Over Here to replace the Olivia from Over There (i.e. Fauxlivia) when they brought her back Over There. It seemed like his death was a key part of the events of the escalating conflict between the two Earths. But in S4E2, *One Night in October*, we see Col. Broyles alive and well. We also know Fauxlivia still went on her mission Over Here, thanks to Walter saying as much. So is Col. Broyles still alive, and if so how? We know that the now-missing character's disappearance altered the history we've seen over the past 3 seasons, how did the events around Broyles' death change in this new history?
2011/10/01
[ "https://scifi.stackexchange.com/questions/5939", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
It's because he did not die in the alternate time line created at the end of the season 3. He is not alone, in "[Subject 9](http://fringepedia.net/wiki/Subject_9)" (episode 4 of season 4), they find Cameron James, a subject of Cortexiphan trials: > > Cameron and Olivia talk about the other test subjects from Jacksonville. Has she heard about any of the others? Olivia has not. He is the only other test subject she knows anything about. The same goes for him - no contact with the others. > > > But, in [Over There, Part 1](http://fringepedia.net/wiki/Over_There,_Part_1) (the first part of the season 2 finale), Olivia needed the help of 3 others Cortexiphan test subjects ([James Heath](http://fringepedia.net/wiki/James_Heath), [Sally Clark](http://fringepedia.net/wiki/Sally_Clark) and [Nick Lane](http://fringepedia.net/wiki/Nick_Lane)) to switch universes. Since she never met them in the alternated time line, they did not die and Olivia never switched universe by these means. Others clues in the early season 4 indicate that she has not mastered her abilities (yet). When Col. Broyles died in the season 3 episode [Entrada](http://fringepedia.net/wiki/Entrada), his body was used as a counterweight for Fauxlivia's recuperation, but the Olivia from Over Here returned by her own means. This cannot be the way she returned in the new alternate timeline, since everything indicates she never switched universes by herself since she quit the Cortexiphan trials. She probably returned to Over Here as Fauxlivia's counterweight, as it was originally planned. Anyway, this make the treason of Col. Broyles unnecessary, as it was to help Olivia to reach the isolation tank in the Harvard lab so she could concentrate and switch universes.
In S4E2, Walter mentioned that *Olivia* was kidnapped to the other side, not Peter being kidnapped and her following. I think that with that significant change, she probably did not interact with Broyles. Walternate would have kept her captive and experimented on her instead of trying to brainwash her into believing she was Fauxlivia. Also, I don't think this is something the writers planned too far in advance. I looked back to S3E22, the final episode of season 3, at the very end, when the two worlds come together. We see both Olivia's and both Walters, but we only see the Broyles from 'our' side. If the writers had been planning this back then, I think the other Broyles would have 'magically' appeared at that time.
5,939
Prior to the events of the season 3 finale of *Fringe*, the Broyles from Over There (i.e. Col. Broyles) died. After the events of that finale, a character was wiped from history. Col. Broyles was killed and used as the mass sent Over Here to replace the Olivia from Over There (i.e. Fauxlivia) when they brought her back Over There. It seemed like his death was a key part of the events of the escalating conflict between the two Earths. But in S4E2, *One Night in October*, we see Col. Broyles alive and well. We also know Fauxlivia still went on her mission Over Here, thanks to Walter saying as much. So is Col. Broyles still alive, and if so how? We know that the now-missing character's disappearance altered the history we've seen over the past 3 seasons, how did the events around Broyles' death change in this new history?
2011/10/01
[ "https://scifi.stackexchange.com/questions/5939", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
It's because he did not die in the alternate time line created at the end of the season 3. He is not alone, in "[Subject 9](http://fringepedia.net/wiki/Subject_9)" (episode 4 of season 4), they find Cameron James, a subject of Cortexiphan trials: > > Cameron and Olivia talk about the other test subjects from Jacksonville. Has she heard about any of the others? Olivia has not. He is the only other test subject she knows anything about. The same goes for him - no contact with the others. > > > But, in [Over There, Part 1](http://fringepedia.net/wiki/Over_There,_Part_1) (the first part of the season 2 finale), Olivia needed the help of 3 others Cortexiphan test subjects ([James Heath](http://fringepedia.net/wiki/James_Heath), [Sally Clark](http://fringepedia.net/wiki/Sally_Clark) and [Nick Lane](http://fringepedia.net/wiki/Nick_Lane)) to switch universes. Since she never met them in the alternated time line, they did not die and Olivia never switched universe by these means. Others clues in the early season 4 indicate that she has not mastered her abilities (yet). When Col. Broyles died in the season 3 episode [Entrada](http://fringepedia.net/wiki/Entrada), his body was used as a counterweight for Fauxlivia's recuperation, but the Olivia from Over Here returned by her own means. This cannot be the way she returned in the new alternate timeline, since everything indicates she never switched universes by herself since she quit the Cortexiphan trials. She probably returned to Over Here as Fauxlivia's counterweight, as it was originally planned. Anyway, this make the treason of Col. Broyles unnecessary, as it was to help Olivia to reach the isolation tank in the Harvard lab so she could concentrate and switch universes.
Go to <http://tvovermind.zap2it.com/fox/fringe/review-fringe-season-4-puts-strange-world/92224> There is an article that states the existance of Broyles might be due to Peter not existing - the timeline may have changed, also the writers may have an explanation in an episode to come - either way people have noticed so there will have to be a good reason for his "resurrection".
5,939
Prior to the events of the season 3 finale of *Fringe*, the Broyles from Over There (i.e. Col. Broyles) died. After the events of that finale, a character was wiped from history. Col. Broyles was killed and used as the mass sent Over Here to replace the Olivia from Over There (i.e. Fauxlivia) when they brought her back Over There. It seemed like his death was a key part of the events of the escalating conflict between the two Earths. But in S4E2, *One Night in October*, we see Col. Broyles alive and well. We also know Fauxlivia still went on her mission Over Here, thanks to Walter saying as much. So is Col. Broyles still alive, and if so how? We know that the now-missing character's disappearance altered the history we've seen over the past 3 seasons, how did the events around Broyles' death change in this new history?
2011/10/01
[ "https://scifi.stackexchange.com/questions/5939", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
In S4E2, Walter mentioned that *Olivia* was kidnapped to the other side, not Peter being kidnapped and her following. I think that with that significant change, she probably did not interact with Broyles. Walternate would have kept her captive and experimented on her instead of trying to brainwash her into believing she was Fauxlivia. Also, I don't think this is something the writers planned too far in advance. I looked back to S3E22, the final episode of season 3, at the very end, when the two worlds come together. We see both Olivia's and both Walters, but we only see the Broyles from 'our' side. If the writers had been planning this back then, I think the other Broyles would have 'magically' appeared at that time.
How about this: what if Fauxlivia stayed Over Here until the bridge was created, thereby not needed an exit and not using Broyles as a mass-replacement? This plot hole is really bothering me.
5,939
Prior to the events of the season 3 finale of *Fringe*, the Broyles from Over There (i.e. Col. Broyles) died. After the events of that finale, a character was wiped from history. Col. Broyles was killed and used as the mass sent Over Here to replace the Olivia from Over There (i.e. Fauxlivia) when they brought her back Over There. It seemed like his death was a key part of the events of the escalating conflict between the two Earths. But in S4E2, *One Night in October*, we see Col. Broyles alive and well. We also know Fauxlivia still went on her mission Over Here, thanks to Walter saying as much. So is Col. Broyles still alive, and if so how? We know that the now-missing character's disappearance altered the history we've seen over the past 3 seasons, how did the events around Broyles' death change in this new history?
2011/10/01
[ "https://scifi.stackexchange.com/questions/5939", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
It's because he did not die in the alternate time line created at the end of the season 3. He is not alone, in "[Subject 9](http://fringepedia.net/wiki/Subject_9)" (episode 4 of season 4), they find Cameron James, a subject of Cortexiphan trials: > > Cameron and Olivia talk about the other test subjects from Jacksonville. Has she heard about any of the others? Olivia has not. He is the only other test subject she knows anything about. The same goes for him - no contact with the others. > > > But, in [Over There, Part 1](http://fringepedia.net/wiki/Over_There,_Part_1) (the first part of the season 2 finale), Olivia needed the help of 3 others Cortexiphan test subjects ([James Heath](http://fringepedia.net/wiki/James_Heath), [Sally Clark](http://fringepedia.net/wiki/Sally_Clark) and [Nick Lane](http://fringepedia.net/wiki/Nick_Lane)) to switch universes. Since she never met them in the alternated time line, they did not die and Olivia never switched universe by these means. Others clues in the early season 4 indicate that she has not mastered her abilities (yet). When Col. Broyles died in the season 3 episode [Entrada](http://fringepedia.net/wiki/Entrada), his body was used as a counterweight for Fauxlivia's recuperation, but the Olivia from Over Here returned by her own means. This cannot be the way she returned in the new alternate timeline, since everything indicates she never switched universes by herself since she quit the Cortexiphan trials. She probably returned to Over Here as Fauxlivia's counterweight, as it was originally planned. Anyway, this make the treason of Col. Broyles unnecessary, as it was to help Olivia to reach the isolation tank in the Harvard lab so she could concentrate and switch universes.
Well since Olivia was kidnapped I'm assuming they sent Olivia back at the same time as brining fauxlivia back which means they didn't have to replace her mass with the other broyles which means the other broyles didn't help her escape and never did anything wrong to be killed
5,939
Prior to the events of the season 3 finale of *Fringe*, the Broyles from Over There (i.e. Col. Broyles) died. After the events of that finale, a character was wiped from history. Col. Broyles was killed and used as the mass sent Over Here to replace the Olivia from Over There (i.e. Fauxlivia) when they brought her back Over There. It seemed like his death was a key part of the events of the escalating conflict between the two Earths. But in S4E2, *One Night in October*, we see Col. Broyles alive and well. We also know Fauxlivia still went on her mission Over Here, thanks to Walter saying as much. So is Col. Broyles still alive, and if so how? We know that the now-missing character's disappearance altered the history we've seen over the past 3 seasons, how did the events around Broyles' death change in this new history?
2011/10/01
[ "https://scifi.stackexchange.com/questions/5939", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
In S4E2, Walter mentioned that *Olivia* was kidnapped to the other side, not Peter being kidnapped and her following. I think that with that significant change, she probably did not interact with Broyles. Walternate would have kept her captive and experimented on her instead of trying to brainwash her into believing she was Fauxlivia. Also, I don't think this is something the writers planned too far in advance. I looked back to S3E22, the final episode of season 3, at the very end, when the two worlds come together. We see both Olivia's and both Walters, but we only see the Broyles from 'our' side. If the writers had been planning this back then, I think the other Broyles would have 'magically' appeared at that time.
Maybe, just maybe, Walternate replaced Broyles on his side with a shape shifter because I seem to recall his team thought he just disappeared As I watch the episode, SE4 The Consultant, the idea of shape shifters is viable ONLY if they take on the emotions of the 'bodies' they inhabit. Remember, in last week's episode, the shape shifter who took on (and killed) multiple victims, STILL carried the picture of his 'real' son. Nothing suggested he had any emotional attachment to the loves ones of the victims he inhabited. With that in mind, it is not consistant for Col. Broyles body to have been occupied by a shape shifter because Col. Broyles is acting as a mole to save his son. A shape shifter would have no love for that child. For these reasons, the reappearance of Col. Broyles, 'back from the dead,' remains unexplained.
5,939
Prior to the events of the season 3 finale of *Fringe*, the Broyles from Over There (i.e. Col. Broyles) died. After the events of that finale, a character was wiped from history. Col. Broyles was killed and used as the mass sent Over Here to replace the Olivia from Over There (i.e. Fauxlivia) when they brought her back Over There. It seemed like his death was a key part of the events of the escalating conflict between the two Earths. But in S4E2, *One Night in October*, we see Col. Broyles alive and well. We also know Fauxlivia still went on her mission Over Here, thanks to Walter saying as much. So is Col. Broyles still alive, and if so how? We know that the now-missing character's disappearance altered the history we've seen over the past 3 seasons, how did the events around Broyles' death change in this new history?
2011/10/01
[ "https://scifi.stackexchange.com/questions/5939", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
It's because he did not die in the alternate time line created at the end of the season 3. He is not alone, in "[Subject 9](http://fringepedia.net/wiki/Subject_9)" (episode 4 of season 4), they find Cameron James, a subject of Cortexiphan trials: > > Cameron and Olivia talk about the other test subjects from Jacksonville. Has she heard about any of the others? Olivia has not. He is the only other test subject she knows anything about. The same goes for him - no contact with the others. > > > But, in [Over There, Part 1](http://fringepedia.net/wiki/Over_There,_Part_1) (the first part of the season 2 finale), Olivia needed the help of 3 others Cortexiphan test subjects ([James Heath](http://fringepedia.net/wiki/James_Heath), [Sally Clark](http://fringepedia.net/wiki/Sally_Clark) and [Nick Lane](http://fringepedia.net/wiki/Nick_Lane)) to switch universes. Since she never met them in the alternated time line, they did not die and Olivia never switched universe by these means. Others clues in the early season 4 indicate that she has not mastered her abilities (yet). When Col. Broyles died in the season 3 episode [Entrada](http://fringepedia.net/wiki/Entrada), his body was used as a counterweight for Fauxlivia's recuperation, but the Olivia from Over Here returned by her own means. This cannot be the way she returned in the new alternate timeline, since everything indicates she never switched universes by herself since she quit the Cortexiphan trials. She probably returned to Over Here as Fauxlivia's counterweight, as it was originally planned. Anyway, this make the treason of Col. Broyles unnecessary, as it was to help Olivia to reach the isolation tank in the Harvard lab so she could concentrate and switch universes.
We know that 'Over There' they are far more advanced technologically and medically. In the first episode of season 4 we see Walter reanimate a dead bird which briefly flies around the lab. Perhaps they sent Colonel Broyles back soon enough so they were able to save him?
5,939
Prior to the events of the season 3 finale of *Fringe*, the Broyles from Over There (i.e. Col. Broyles) died. After the events of that finale, a character was wiped from history. Col. Broyles was killed and used as the mass sent Over Here to replace the Olivia from Over There (i.e. Fauxlivia) when they brought her back Over There. It seemed like his death was a key part of the events of the escalating conflict between the two Earths. But in S4E2, *One Night in October*, we see Col. Broyles alive and well. We also know Fauxlivia still went on her mission Over Here, thanks to Walter saying as much. So is Col. Broyles still alive, and if so how? We know that the now-missing character's disappearance altered the history we've seen over the past 3 seasons, how did the events around Broyles' death change in this new history?
2011/10/01
[ "https://scifi.stackexchange.com/questions/5939", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
Maybe, just maybe, Walternate replaced Broyles on his side with a shape shifter because I seem to recall his team thought he just disappeared As I watch the episode, SE4 The Consultant, the idea of shape shifters is viable ONLY if they take on the emotions of the 'bodies' they inhabit. Remember, in last week's episode, the shape shifter who took on (and killed) multiple victims, STILL carried the picture of his 'real' son. Nothing suggested he had any emotional attachment to the loves ones of the victims he inhabited. With that in mind, it is not consistant for Col. Broyles body to have been occupied by a shape shifter because Col. Broyles is acting as a mole to save his son. A shape shifter would have no love for that child. For these reasons, the reappearance of Col. Broyles, 'back from the dead,' remains unexplained.
This really bothers me because either way, Fauxlivia would have had to be replaced mass wise with something from the other side. There's no way Olivia could have escaped without col. Broyles help, so the events don't seem to have changed even with / without the missing character.
5,939
Prior to the events of the season 3 finale of *Fringe*, the Broyles from Over There (i.e. Col. Broyles) died. After the events of that finale, a character was wiped from history. Col. Broyles was killed and used as the mass sent Over Here to replace the Olivia from Over There (i.e. Fauxlivia) when they brought her back Over There. It seemed like his death was a key part of the events of the escalating conflict between the two Earths. But in S4E2, *One Night in October*, we see Col. Broyles alive and well. We also know Fauxlivia still went on her mission Over Here, thanks to Walter saying as much. So is Col. Broyles still alive, and if so how? We know that the now-missing character's disappearance altered the history we've seen over the past 3 seasons, how did the events around Broyles' death change in this new history?
2011/10/01
[ "https://scifi.stackexchange.com/questions/5939", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/-1/" ]
In S4E2, Walter mentioned that *Olivia* was kidnapped to the other side, not Peter being kidnapped and her following. I think that with that significant change, she probably did not interact with Broyles. Walternate would have kept her captive and experimented on her instead of trying to brainwash her into believing she was Fauxlivia. Also, I don't think this is something the writers planned too far in advance. I looked back to S3E22, the final episode of season 3, at the very end, when the two worlds come together. We see both Olivia's and both Walters, but we only see the Broyles from 'our' side. If the writers had been planning this back then, I think the other Broyles would have 'magically' appeared at that time.
We know that 'Over There' they are far more advanced technologically and medically. In the first episode of season 4 we see Walter reanimate a dead bird which briefly flies around the lab. Perhaps they sent Colonel Broyles back soon enough so they were able to save him?
6,021,047
I have (what I hope is) a very simple question. I would like to use some javax.crypto classes from within a python script, so be able to do something like: ``` from javax.crypto import Cipher cipher = Cipher.getInstance('AES/CTR/NoPadding') ``` But I am not familiar with how to do this get python to be able to recognise java packages, at the moment python, of course, simply says: > > ImportError: No module named > javax.crypto > > > Is it simply a case of adding some variable to $PYTHONPATH or is this just completely wrong? Many Thanks, Chris
2011/05/16
[ "https://Stackoverflow.com/questions/6021047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/744064/" ]
It's very completely wrong. Python and Java are separate languages, and CPython, the implementation you're using, has its own VM. Use [Jython](http://www.jython.org/) if you want to bridge the two.
Under jython you use the syntax you describe. Basic types(strings, ints, floats) are converted automatically by jython when going from some .py code into java. If you want to be processing your own objects you have to start writing interface wrappers. ``` C:\>SET PATH=C:\jython2.5.2\bin;%PATH% C:\>jython Jython 2.5.2 (Release_2_5_2:7206, Mar 2 2011, 23:12:06) [Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.6.0_24 Type "help", "copyright", "credits" or "license" for more information. >>> from javax.crypto import Cipher >>> cipher = Cipher.getInstance('AES/CTR/NoPadding') >>> cipher javax.crypto.Cipher@1296d1d >>> ```
69,222,704
What I want to do is following left corner in the container. I tried to do it putting another green container in it but, it does not fit with the border radius of original container. [![enter image description here](https://i.stack.imgur.com/NODtG.png)](https://i.stack.imgur.com/NODtG.png)
2021/09/17
[ "https://Stackoverflow.com/questions/69222704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15751269/" ]
like this? ``` ClipRRect( borderRadius: BorderRadius.all(Radius.circular(16)), child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Container( width: 10, height: 100, decoration: BoxDecoration( color: Colors.green, ), ), Container( width: 390, height: 100, decoration: BoxDecoration( color: Colors.greenAccent, ), child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Icon(Icons.check_circle), Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text("YOUR MAIN TEXT"), Text("YOUR TEXT"), ], ), ], ), ), ], ), ) ```
You can achieve it by setting a `BorderSide` inside a `Border`. ``` Container( height: 100, width: 400, decoration: BoxDecoration( color: Colors.green[200], border: const Border( left: BorderSide( width: 16.0, color: Colors.green, ), ), ), ), ``` [![Result](https://i.stack.imgur.com/teQm0.png)](https://i.stack.imgur.com/teQm0.png)
52,462,991
SQL table has the following data, with 3 columns Id, Name and Full Name. ``` | ID | Name | FullName | | 1 | a | a | | 2 | b | ab | | 3 | c | abc | | 4 | d | ad | | 5 | e | ade | | 6 | i | i | | 7 | g | ig | ``` For example, in the rows where ID =1 and , Full Name column value(s) are 'a' and 'ab'. This data is a substring in the row 3 (id =3) Full Name column data 'abc'. How to exclude the rows Id =1 and Id =2 because the 'full name' column data is a substring to the FullName column value 'abc' in row Id =3. **Desired output** ``` | ID | Name | FullName | | 3 | c | abc | | 5 | e | ade | | 7 | g | ig | ```
2018/09/23
[ "https://Stackoverflow.com/questions/52462991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5028052/" ]
Here is a solution: ``` CREATE TABLE MyTable( ID INT, Name VARCHAR(45), FullName VARCHAR(90) ); INSERT INTO MyTable VALUES (1, 'a', 'a'), (2, 'b', 'ab'), (3, 'c', 'abc'), (4, 'd', 'ad'), (5, 'e', 'ade'), (6, 'i', 'i'), (7, 'g', 'ig'); SELECT * FROM MyTable WHERE ID NOT IN ( SELECT DISTINCT T1.ID FROM MyTable T1 INNER JOIN MyTable T2 ON T1.ID <> T2.ID AND T2.FullName LIKE '%' + T1.FullName + '%' ); ``` Results: ``` +----+----+------+----------+ | | ID | Name | FullName | +----+----+------+----------+ | 1 | 3 | c | abc | | 2 | 5 | e | ade | | 3 | 7 | g | ig | +----+----+------+----------+ ```
Here is a query which seems to be working. We can phrase a matching full name as one for which there are no parents of that full name. ``` SELECT t1.* FROM yourTable t1 WHERE NOT EXISTS (SELECT 1 FROM yourTable t2 WHERE t2.FullName LIKE '%' + t1.FullName + '%' AND LEN(t2.FullName) > LEN(t1.FullName)); ``` [![enter image description here](https://i.stack.imgur.com/iUwWU.png)](https://i.stack.imgur.com/iUwWU.png) [Demo ----](http://rextester.com/QQEDN60446)
73,990,693
How can i add three diagonal gradients on this section with the first gradient top left and the rest succeeding the next? ``` <section id='product'> <div className="container"> <div className="row justify-content-center"> <div className="col-md-8 mt-5"> <h1 className="display-4 fw-bolder mb-4 text-center text-white" style={{fontFamily: "Brush Script MT, Brush Script Std, cursive",display: 'flex', justifyContent:'center', alignItems:'center', height: '45vh'}}>Coming Soon</h1> {/* <p className="lead text-center fs-4 mb-5 text-white" style={} >Coming Soon</p> */} <div className='buttons d-flex justify-content-center'> {/* <button className='btn btn-outline-primary rounded-pill px-4 py-2 ms-2'>Learn More</button> <button className='btn btn-outline-primary rounded-pill px-4 py-2 ms-2'>Buy Now</button> */} </div> </div> </div> </div> </section> ``` css : ``` #product{ background: #00FFFF; background: linear-gradient(118deg,#0000FF .001%,#00FFFF 100%); min-height: 500px; } ```
2022/10/07
[ "https://Stackoverflow.com/questions/73990693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19943129/" ]
If there is no discernable speedup, then probably your code is not CPU-bound. In general, writing to a disk (even an SSD) is much slower than running code on the CPU. If several worker processes are writing significant amounts of data to disk, that might be the bottleneck. To diagnose the problem, you have to *measure*. You should separate the calculations from the saving of the data; e.g. run `sim.integrate()` followed by `sim.simulationarchive_snapshot()` 10 times, and sandwich each of those calls between `time.monotonic()` calls. Then return the average time of the integration step and the snapshot steps as shown below. ``` import time def two_orbits_one_pool(orbit1, orbit2): ####################################### print('process number', mp.current_process().name) ####################################### # build simulation sim = rebound.Simulation() # add sun sim.add(m=1.) # add two overlapping orbits sim.add(primary=sim.particles[0], m=orbit1['m'], a=orbit1['a'], e=orbit1['e'], inc=orbit1['i'], \ pomega=orbit1['lop'], Omega=orbit1['lan'], M=orbit1['M']) sim.add(primary=sim.particles[0], m=orbit2['m'], a=orbit2['a'], e=orbit2['e'], inc=orbit2['i'], \ pomega=orbit2['lop'], Omega=orbit2['lan'], M=orbit2['M']) sim.move_to_com() # integrate for 10 orbits of orbit1 P = 2.*np.pi * np.sqrt(orbit1['a']**3) arname = "archive-{}.bin".format(mp.current_process().name) itime, stime = 0.0, 0.0 for k in range(10): start = time.monotonic() sim.integrate(P) itime += time.monotonic() - start start = time.monotonic() sim.simulationarchive_snapshot(arname) stime += time.monotonic() - start return (mp.current_process().name, itime/10, stime/10) # Run the calculations with mp.Pool() as pool: data = pool.starmap(two_orbits_one_pool, args) # Print the times that it took. for name, itime, stime in data: print(f"worker {name}: itime {itime} s, stime {stime} s") ``` That should tell you what the bottleneck is. Possible solutions *if* writing to disk is the bottleneck; * ~~Use an SSD to store the simulation results~~. * Use a RAM-disk to store the simulation results. (Although compared to an SSD not a huge performance boost.) * Check if you can tune your OS for maximum write performance. **Edit1:** Given your measurement result, the obvious performance improvement is to save less often. Another option that might be worth looking at is staggering the writes. *That only makes sense if there is significant overlap between the writes from different processes, and if those concurrent writes can saturate the disk I/O subsystem.* So you'd have to measure that first. If there is overlap, create a `Lock` object in the parent process. Then acquire the lock before (explicitly) saving, and release it after. This won't work with `automateSimulationArchive`. A last option is to write your own save function using `mmap`. Using `mmap` is somewhat clunky compared to normal file handling in Python. But it can significantly improve performance. However I am unsure that the gains justify the effort in this case.
The straggler effect can have a big impact on such jobs. straggler effect ================ Suppose you have N tasks for N cores, and each task has a different duration. Order by duration to find min\_time and max\_time. All N cores will be busy up through min\_time, but then they go idle, one by one. Just before max\_time, only a single "straggler" core is being used. predictions =========== If you can make a decent guess about task duration beforehand, use that to sort them in descending order. For T tasks > N cores, schedule the long tasks first. Then N tasks run for a while, the shortest of those completes, and the now-idle core picks up a task of "medium" duration. By the time we get to the T-th task, each core has a random amount of work still to do, and we're scheduling a "short" task. So cores are mostly busy doing useful work, right up till near the end. logging ======= If you cannot make a useful duration estimate a priori, at least record the start times and durations. Use that to figure out whether stragglers are causing you grief, or if it's something else like L3 cache thrashing.
38,418,504
I've been trying to implement image upload with the following requirements: 1. Drag and drop 2. Display dropped image in a popup with option to resize image 3. Upload image after preview and resize I'm trying to restrict my options to either [bass jobsen's jqueryupload](https://github.com/bassjobsen/jqueryupload). Using this plugin, I've so far managed to do something similar to this: ``` $('document).on('drop', '#drop_area', function(event) { var file_input = $('<input>').attr({type: 'file', 'id': 'hidden_file_input'}); $('body').append(file_input.hide()); var file = event.originalEvent.dataTransfer.files[0]; var file_reader = new FileReader(); file_reader.onloadend = function(e) { var src = file_reader.result; file_upload_preview(); } file_reader.readAsDataUrl(file); $file_input[0][files][0] = file; // this line only works 5% of the time }); function file_upload_preview() { self.modal_show('/modal/preview', function(e) { // render popup using file /modal/preview.html // do image crop options }); doUpload(); } function doUpload() { var file_input = $('#upload_form_id'); var file = file_input.get(0).files[0]; // throws error because of $file_input[0][files][0] = file; not working var url = '/tmp/uploads'; var data = { 'x' : file_input.data('x') // image resize dimension // add others, etc. }; // do validations file_input.upload(url, data, function(json) { // jqueryupload start var res = JSON.parse(json); // throws error if the above code doesn't }); } ``` I am getting multiple errors with this code: 1. The line **$file\_input[0][files][0] = file;** will not always work for some reason 2. If #1 does not happen, another error is thrown when trying to upload: **Can not process empty Imagick object** Given this situation, what is the best and sure way I can set the value of file\_input by drag and drop instead of choosing the file? Also is it possible to implement what I need using this plugin? Any suggestions would be welcome. Thanks in advanced.
2016/07/17
[ "https://Stackoverflow.com/questions/38418504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1597438/" ]
There are several issues at `javascript` at Question * `$file_input[0]files[0]` should select `File` object, instead of `$file_input[0][files][0]`, where brackets surrounding `files` property is syntax error; * it is not possible to set a `File` object to the [`FileList`](https://developer.mozilla.org/en-US/docs/Web/API/FileList) object of an `<input type="file">` element, where `$file_input[0][files][0] = file; // this line only works 5% of the time` attempts to set dropped file `var file = event.originalEvent.dataTransfer.files[0];` as value of `.files[0]` at dynamically created `<input type="file">` element `var file_input = $('<input>').attr({type: 'file', 'id': 'hidden_file_input'});`; * `var file_input = $('#upload_form_id')` is not `#drop_area` element where files were dropped by user --- Edit, Updated > > 1. Drag and drop file to main.html 2. Add file to rendered popup - preview.html 3. upload > > > main.html ``` <!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"> </script> <style> #dropzone { display: block; width: 400px; height: 200px; border: 1px solid blue; text-align: center; font-size: 36px; } </style> <script> function handleDrop(event) { var file = event.dataTransfer.files[0]; // copy dropped file // note, not necessary though requirement var copy = file.slice(); // create objectURL of `copy` var url = URL.createObjectURL(copy); // open `preview.html` var preview = window .open("preview.html" , "preview" , "width=400,height=400,resizable=yes,scrollbars=yes"); // set `img` at `preview.html` to `copy` // at `DOMContenetLoaded` event of `peview $(preview).on("DOMContentLoaded", function(e) { // set `img` `src` to `url`:`copy` of `file` at `preview.html` $(e.target.body).find("img").attr("src", url); // remove `disabled` for ability to close `preview` $("button:eq(1)").removeAttr("disabled") }); $("button:eq(1)").on("click", function() { // close `preview` preview.close(); // revoke objectURL URL.revokeObjectURL(url); $(this).attr("disabled", true) // remove `disabled` at previous `button` // for ability to upload file .prev("button").removeAttr("disabled") }); $("button:eq(0)").on("click", function() { // create `FormData` object to `POST` var data = new FormData(); data.append("file", file); console.log(data.get("file")); $(this).attr("disabled", true) // do ajax stuff, post file // $.ajax({ // type:"POST", // processData:false, // data: data // }) }); } </script> </head> <body> <div id="dropzone" ondragenter="event.stopPropagation(); event.preventDefault();" ondragover="event.stopPropagation(); event.preventDefault();" ondrop="event.stopPropagation(); event.preventDefault();handleDrop(event)"> Drop files </div> <button disabled="">upload</button> <button disabled="">close preview</button> </body> </html> ``` preview.html ``` <!DOCTYPE html> <html> <body> <img src=""> </body> </html> ``` plnkr <http://plnkr.co/edit/Cij0bUojvfhUNZjRw4FM?p=preview>
I think,the cause of the error that `readAsDataUrl()` is async operation, and you must wait for it to finish before you do the rest of the work. You can try the following code: ``` file_reader.onload = function(e) { if(reader.readyState == FileReader.DONE) //You can remove this if not needed alert(file.name); } } ```
897
In the [site FAQ](https://security.stackexchange.com/faq), it is written: > > Black Hat vs White Hat - This site is not intended to be a resource for Black Hats, or malicious hackers. While we understand discussion of exploits may require examples, if the question looks too much like a request for attack tools or mechanisms to spread a virus, it may be moderated. > > > I don't think this reflects our stance on black hat topics very well. The assertion that “This site is not intended to be a resource for Black Hats” seems to be saying that any discussion of black hat *topics* (attacks, exploits, etc.) is forbidden. Furthermore, while the text actually doesn't say so, it looks like all questions of attack tools or mechanisms to spread viruses are forbidden. The outcome of meta discussions [1](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware) [2](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code) [3](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats) [4](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat) is rather that broadly speaking, we don't discriminate against black hat content. Quoting from some of the answers with high upvotes on these threads: * Should we accept question about making exploit or building malware ? “[I say we should allow such questions](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware/22#22)” * [why even risk losing legitimate users and content?](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/130#130) * [exploit code should not only be allowed, it should be expected!](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/193#193) * [It's perfectly valid, even in a whitehat PoV, to be asking only about the attack, exploit, vector, payload, whatever.](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats/294#294) * “[There is no such thing as black and white, only shades of gray.](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat/297#297)” We should clarify the FAQ to make it clear that discussions of attacks and exploits is on-topic on this site. We should replace the paragraph quoted above by one that reflects the policies that are effectively applied and the kind of bad content that we want to feel justified in removing. The script kiddie content can pretty much be moderated by the usual Stack Exchange rules. Things like “How do I hack www.example.com?” or “Join me in a DDoS!” can be closed as [not a real question](https://security.stackexchange.com/faq#close). I would appreciate input from moderators regarding past questions that have been deleted for some black hat-related reason and that were not close-worthy under the general Stack Exchange rules. I propose to start with this: > > Black Hat vs White Hat: Discussions of attacks and exploits are allowed within reason. We adhere to responsible disclosure rules, > > > What else do we need to say?
2012/08/10
[ "https://security.meta.stackexchange.com/questions/897", "https://security.meta.stackexchange.com", "https://security.meta.stackexchange.com/users/414/" ]
After several discussions in chat, most notably ones involving @Gilles, I've learned a couple key points. To sum up, these add up to say that any truly undesirable or inappropriate "black hat" questions should already be getting handled per existing StackExchange policies. **For the TL;DR version, jump to the bolded paragraph at the end.** * Any post that appears deliberately aimed at facilitating malicious and/or illegal activity runs afoul of the StackExchange [Terms of Service](http://stackexchange.com/legal/terms-of-service). Particularly, these pieces of Section 4, "Restrictions" (emphasis mine): > > ... ***Any fraudulent, abusive, or > otherwise illegal activity*** or any use of the Services or Content in > violation of this Agreement ***may be grounds for termination of > Subscriber’s right to Services or to access the Network***. > > > ... > > ***Use of the Network or Services to violate the security of any computer network, crack passwords or security encryption codes,*** > transfer or store illegal material including that are deemed > threatening or obscene, ***or engage in any kind of illegal activity > is expressly prohibited.*** ... > > > * Most (if not all) other undesirable or inappropriate "black hat" questions should already be getting closed per the regular close reasons. Particularly: **Not Constructive**, **Not a Real Question**, or **Too Localized**. Off-Topic should not be used, because "black hat" in general is *not* off-topic. So, for the purposes of *setting* policy, nothing really needs to be added to the FAQ - in fact, the existing section could be removed and our policy would still be the same. However, for the sake of emphasizing our position against the *knowing* facilitation of illegal conduct, there *should* be something in the FAQ to re-iterate or paraphrase the relevant portions in the ToS. Perhaps the existing section could use a thorough re-write, but it should not be done without. Throughout all these discussions, I came to form an analogy of our community's situation to that of a responsible gun store owner who is operating in a jurisdiction that protects the right to keep and bear arms. **As responsible citizens who are in the business of "selling weapons", we should happily "sell" our "weapons" to anyone - regardless of their intent - up until the point that we actually have a reasonable suspicion (or, and especially, confession) that their intent is malicious and/or illegal. After that point, and *only* after that point, it is our ethical responsibility to refuse the "sale".**
It's not hard to come up with a real question that's not too localized, that is clearly only for black hat purposes and in my opinion should get deleted. For example: > > **How do I do an ARP Spoofing Attack**: I'm trying to steal my neighbors passwords/credit card numbers. I set up a fake version of a popular shopping website and I can connect on their open wifi network. I think I could do something like ARP spoofing or something to redirect them to my fake site. It would be very appreciated if someone could give me a clear tutorial on how to carry out these attacks or suggest tools or other attacks that will do this for me. > > > Compare to a similar, but perfectly valid question on the same topic: > > **What is the threat from ARP Spoofing:** How are the attacks done and what can I do to safeguard myself from them?" > > > I would expect stupid answers to the first question posting links to kiddie hacker scripts with little to no explanation of what's going on so being of no use to white hats, but being immediately useful to kiddie black hats. I wouldn't expect answers to the second question to be such low quality. Instead, I'd expect them to explain the threat (what is ARP, how does level-2 routing work) and ways to prevent it (e.g., secure the wifi network, use https and other secure protocols). The difference is subtle, but I believe quite important. We shouldn't deliberately assist black hats or people doing blind penetration tests (that cannot be in any way differentiated from black hats). Personally, I would like something to that effect to be present in the rules; otherwise we run the risk of doing [illegal things](http://stackexchange.com/legal/content-policy) in some jurisdictions, though I am not a lawyer. (Does suggesting ways for someone to do a successful SQL injection attack on a specific application count as abetting a criminal?) You should not ask questions asking for assistance in doing illegal activities like breaking into a system you do not have permission to use, or searching for exploits in an web application that you did not write and do not have the source code for and we have no way of knowing if the web application's owners have given you permission to legally evaluate its security. However, it is encouraged to ask and answer generic questions about various types of attacks, essentially in the context of how do the attacks work and how to best prevent them from occurring on your systems. A general guideline of questions and answers should be whether this question could be useful to a white hat (e.g., not automated kiddie hacking scripts), but a description of weaknesses in certain weak methods and how they should be fixed. --- Long edit in response to Gilles: My claim is that "too localized" and "not a real question" will not capture all black hat questions. NaRQ can usually be avoided with clear language focused a specific aspect of an attack. Localization can be avoided by asking about an attack relevant to many computers/situations. (And in any case many too localized attacks are less localized than highly-upvoted questions like ["I just discovered major security flaws in my web store"](https://security.stackexchange.com/questions/5701/i-just-discovered-major-security-flaws-in-my-web-store) ). I have no problem erring on the side of explaining principles behind an attack to increase the knowledge for defensive measures. Yes, resources on the internet exist for black hats with tools and tutorials, but we don't have to be one of them (asking specific questions could be quite useful to script kiddies even if the knowledge exists elsewhere). I don't think my belief is unique: let's look at other parts of the four of the five quotes you gave (Graham Lee's answer did want to allow any question asking about how to build malware without regard to intention): * [rox0r - 'why risk losing legitimate users/conent'](https://security.meta.stackexchange.com/a/130/2568) "Asking for exploits against a specific person (company) are banned" while "illustrating auth attacks and weakness should be discussed. Malware construction questions are out of scope." * [Dave - "exploit code ... should be expected!"](https://security.meta.stackexchange.com/a/193/2568) "banning questions that ask for exploit code only"; "encouraging answers that provide solutions with the attack that caused the vulnerability". * [Avid - 'It's ... valid ... to be asking about the attack, exploit ...'](https://security.meta.stackexchange.com/a/294/2568) At some point, we need to rely on human sense - our collective noses for what is hinky". [Elsewhere Avid said](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware#comment12_15): [We should be] 'explaining principles, so as to better protect against [malware/exploits] rather than providing food for script kiddies.' * [ninefingers - 'There is ... only shades of gray'](https://security.meta.stackexchange.com/a/297/2568) "its a subjective call". "Pretty much the same question, but looks totally different in terms of intent. If I were to draw the line in the sand, I would say the key in my version would be that you're coming at it from a defence angle too." These all seem to agree that intent is important; and the belief that black hat useful only questions/answers should be against our policies. This is not an academic issue that only exists for trick questions. There have been mod-removed questions that specifically asked how do I do some black hat activity (e.g., [how to exploit windows 7 remotely](https://security.stackexchange.com/questions/1444/windows-7-exploited-remotely) ) that were not too localized and easily could have been phrased as a real question. Another example is ["How can I check whether it's SQL injection? How can I exploit it? I don't have access to the source code but can query it with more requests."](https://security.stackexchange.com/revisions/13997acf-e211-471b-9674-486b0e6500a5/view-source). I think questions like that (part of an attack or blackbox pen test) should be deleted, not edited into something [resembling a legitimate question](https://security.stackexchange.com/questions/18663/how-to-make-sql-injection-in-postgresqls-tsquery). I have no problem with a quite similar question (possibly from a gray/white box pen test) saying "the PHP source code executing the SQL query says `pg_query_params($dbconn, 'SELECT * from text_table where plainto_tsquery($1) ', array($user_input);` and gives error messages like ... is this vulnerable to SQL injection?". This is perfectly fine as it will be useful to know if you have to fix your weak source code (despite being more localized). Note, the original version of the question had mod-removed answers that basically said "try running this set of SQL injection kiddie scripts". How about something along the lines of > > This site is not intended to be a resource for black hats to ask for assistance in implementing attacks (or doing blackbox penetration tests that simulate a black hat attack). That said educational discussion of insecure practices, including demonstrating example code that bypasses weak security practices is encouraged to enlighten everyone on how to best defend your system against existing attacks. While we prefer to err on the side of more disclosure, questions and answers that focus exclusively on implementation of black hat attacks may be moderated. > > >
897
In the [site FAQ](https://security.stackexchange.com/faq), it is written: > > Black Hat vs White Hat - This site is not intended to be a resource for Black Hats, or malicious hackers. While we understand discussion of exploits may require examples, if the question looks too much like a request for attack tools or mechanisms to spread a virus, it may be moderated. > > > I don't think this reflects our stance on black hat topics very well. The assertion that “This site is not intended to be a resource for Black Hats” seems to be saying that any discussion of black hat *topics* (attacks, exploits, etc.) is forbidden. Furthermore, while the text actually doesn't say so, it looks like all questions of attack tools or mechanisms to spread viruses are forbidden. The outcome of meta discussions [1](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware) [2](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code) [3](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats) [4](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat) is rather that broadly speaking, we don't discriminate against black hat content. Quoting from some of the answers with high upvotes on these threads: * Should we accept question about making exploit or building malware ? “[I say we should allow such questions](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware/22#22)” * [why even risk losing legitimate users and content?](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/130#130) * [exploit code should not only be allowed, it should be expected!](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/193#193) * [It's perfectly valid, even in a whitehat PoV, to be asking only about the attack, exploit, vector, payload, whatever.](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats/294#294) * “[There is no such thing as black and white, only shades of gray.](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat/297#297)” We should clarify the FAQ to make it clear that discussions of attacks and exploits is on-topic on this site. We should replace the paragraph quoted above by one that reflects the policies that are effectively applied and the kind of bad content that we want to feel justified in removing. The script kiddie content can pretty much be moderated by the usual Stack Exchange rules. Things like “How do I hack www.example.com?” or “Join me in a DDoS!” can be closed as [not a real question](https://security.stackexchange.com/faq#close). I would appreciate input from moderators regarding past questions that have been deleted for some black hat-related reason and that were not close-worthy under the general Stack Exchange rules. I propose to start with this: > > Black Hat vs White Hat: Discussions of attacks and exploits are allowed within reason. We adhere to responsible disclosure rules, > > > What else do we need to say?
2012/08/10
[ "https://security.meta.stackexchange.com/questions/897", "https://security.meta.stackexchange.com", "https://security.meta.stackexchange.com/users/414/" ]
I think in principle I agree...and in following @Gilles well researched argument on what we have previously removed as Black Hat it does look like we have pretty much only removed ones that are either rubbish questions, or ones that are blatantly aiming to cause 'bad things' I think I have been quite risk averse (it is instilled into you by the Big-4 :-) so have generally argued for staying further away from Black than this community wants as a whole, but it is a community so we just need to work out what is to be done. So - a way forward that occurs to me is: * We don't use 'This is Black Hat' as a close reason * we do use NARQ/Too localised etc * when we have edge cases, I think us mods need to be a little more patient and you guys will have to be prepared to give guidance in the form of Close Votes and Flags, and chat in the DMZ. Oh, and make sure you point out the ne'er-do-well's and pirates, that we may introduce them to the blunt end of the mod-hammer!
It is the intent that matters. More often than not, you can tell with reasonable accuracy whether the poster is looking for help to do bad stuff or just trying to find vulnerabilities for purposes of system hardening. To paraphrase Justice Stewart, I may not be able to define black-hat questions, but I knows it when I sees it. In other words, the only blanket rule you can make is *don’t ask for help to do bad stuff*, short of that, simply use provided the moderation tools (voting, flagging, closing, etc.) to deal with questions on a case by cases basis as necessary. (You may think that this creates extra, unnecessary work, but the fact is that regardless of what it says in the rules page, bad guys—especially the less smarterier ones—will post anyway and create that same work anyway.)
897
In the [site FAQ](https://security.stackexchange.com/faq), it is written: > > Black Hat vs White Hat - This site is not intended to be a resource for Black Hats, or malicious hackers. While we understand discussion of exploits may require examples, if the question looks too much like a request for attack tools or mechanisms to spread a virus, it may be moderated. > > > I don't think this reflects our stance on black hat topics very well. The assertion that “This site is not intended to be a resource for Black Hats” seems to be saying that any discussion of black hat *topics* (attacks, exploits, etc.) is forbidden. Furthermore, while the text actually doesn't say so, it looks like all questions of attack tools or mechanisms to spread viruses are forbidden. The outcome of meta discussions [1](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware) [2](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code) [3](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats) [4](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat) is rather that broadly speaking, we don't discriminate against black hat content. Quoting from some of the answers with high upvotes on these threads: * Should we accept question about making exploit or building malware ? “[I say we should allow such questions](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware/22#22)” * [why even risk losing legitimate users and content?](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/130#130) * [exploit code should not only be allowed, it should be expected!](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/193#193) * [It's perfectly valid, even in a whitehat PoV, to be asking only about the attack, exploit, vector, payload, whatever.](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats/294#294) * “[There is no such thing as black and white, only shades of gray.](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat/297#297)” We should clarify the FAQ to make it clear that discussions of attacks and exploits is on-topic on this site. We should replace the paragraph quoted above by one that reflects the policies that are effectively applied and the kind of bad content that we want to feel justified in removing. The script kiddie content can pretty much be moderated by the usual Stack Exchange rules. Things like “How do I hack www.example.com?” or “Join me in a DDoS!” can be closed as [not a real question](https://security.stackexchange.com/faq#close). I would appreciate input from moderators regarding past questions that have been deleted for some black hat-related reason and that were not close-worthy under the general Stack Exchange rules. I propose to start with this: > > Black Hat vs White Hat: Discussions of attacks and exploits are allowed within reason. We adhere to responsible disclosure rules, > > > What else do we need to say?
2012/08/10
[ "https://security.meta.stackexchange.com/questions/897", "https://security.meta.stackexchange.com", "https://security.meta.stackexchange.com/users/414/" ]
It's not hard to come up with a real question that's not too localized, that is clearly only for black hat purposes and in my opinion should get deleted. For example: > > **How do I do an ARP Spoofing Attack**: I'm trying to steal my neighbors passwords/credit card numbers. I set up a fake version of a popular shopping website and I can connect on their open wifi network. I think I could do something like ARP spoofing or something to redirect them to my fake site. It would be very appreciated if someone could give me a clear tutorial on how to carry out these attacks or suggest tools or other attacks that will do this for me. > > > Compare to a similar, but perfectly valid question on the same topic: > > **What is the threat from ARP Spoofing:** How are the attacks done and what can I do to safeguard myself from them?" > > > I would expect stupid answers to the first question posting links to kiddie hacker scripts with little to no explanation of what's going on so being of no use to white hats, but being immediately useful to kiddie black hats. I wouldn't expect answers to the second question to be such low quality. Instead, I'd expect them to explain the threat (what is ARP, how does level-2 routing work) and ways to prevent it (e.g., secure the wifi network, use https and other secure protocols). The difference is subtle, but I believe quite important. We shouldn't deliberately assist black hats or people doing blind penetration tests (that cannot be in any way differentiated from black hats). Personally, I would like something to that effect to be present in the rules; otherwise we run the risk of doing [illegal things](http://stackexchange.com/legal/content-policy) in some jurisdictions, though I am not a lawyer. (Does suggesting ways for someone to do a successful SQL injection attack on a specific application count as abetting a criminal?) You should not ask questions asking for assistance in doing illegal activities like breaking into a system you do not have permission to use, or searching for exploits in an web application that you did not write and do not have the source code for and we have no way of knowing if the web application's owners have given you permission to legally evaluate its security. However, it is encouraged to ask and answer generic questions about various types of attacks, essentially in the context of how do the attacks work and how to best prevent them from occurring on your systems. A general guideline of questions and answers should be whether this question could be useful to a white hat (e.g., not automated kiddie hacking scripts), but a description of weaknesses in certain weak methods and how they should be fixed. --- Long edit in response to Gilles: My claim is that "too localized" and "not a real question" will not capture all black hat questions. NaRQ can usually be avoided with clear language focused a specific aspect of an attack. Localization can be avoided by asking about an attack relevant to many computers/situations. (And in any case many too localized attacks are less localized than highly-upvoted questions like ["I just discovered major security flaws in my web store"](https://security.stackexchange.com/questions/5701/i-just-discovered-major-security-flaws-in-my-web-store) ). I have no problem erring on the side of explaining principles behind an attack to increase the knowledge for defensive measures. Yes, resources on the internet exist for black hats with tools and tutorials, but we don't have to be one of them (asking specific questions could be quite useful to script kiddies even if the knowledge exists elsewhere). I don't think my belief is unique: let's look at other parts of the four of the five quotes you gave (Graham Lee's answer did want to allow any question asking about how to build malware without regard to intention): * [rox0r - 'why risk losing legitimate users/conent'](https://security.meta.stackexchange.com/a/130/2568) "Asking for exploits against a specific person (company) are banned" while "illustrating auth attacks and weakness should be discussed. Malware construction questions are out of scope." * [Dave - "exploit code ... should be expected!"](https://security.meta.stackexchange.com/a/193/2568) "banning questions that ask for exploit code only"; "encouraging answers that provide solutions with the attack that caused the vulnerability". * [Avid - 'It's ... valid ... to be asking about the attack, exploit ...'](https://security.meta.stackexchange.com/a/294/2568) At some point, we need to rely on human sense - our collective noses for what is hinky". [Elsewhere Avid said](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware#comment12_15): [We should be] 'explaining principles, so as to better protect against [malware/exploits] rather than providing food for script kiddies.' * [ninefingers - 'There is ... only shades of gray'](https://security.meta.stackexchange.com/a/297/2568) "its a subjective call". "Pretty much the same question, but looks totally different in terms of intent. If I were to draw the line in the sand, I would say the key in my version would be that you're coming at it from a defence angle too." These all seem to agree that intent is important; and the belief that black hat useful only questions/answers should be against our policies. This is not an academic issue that only exists for trick questions. There have been mod-removed questions that specifically asked how do I do some black hat activity (e.g., [how to exploit windows 7 remotely](https://security.stackexchange.com/questions/1444/windows-7-exploited-remotely) ) that were not too localized and easily could have been phrased as a real question. Another example is ["How can I check whether it's SQL injection? How can I exploit it? I don't have access to the source code but can query it with more requests."](https://security.stackexchange.com/revisions/13997acf-e211-471b-9674-486b0e6500a5/view-source). I think questions like that (part of an attack or blackbox pen test) should be deleted, not edited into something [resembling a legitimate question](https://security.stackexchange.com/questions/18663/how-to-make-sql-injection-in-postgresqls-tsquery). I have no problem with a quite similar question (possibly from a gray/white box pen test) saying "the PHP source code executing the SQL query says `pg_query_params($dbconn, 'SELECT * from text_table where plainto_tsquery($1) ', array($user_input);` and gives error messages like ... is this vulnerable to SQL injection?". This is perfectly fine as it will be useful to know if you have to fix your weak source code (despite being more localized). Note, the original version of the question had mod-removed answers that basically said "try running this set of SQL injection kiddie scripts". How about something along the lines of > > This site is not intended to be a resource for black hats to ask for assistance in implementing attacks (or doing blackbox penetration tests that simulate a black hat attack). That said educational discussion of insecure practices, including demonstrating example code that bypasses weak security practices is encouraged to enlighten everyone on how to best defend your system against existing attacks. While we prefer to err on the side of more disclosure, questions and answers that focus exclusively on implementation of black hat attacks may be moderated. > > >
It seems to me that there is quite a bit of time wasted on the assumption that people on here (whitehat, blackhat, grey, yellow...) are actually telling the truth about who they are. Honestly, when I read a question I skim over personal details and all the 'fluff' just to figure out what the actual question or answer is -from an objective perspective. In fact, I many times edit posts to *remove* that fluff just so they can be received equally and not judged on some ancillary detail (Like "my mother is..." or " I am a ransomeware author...") that doesnt add value to the post itself. While this debate over the stance is useful from a philosophical perspective, it is moot in that we cannot reasonably determine if posters are who they say they are. That being the case, why bother getting all flustered about it. Just take posts at face value. My suggestion would be to (1) add verbage in the policies that encourage objectivity in posting, (2) actively edit posts to remove subjective details -especially credentials that cannot be verified, and (3) encourage users to be tolerant of offensive posts.
897
In the [site FAQ](https://security.stackexchange.com/faq), it is written: > > Black Hat vs White Hat - This site is not intended to be a resource for Black Hats, or malicious hackers. While we understand discussion of exploits may require examples, if the question looks too much like a request for attack tools or mechanisms to spread a virus, it may be moderated. > > > I don't think this reflects our stance on black hat topics very well. The assertion that “This site is not intended to be a resource for Black Hats” seems to be saying that any discussion of black hat *topics* (attacks, exploits, etc.) is forbidden. Furthermore, while the text actually doesn't say so, it looks like all questions of attack tools or mechanisms to spread viruses are forbidden. The outcome of meta discussions [1](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware) [2](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code) [3](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats) [4](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat) is rather that broadly speaking, we don't discriminate against black hat content. Quoting from some of the answers with high upvotes on these threads: * Should we accept question about making exploit or building malware ? “[I say we should allow such questions](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware/22#22)” * [why even risk losing legitimate users and content?](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/130#130) * [exploit code should not only be allowed, it should be expected!](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/193#193) * [It's perfectly valid, even in a whitehat PoV, to be asking only about the attack, exploit, vector, payload, whatever.](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats/294#294) * “[There is no such thing as black and white, only shades of gray.](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat/297#297)” We should clarify the FAQ to make it clear that discussions of attacks and exploits is on-topic on this site. We should replace the paragraph quoted above by one that reflects the policies that are effectively applied and the kind of bad content that we want to feel justified in removing. The script kiddie content can pretty much be moderated by the usual Stack Exchange rules. Things like “How do I hack www.example.com?” or “Join me in a DDoS!” can be closed as [not a real question](https://security.stackexchange.com/faq#close). I would appreciate input from moderators regarding past questions that have been deleted for some black hat-related reason and that were not close-worthy under the general Stack Exchange rules. I propose to start with this: > > Black Hat vs White Hat: Discussions of attacks and exploits are allowed within reason. We adhere to responsible disclosure rules, > > > What else do we need to say?
2012/08/10
[ "https://security.meta.stackexchange.com/questions/897", "https://security.meta.stackexchange.com", "https://security.meta.stackexchange.com/users/414/" ]
I think the biggest problem in the security industry right now is that there are too many stuck up whitehats that are expected to break the exploitation process when they themselves have never written an exploit. So in the realm of security, making any topic taboo makes the process of learning into a vulnerability. After all a blackhat might ask a question where we all learn somthing, \*\* **gasp** \*\*... I am a whitehat, in that I have never Illegally broken into a system and I am paid to prevent such behavior. That being said [I enjoy writing exploits](http://www.exploit-db.com/author/?a=628) and I think that full disclosure is a useful tool if the vendor is not cooperative. This behavior is legal, at least in the US. Blackhats must be able to solve difficult, intellectual problems in order to be successful, and for that they have my respect. Very few people on the planet can grasp such problems. If anyone is able to ask an interesting question and I am able to provide an answer I will do so. By not providing an answer to a potential blackhat, I don't believe that the internet is a "safer place". After all this community is the sole provider of such information. I will not answer questions like "How do I hack a facebook account" or other such nonsense. I think that the community is uniformly against such questions. If the OP isn't willing to put in the effort to climb the mountain of information that makes up modern security then I am not willing guide that person through the difficult terrain.
It is the intent that matters. More often than not, you can tell with reasonable accuracy whether the poster is looking for help to do bad stuff or just trying to find vulnerabilities for purposes of system hardening. To paraphrase Justice Stewart, I may not be able to define black-hat questions, but I knows it when I sees it. In other words, the only blanket rule you can make is *don’t ask for help to do bad stuff*, short of that, simply use provided the moderation tools (voting, flagging, closing, etc.) to deal with questions on a case by cases basis as necessary. (You may think that this creates extra, unnecessary work, but the fact is that regardless of what it says in the rules page, bad guys—especially the less smarterier ones—will post anyway and create that same work anyway.)
897
In the [site FAQ](https://security.stackexchange.com/faq), it is written: > > Black Hat vs White Hat - This site is not intended to be a resource for Black Hats, or malicious hackers. While we understand discussion of exploits may require examples, if the question looks too much like a request for attack tools or mechanisms to spread a virus, it may be moderated. > > > I don't think this reflects our stance on black hat topics very well. The assertion that “This site is not intended to be a resource for Black Hats” seems to be saying that any discussion of black hat *topics* (attacks, exploits, etc.) is forbidden. Furthermore, while the text actually doesn't say so, it looks like all questions of attack tools or mechanisms to spread viruses are forbidden. The outcome of meta discussions [1](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware) [2](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code) [3](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats) [4](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat) is rather that broadly speaking, we don't discriminate against black hat content. Quoting from some of the answers with high upvotes on these threads: * Should we accept question about making exploit or building malware ? “[I say we should allow such questions](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware/22#22)” * [why even risk losing legitimate users and content?](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/130#130) * [exploit code should not only be allowed, it should be expected!](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/193#193) * [It's perfectly valid, even in a whitehat PoV, to be asking only about the attack, exploit, vector, payload, whatever.](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats/294#294) * “[There is no such thing as black and white, only shades of gray.](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat/297#297)” We should clarify the FAQ to make it clear that discussions of attacks and exploits is on-topic on this site. We should replace the paragraph quoted above by one that reflects the policies that are effectively applied and the kind of bad content that we want to feel justified in removing. The script kiddie content can pretty much be moderated by the usual Stack Exchange rules. Things like “How do I hack www.example.com?” or “Join me in a DDoS!” can be closed as [not a real question](https://security.stackexchange.com/faq#close). I would appreciate input from moderators regarding past questions that have been deleted for some black hat-related reason and that were not close-worthy under the general Stack Exchange rules. I propose to start with this: > > Black Hat vs White Hat: Discussions of attacks and exploits are allowed within reason. We adhere to responsible disclosure rules, > > > What else do we need to say?
2012/08/10
[ "https://security.meta.stackexchange.com/questions/897", "https://security.meta.stackexchange.com", "https://security.meta.stackexchange.com/users/414/" ]
In my opinion to be sure that protection mechanisms work, you should know what attacks can be performed against them. Only if you know techniques that can be used to attack you, you can be sure whether you are protected. If you go to Sec.SE asking about attack protection without knowing full attack profile, you can't judge whether those protection mechanisms work. So before knowing protection measures, you should know attack itself. Based on this, I think that questions asking about how to perform an attack seem to be good for me as this knowledge is needed to be able to judge protection measures. For example to be sure that my protection measures catching scan anonymizers work, I should [know techniques](https://security.stackexchange.com/questions/12762/what-is-the-best-tool-to-anonymize-your-scans-network-ports) that can be used to anonymize scans. To figure out how to build smartphone that will be able to notify user in case of attack, I should know [how those attacks work](https://security.stackexchange.com/questions/17738/are-there-bluetooth-attacks-on-smartphones-that-will-not-notify-the-user-of-the). Arguments like this can be devised in most situations. I vote to allow content like this to be posted on site.
It is the intent that matters. More often than not, you can tell with reasonable accuracy whether the poster is looking for help to do bad stuff or just trying to find vulnerabilities for purposes of system hardening. To paraphrase Justice Stewart, I may not be able to define black-hat questions, but I knows it when I sees it. In other words, the only blanket rule you can make is *don’t ask for help to do bad stuff*, short of that, simply use provided the moderation tools (voting, flagging, closing, etc.) to deal with questions on a case by cases basis as necessary. (You may think that this creates extra, unnecessary work, but the fact is that regardless of what it says in the rules page, bad guys—especially the less smarterier ones—will post anyway and create that same work anyway.)
897
In the [site FAQ](https://security.stackexchange.com/faq), it is written: > > Black Hat vs White Hat - This site is not intended to be a resource for Black Hats, or malicious hackers. While we understand discussion of exploits may require examples, if the question looks too much like a request for attack tools or mechanisms to spread a virus, it may be moderated. > > > I don't think this reflects our stance on black hat topics very well. The assertion that “This site is not intended to be a resource for Black Hats” seems to be saying that any discussion of black hat *topics* (attacks, exploits, etc.) is forbidden. Furthermore, while the text actually doesn't say so, it looks like all questions of attack tools or mechanisms to spread viruses are forbidden. The outcome of meta discussions [1](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware) [2](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code) [3](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats) [4](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat) is rather that broadly speaking, we don't discriminate against black hat content. Quoting from some of the answers with high upvotes on these threads: * Should we accept question about making exploit or building malware ? “[I say we should allow such questions](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware/22#22)” * [why even risk losing legitimate users and content?](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/130#130) * [exploit code should not only be allowed, it should be expected!](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/193#193) * [It's perfectly valid, even in a whitehat PoV, to be asking only about the attack, exploit, vector, payload, whatever.](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats/294#294) * “[There is no such thing as black and white, only shades of gray.](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat/297#297)” We should clarify the FAQ to make it clear that discussions of attacks and exploits is on-topic on this site. We should replace the paragraph quoted above by one that reflects the policies that are effectively applied and the kind of bad content that we want to feel justified in removing. The script kiddie content can pretty much be moderated by the usual Stack Exchange rules. Things like “How do I hack www.example.com?” or “Join me in a DDoS!” can be closed as [not a real question](https://security.stackexchange.com/faq#close). I would appreciate input from moderators regarding past questions that have been deleted for some black hat-related reason and that were not close-worthy under the general Stack Exchange rules. I propose to start with this: > > Black Hat vs White Hat: Discussions of attacks and exploits are allowed within reason. We adhere to responsible disclosure rules, > > > What else do we need to say?
2012/08/10
[ "https://security.meta.stackexchange.com/questions/897", "https://security.meta.stackexchange.com", "https://security.meta.stackexchange.com/users/414/" ]
It's not hard to come up with a real question that's not too localized, that is clearly only for black hat purposes and in my opinion should get deleted. For example: > > **How do I do an ARP Spoofing Attack**: I'm trying to steal my neighbors passwords/credit card numbers. I set up a fake version of a popular shopping website and I can connect on their open wifi network. I think I could do something like ARP spoofing or something to redirect them to my fake site. It would be very appreciated if someone could give me a clear tutorial on how to carry out these attacks or suggest tools or other attacks that will do this for me. > > > Compare to a similar, but perfectly valid question on the same topic: > > **What is the threat from ARP Spoofing:** How are the attacks done and what can I do to safeguard myself from them?" > > > I would expect stupid answers to the first question posting links to kiddie hacker scripts with little to no explanation of what's going on so being of no use to white hats, but being immediately useful to kiddie black hats. I wouldn't expect answers to the second question to be such low quality. Instead, I'd expect them to explain the threat (what is ARP, how does level-2 routing work) and ways to prevent it (e.g., secure the wifi network, use https and other secure protocols). The difference is subtle, but I believe quite important. We shouldn't deliberately assist black hats or people doing blind penetration tests (that cannot be in any way differentiated from black hats). Personally, I would like something to that effect to be present in the rules; otherwise we run the risk of doing [illegal things](http://stackexchange.com/legal/content-policy) in some jurisdictions, though I am not a lawyer. (Does suggesting ways for someone to do a successful SQL injection attack on a specific application count as abetting a criminal?) You should not ask questions asking for assistance in doing illegal activities like breaking into a system you do not have permission to use, or searching for exploits in an web application that you did not write and do not have the source code for and we have no way of knowing if the web application's owners have given you permission to legally evaluate its security. However, it is encouraged to ask and answer generic questions about various types of attacks, essentially in the context of how do the attacks work and how to best prevent them from occurring on your systems. A general guideline of questions and answers should be whether this question could be useful to a white hat (e.g., not automated kiddie hacking scripts), but a description of weaknesses in certain weak methods and how they should be fixed. --- Long edit in response to Gilles: My claim is that "too localized" and "not a real question" will not capture all black hat questions. NaRQ can usually be avoided with clear language focused a specific aspect of an attack. Localization can be avoided by asking about an attack relevant to many computers/situations. (And in any case many too localized attacks are less localized than highly-upvoted questions like ["I just discovered major security flaws in my web store"](https://security.stackexchange.com/questions/5701/i-just-discovered-major-security-flaws-in-my-web-store) ). I have no problem erring on the side of explaining principles behind an attack to increase the knowledge for defensive measures. Yes, resources on the internet exist for black hats with tools and tutorials, but we don't have to be one of them (asking specific questions could be quite useful to script kiddies even if the knowledge exists elsewhere). I don't think my belief is unique: let's look at other parts of the four of the five quotes you gave (Graham Lee's answer did want to allow any question asking about how to build malware without regard to intention): * [rox0r - 'why risk losing legitimate users/conent'](https://security.meta.stackexchange.com/a/130/2568) "Asking for exploits against a specific person (company) are banned" while "illustrating auth attacks and weakness should be discussed. Malware construction questions are out of scope." * [Dave - "exploit code ... should be expected!"](https://security.meta.stackexchange.com/a/193/2568) "banning questions that ask for exploit code only"; "encouraging answers that provide solutions with the attack that caused the vulnerability". * [Avid - 'It's ... valid ... to be asking about the attack, exploit ...'](https://security.meta.stackexchange.com/a/294/2568) At some point, we need to rely on human sense - our collective noses for what is hinky". [Elsewhere Avid said](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware#comment12_15): [We should be] 'explaining principles, so as to better protect against [malware/exploits] rather than providing food for script kiddies.' * [ninefingers - 'There is ... only shades of gray'](https://security.meta.stackexchange.com/a/297/2568) "its a subjective call". "Pretty much the same question, but looks totally different in terms of intent. If I were to draw the line in the sand, I would say the key in my version would be that you're coming at it from a defence angle too." These all seem to agree that intent is important; and the belief that black hat useful only questions/answers should be against our policies. This is not an academic issue that only exists for trick questions. There have been mod-removed questions that specifically asked how do I do some black hat activity (e.g., [how to exploit windows 7 remotely](https://security.stackexchange.com/questions/1444/windows-7-exploited-remotely) ) that were not too localized and easily could have been phrased as a real question. Another example is ["How can I check whether it's SQL injection? How can I exploit it? I don't have access to the source code but can query it with more requests."](https://security.stackexchange.com/revisions/13997acf-e211-471b-9674-486b0e6500a5/view-source). I think questions like that (part of an attack or blackbox pen test) should be deleted, not edited into something [resembling a legitimate question](https://security.stackexchange.com/questions/18663/how-to-make-sql-injection-in-postgresqls-tsquery). I have no problem with a quite similar question (possibly from a gray/white box pen test) saying "the PHP source code executing the SQL query says `pg_query_params($dbconn, 'SELECT * from text_table where plainto_tsquery($1) ', array($user_input);` and gives error messages like ... is this vulnerable to SQL injection?". This is perfectly fine as it will be useful to know if you have to fix your weak source code (despite being more localized). Note, the original version of the question had mod-removed answers that basically said "try running this set of SQL injection kiddie scripts". How about something along the lines of > > This site is not intended to be a resource for black hats to ask for assistance in implementing attacks (or doing blackbox penetration tests that simulate a black hat attack). That said educational discussion of insecure practices, including demonstrating example code that bypasses weak security practices is encouraged to enlighten everyone on how to best defend your system against existing attacks. While we prefer to err on the side of more disclosure, questions and answers that focus exclusively on implementation of black hat attacks may be moderated. > > >
It is the intent that matters. More often than not, you can tell with reasonable accuracy whether the poster is looking for help to do bad stuff or just trying to find vulnerabilities for purposes of system hardening. To paraphrase Justice Stewart, I may not be able to define black-hat questions, but I knows it when I sees it. In other words, the only blanket rule you can make is *don’t ask for help to do bad stuff*, short of that, simply use provided the moderation tools (voting, flagging, closing, etc.) to deal with questions on a case by cases basis as necessary. (You may think that this creates extra, unnecessary work, but the fact is that regardless of what it says in the rules page, bad guys—especially the less smarterier ones—will post anyway and create that same work anyway.)
897
In the [site FAQ](https://security.stackexchange.com/faq), it is written: > > Black Hat vs White Hat - This site is not intended to be a resource for Black Hats, or malicious hackers. While we understand discussion of exploits may require examples, if the question looks too much like a request for attack tools or mechanisms to spread a virus, it may be moderated. > > > I don't think this reflects our stance on black hat topics very well. The assertion that “This site is not intended to be a resource for Black Hats” seems to be saying that any discussion of black hat *topics* (attacks, exploits, etc.) is forbidden. Furthermore, while the text actually doesn't say so, it looks like all questions of attack tools or mechanisms to spread viruses are forbidden. The outcome of meta discussions [1](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware) [2](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code) [3](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats) [4](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat) is rather that broadly speaking, we don't discriminate against black hat content. Quoting from some of the answers with high upvotes on these threads: * Should we accept question about making exploit or building malware ? “[I say we should allow such questions](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware/22#22)” * [why even risk losing legitimate users and content?](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/130#130) * [exploit code should not only be allowed, it should be expected!](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/193#193) * [It's perfectly valid, even in a whitehat PoV, to be asking only about the attack, exploit, vector, payload, whatever.](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats/294#294) * “[There is no such thing as black and white, only shades of gray.](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat/297#297)” We should clarify the FAQ to make it clear that discussions of attacks and exploits is on-topic on this site. We should replace the paragraph quoted above by one that reflects the policies that are effectively applied and the kind of bad content that we want to feel justified in removing. The script kiddie content can pretty much be moderated by the usual Stack Exchange rules. Things like “How do I hack www.example.com?” or “Join me in a DDoS!” can be closed as [not a real question](https://security.stackexchange.com/faq#close). I would appreciate input from moderators regarding past questions that have been deleted for some black hat-related reason and that were not close-worthy under the general Stack Exchange rules. I propose to start with this: > > Black Hat vs White Hat: Discussions of attacks and exploits are allowed within reason. We adhere to responsible disclosure rules, > > > What else do we need to say?
2012/08/10
[ "https://security.meta.stackexchange.com/questions/897", "https://security.meta.stackexchange.com", "https://security.meta.stackexchange.com/users/414/" ]
I think the biggest problem in the security industry right now is that there are too many stuck up whitehats that are expected to break the exploitation process when they themselves have never written an exploit. So in the realm of security, making any topic taboo makes the process of learning into a vulnerability. After all a blackhat might ask a question where we all learn somthing, \*\* **gasp** \*\*... I am a whitehat, in that I have never Illegally broken into a system and I am paid to prevent such behavior. That being said [I enjoy writing exploits](http://www.exploit-db.com/author/?a=628) and I think that full disclosure is a useful tool if the vendor is not cooperative. This behavior is legal, at least in the US. Blackhats must be able to solve difficult, intellectual problems in order to be successful, and for that they have my respect. Very few people on the planet can grasp such problems. If anyone is able to ask an interesting question and I am able to provide an answer I will do so. By not providing an answer to a potential blackhat, I don't believe that the internet is a "safer place". After all this community is the sole provider of such information. I will not answer questions like "How do I hack a facebook account" or other such nonsense. I think that the community is uniformly against such questions. If the OP isn't willing to put in the effort to climb the mountain of information that makes up modern security then I am not willing guide that person through the difficult terrain.
After several discussions in chat, most notably ones involving @Gilles, I've learned a couple key points. To sum up, these add up to say that any truly undesirable or inappropriate "black hat" questions should already be getting handled per existing StackExchange policies. **For the TL;DR version, jump to the bolded paragraph at the end.** * Any post that appears deliberately aimed at facilitating malicious and/or illegal activity runs afoul of the StackExchange [Terms of Service](http://stackexchange.com/legal/terms-of-service). Particularly, these pieces of Section 4, "Restrictions" (emphasis mine): > > ... ***Any fraudulent, abusive, or > otherwise illegal activity*** or any use of the Services or Content in > violation of this Agreement ***may be grounds for termination of > Subscriber’s right to Services or to access the Network***. > > > ... > > ***Use of the Network or Services to violate the security of any computer network, crack passwords or security encryption codes,*** > transfer or store illegal material including that are deemed > threatening or obscene, ***or engage in any kind of illegal activity > is expressly prohibited.*** ... > > > * Most (if not all) other undesirable or inappropriate "black hat" questions should already be getting closed per the regular close reasons. Particularly: **Not Constructive**, **Not a Real Question**, or **Too Localized**. Off-Topic should not be used, because "black hat" in general is *not* off-topic. So, for the purposes of *setting* policy, nothing really needs to be added to the FAQ - in fact, the existing section could be removed and our policy would still be the same. However, for the sake of emphasizing our position against the *knowing* facilitation of illegal conduct, there *should* be something in the FAQ to re-iterate or paraphrase the relevant portions in the ToS. Perhaps the existing section could use a thorough re-write, but it should not be done without. Throughout all these discussions, I came to form an analogy of our community's situation to that of a responsible gun store owner who is operating in a jurisdiction that protects the right to keep and bear arms. **As responsible citizens who are in the business of "selling weapons", we should happily "sell" our "weapons" to anyone - regardless of their intent - up until the point that we actually have a reasonable suspicion (or, and especially, confession) that their intent is malicious and/or illegal. After that point, and *only* after that point, it is our ethical responsibility to refuse the "sale".**
897
In the [site FAQ](https://security.stackexchange.com/faq), it is written: > > Black Hat vs White Hat - This site is not intended to be a resource for Black Hats, or malicious hackers. While we understand discussion of exploits may require examples, if the question looks too much like a request for attack tools or mechanisms to spread a virus, it may be moderated. > > > I don't think this reflects our stance on black hat topics very well. The assertion that “This site is not intended to be a resource for Black Hats” seems to be saying that any discussion of black hat *topics* (attacks, exploits, etc.) is forbidden. Furthermore, while the text actually doesn't say so, it looks like all questions of attack tools or mechanisms to spread viruses are forbidden. The outcome of meta discussions [1](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware) [2](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code) [3](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats) [4](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat) is rather that broadly speaking, we don't discriminate against black hat content. Quoting from some of the answers with high upvotes on these threads: * Should we accept question about making exploit or building malware ? “[I say we should allow such questions](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware/22#22)” * [why even risk losing legitimate users and content?](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/130#130) * [exploit code should not only be allowed, it should be expected!](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/193#193) * [It's perfectly valid, even in a whitehat PoV, to be asking only about the attack, exploit, vector, payload, whatever.](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats/294#294) * “[There is no such thing as black and white, only shades of gray.](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat/297#297)” We should clarify the FAQ to make it clear that discussions of attacks and exploits is on-topic on this site. We should replace the paragraph quoted above by one that reflects the policies that are effectively applied and the kind of bad content that we want to feel justified in removing. The script kiddie content can pretty much be moderated by the usual Stack Exchange rules. Things like “How do I hack www.example.com?” or “Join me in a DDoS!” can be closed as [not a real question](https://security.stackexchange.com/faq#close). I would appreciate input from moderators regarding past questions that have been deleted for some black hat-related reason and that were not close-worthy under the general Stack Exchange rules. I propose to start with this: > > Black Hat vs White Hat: Discussions of attacks and exploits are allowed within reason. We adhere to responsible disclosure rules, > > > What else do we need to say?
2012/08/10
[ "https://security.meta.stackexchange.com/questions/897", "https://security.meta.stackexchange.com", "https://security.meta.stackexchange.com/users/414/" ]
I think the biggest problem in the security industry right now is that there are too many stuck up whitehats that are expected to break the exploitation process when they themselves have never written an exploit. So in the realm of security, making any topic taboo makes the process of learning into a vulnerability. After all a blackhat might ask a question where we all learn somthing, \*\* **gasp** \*\*... I am a whitehat, in that I have never Illegally broken into a system and I am paid to prevent such behavior. That being said [I enjoy writing exploits](http://www.exploit-db.com/author/?a=628) and I think that full disclosure is a useful tool if the vendor is not cooperative. This behavior is legal, at least in the US. Blackhats must be able to solve difficult, intellectual problems in order to be successful, and for that they have my respect. Very few people on the planet can grasp such problems. If anyone is able to ask an interesting question and I am able to provide an answer I will do so. By not providing an answer to a potential blackhat, I don't believe that the internet is a "safer place". After all this community is the sole provider of such information. I will not answer questions like "How do I hack a facebook account" or other such nonsense. I think that the community is uniformly against such questions. If the OP isn't willing to put in the effort to climb the mountain of information that makes up modern security then I am not willing guide that person through the difficult terrain.
It seems to me that there is quite a bit of time wasted on the assumption that people on here (whitehat, blackhat, grey, yellow...) are actually telling the truth about who they are. Honestly, when I read a question I skim over personal details and all the 'fluff' just to figure out what the actual question or answer is -from an objective perspective. In fact, I many times edit posts to *remove* that fluff just so they can be received equally and not judged on some ancillary detail (Like "my mother is..." or " I am a ransomeware author...") that doesnt add value to the post itself. While this debate over the stance is useful from a philosophical perspective, it is moot in that we cannot reasonably determine if posters are who they say they are. That being the case, why bother getting all flustered about it. Just take posts at face value. My suggestion would be to (1) add verbage in the policies that encourage objectivity in posting, (2) actively edit posts to remove subjective details -especially credentials that cannot be verified, and (3) encourage users to be tolerant of offensive posts.
897
In the [site FAQ](https://security.stackexchange.com/faq), it is written: > > Black Hat vs White Hat - This site is not intended to be a resource for Black Hats, or malicious hackers. While we understand discussion of exploits may require examples, if the question looks too much like a request for attack tools or mechanisms to spread a virus, it may be moderated. > > > I don't think this reflects our stance on black hat topics very well. The assertion that “This site is not intended to be a resource for Black Hats” seems to be saying that any discussion of black hat *topics* (attacks, exploits, etc.) is forbidden. Furthermore, while the text actually doesn't say so, it looks like all questions of attack tools or mechanisms to spread viruses are forbidden. The outcome of meta discussions [1](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware) [2](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code) [3](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats) [4](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat) is rather that broadly speaking, we don't discriminate against black hat content. Quoting from some of the answers with high upvotes on these threads: * Should we accept question about making exploit or building malware ? “[I say we should allow such questions](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware/22#22)” * [why even risk losing legitimate users and content?](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/130#130) * [exploit code should not only be allowed, it should be expected!](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/193#193) * [It's perfectly valid, even in a whitehat PoV, to be asking only about the attack, exploit, vector, payload, whatever.](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats/294#294) * “[There is no such thing as black and white, only shades of gray.](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat/297#297)” We should clarify the FAQ to make it clear that discussions of attacks and exploits is on-topic on this site. We should replace the paragraph quoted above by one that reflects the policies that are effectively applied and the kind of bad content that we want to feel justified in removing. The script kiddie content can pretty much be moderated by the usual Stack Exchange rules. Things like “How do I hack www.example.com?” or “Join me in a DDoS!” can be closed as [not a real question](https://security.stackexchange.com/faq#close). I would appreciate input from moderators regarding past questions that have been deleted for some black hat-related reason and that were not close-worthy under the general Stack Exchange rules. I propose to start with this: > > Black Hat vs White Hat: Discussions of attacks and exploits are allowed within reason. We adhere to responsible disclosure rules, > > > What else do we need to say?
2012/08/10
[ "https://security.meta.stackexchange.com/questions/897", "https://security.meta.stackexchange.com", "https://security.meta.stackexchange.com/users/414/" ]
It seems to me that there is quite a bit of time wasted on the assumption that people on here (whitehat, blackhat, grey, yellow...) are actually telling the truth about who they are. Honestly, when I read a question I skim over personal details and all the 'fluff' just to figure out what the actual question or answer is -from an objective perspective. In fact, I many times edit posts to *remove* that fluff just so they can be received equally and not judged on some ancillary detail (Like "my mother is..." or " I am a ransomeware author...") that doesnt add value to the post itself. While this debate over the stance is useful from a philosophical perspective, it is moot in that we cannot reasonably determine if posters are who they say they are. That being the case, why bother getting all flustered about it. Just take posts at face value. My suggestion would be to (1) add verbage in the policies that encourage objectivity in posting, (2) actively edit posts to remove subjective details -especially credentials that cannot be verified, and (3) encourage users to be tolerant of offensive posts.
It is the intent that matters. More often than not, you can tell with reasonable accuracy whether the poster is looking for help to do bad stuff or just trying to find vulnerabilities for purposes of system hardening. To paraphrase Justice Stewart, I may not be able to define black-hat questions, but I knows it when I sees it. In other words, the only blanket rule you can make is *don’t ask for help to do bad stuff*, short of that, simply use provided the moderation tools (voting, flagging, closing, etc.) to deal with questions on a case by cases basis as necessary. (You may think that this creates extra, unnecessary work, but the fact is that regardless of what it says in the rules page, bad guys—especially the less smarterier ones—will post anyway and create that same work anyway.)
897
In the [site FAQ](https://security.stackexchange.com/faq), it is written: > > Black Hat vs White Hat - This site is not intended to be a resource for Black Hats, or malicious hackers. While we understand discussion of exploits may require examples, if the question looks too much like a request for attack tools or mechanisms to spread a virus, it may be moderated. > > > I don't think this reflects our stance on black hat topics very well. The assertion that “This site is not intended to be a resource for Black Hats” seems to be saying that any discussion of black hat *topics* (attacks, exploits, etc.) is forbidden. Furthermore, while the text actually doesn't say so, it looks like all questions of attack tools or mechanisms to spread viruses are forbidden. The outcome of meta discussions [1](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware) [2](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code) [3](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats) [4](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat) is rather that broadly speaking, we don't discriminate against black hat content. Quoting from some of the answers with high upvotes on these threads: * Should we accept question about making exploit or building malware ? “[I say we should allow such questions](https://security.meta.stackexchange.com/questions/14/should-we-accept-question-about-making-exploit-or-building-malware/22#22)” * [why even risk losing legitimate users and content?](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/130#130) * [exploit code should not only be allowed, it should be expected!](https://security.meta.stackexchange.com/questions/117/should-we-allow-questions-answers-that-appear-to-include-or-request-exploit-code/193#193) * [It's perfectly valid, even in a whitehat PoV, to be asking only about the attack, exploit, vector, payload, whatever.](https://security.meta.stackexchange.com/questions/290/how-do-we-provide-value-to-white-and-grey-hats/294#294) * “[There is no such thing as black and white, only shades of gray.](https://security.meta.stackexchange.com/questions/296/what-determines-if-a-question-should-be-considered-blackhat/297#297)” We should clarify the FAQ to make it clear that discussions of attacks and exploits is on-topic on this site. We should replace the paragraph quoted above by one that reflects the policies that are effectively applied and the kind of bad content that we want to feel justified in removing. The script kiddie content can pretty much be moderated by the usual Stack Exchange rules. Things like “How do I hack www.example.com?” or “Join me in a DDoS!” can be closed as [not a real question](https://security.stackexchange.com/faq#close). I would appreciate input from moderators regarding past questions that have been deleted for some black hat-related reason and that were not close-worthy under the general Stack Exchange rules. I propose to start with this: > > Black Hat vs White Hat: Discussions of attacks and exploits are allowed within reason. We adhere to responsible disclosure rules, > > > What else do we need to say?
2012/08/10
[ "https://security.meta.stackexchange.com/questions/897", "https://security.meta.stackexchange.com", "https://security.meta.stackexchange.com/users/414/" ]
After several discussions in chat, most notably ones involving @Gilles, I've learned a couple key points. To sum up, these add up to say that any truly undesirable or inappropriate "black hat" questions should already be getting handled per existing StackExchange policies. **For the TL;DR version, jump to the bolded paragraph at the end.** * Any post that appears deliberately aimed at facilitating malicious and/or illegal activity runs afoul of the StackExchange [Terms of Service](http://stackexchange.com/legal/terms-of-service). Particularly, these pieces of Section 4, "Restrictions" (emphasis mine): > > ... ***Any fraudulent, abusive, or > otherwise illegal activity*** or any use of the Services or Content in > violation of this Agreement ***may be grounds for termination of > Subscriber’s right to Services or to access the Network***. > > > ... > > ***Use of the Network or Services to violate the security of any computer network, crack passwords or security encryption codes,*** > transfer or store illegal material including that are deemed > threatening or obscene, ***or engage in any kind of illegal activity > is expressly prohibited.*** ... > > > * Most (if not all) other undesirable or inappropriate "black hat" questions should already be getting closed per the regular close reasons. Particularly: **Not Constructive**, **Not a Real Question**, or **Too Localized**. Off-Topic should not be used, because "black hat" in general is *not* off-topic. So, for the purposes of *setting* policy, nothing really needs to be added to the FAQ - in fact, the existing section could be removed and our policy would still be the same. However, for the sake of emphasizing our position against the *knowing* facilitation of illegal conduct, there *should* be something in the FAQ to re-iterate or paraphrase the relevant portions in the ToS. Perhaps the existing section could use a thorough re-write, but it should not be done without. Throughout all these discussions, I came to form an analogy of our community's situation to that of a responsible gun store owner who is operating in a jurisdiction that protects the right to keep and bear arms. **As responsible citizens who are in the business of "selling weapons", we should happily "sell" our "weapons" to anyone - regardless of their intent - up until the point that we actually have a reasonable suspicion (or, and especially, confession) that their intent is malicious and/or illegal. After that point, and *only* after that point, it is our ethical responsibility to refuse the "sale".**
It is the intent that matters. More often than not, you can tell with reasonable accuracy whether the poster is looking for help to do bad stuff or just trying to find vulnerabilities for purposes of system hardening. To paraphrase Justice Stewart, I may not be able to define black-hat questions, but I knows it when I sees it. In other words, the only blanket rule you can make is *don’t ask for help to do bad stuff*, short of that, simply use provided the moderation tools (voting, flagging, closing, etc.) to deal with questions on a case by cases basis as necessary. (You may think that this creates extra, unnecessary work, but the fact is that regardless of what it says in the rules page, bad guys—especially the less smarterier ones—will post anyway and create that same work anyway.)
198,400
This is improved code from my [previous question.](https://codereview.stackexchange.com/questions/195112/android-game-inspired-by-space-invaders-and-moon-patrol) This mini game which we call ["Moon Buggy" is available in beta](https://play.google.com/store/apps/details?id=dev.android.buggy) from the google playstore. [![enter image description here](https://i.stack.imgur.com/afLta.gif)](https://i.stack.imgur.com/afLta.gif) The action is that you control a vechicle on the moon and you defend yourself against evil UFO:s. I have written a separate class for the UFO which is instanciated once for every UFO. I have also created a separate class for the vehicle which we call the "moon rover" (might change the name of the game to "Moon Rover" possibly). **UFO.java** ``` public class UFO extends MoonSprite { private Bitmap ufoBitmap; //boolean to avoid multiple hits, switched in the beginning static boolean recent = true; private long changeDirections = System.currentTimeMillis(); private long fireTimeout = System.currentTimeMillis(); private int ufoY = 0; private int ufoX = 0; private int missileX = 25; private int deltaUfoY = 7; private int deltaUfoX = 7; private int missileOffSetY = 0; private int missileYstart = 0; private boolean wasHit = false; private boolean alienexplode; private boolean waitForTimer, waitForUfoTimer; private boolean toggleDeltaY = true; private boolean runOnce = true; protected UFO(Context context, String name, int deltaUfoY) { super(context, name); this.screenHeight = context.getResources().getDisplayMetrics().heightPixels; this.screenWidth = context.getResources().getDisplayMetrics().widthPixels; Log.d("dimensions", "dimensions " + this.screenHeight + " " + this.screenWidth); this.deltaUfoY = deltaUfoY; // the vertical velocity int ufoId = context.getResources().getIdentifier(name, "drawable", context.getPackageName()); ufoBitmap = BitmapFactory.decodeResource(context.getResources(), ufoId); ufoX = randomize((int) (0.8 * screenWidth), (int) (0.2 * screenWidth)); // missile starts at same coordinates as UFO missileX = ufoX; ufoY = 0; waitForUfoTimer = true; Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(() -> { missileX = ufoX; UFO.recent = false; waitForUfoTimer = false; }, randomize(20000, 18000)); } //not yet used. start from beginning if target or UFO is hit public void reset(Canvas canvas, Paint paint) { missileX = randomize((int) (0.75 * screenWidth), 20); ufoX = missileX; ufoY = 0; waitForUfoTimer = true; Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(() -> { missileX = ufoX; UFO.recent = false; waitForUfoTimer = false; }, randomize(20000, 18000)); } private void changeDirections() { if (System.currentTimeMillis() - changeDirections >= randomize(500, 100)) { // Change direction here toggleDeltaY = !toggleDeltaY; changeDirections = System.currentTimeMillis(); } } public void update(Canvas canvas, Paint paint, boolean toggleDeltaY) { // don't move outside the top. (0,0) is top left corner if(ufoY<0) { ufoY = 0; deltaUfoY = (int) Math.sqrt(deltaUfoY * deltaUfoY); // use the positive } if (ufoX > screenWidth - ufoBitmap.getWidth() || ufoX <= 0) { // UFO change horizontal direction deltaUfoX = -deltaUfoX; } //if missiles goes outside the screen lower part, update to new missile coordinates if (missileYstart + ufoBitmap.getHeight() + missileOffSetY >= screenHeight) { missileYstart = ufoY; missileX = ufoX; } //change directions after a while if (toggleDeltaY) { deltaUfoY = -deltaUfoY; } //make sure UFO does not move too low //(0,0) is top left corner if (ufoY >= (int) (0.2 * screenHeight)) { // why 0.2 ? deltaUfoY = - (int) Math.sqrt(deltaUfoY * deltaUfoY); // use the negative; } if (!waitForUfoTimer && MoonBackground.checkpoint >= 'A') { runOnce = true; canvas.drawBitmap(ufoBitmap, ufoX + 10, ufoY, paint); } ufoX = ufoX + deltaUfoX; if (waitForTimer) missileX = ufoX; ufoY = ufoY + deltaUfoY; changeDirections(); } public boolean checkBeingHit(int[] missiles, int buggyXDisplacement, double buggyXDistance, Canvas canvas, Bitmap explode2, Paint paint, int score, ParallaxView pview, int i1, int xbuggy2) { // if UFO is being hit by buggy if (!waitForTimer && java.lang.Math.abs(ufoX + 10 - 400 - buggyXDistance) * 2 < (ufoBitmap.getWidth()) && java.lang.Math.abs(ufoY - (screenHeight / 100 * 95 - missiles[i1] - xbuggy2)) * 2 < (ufoBitmap.getHeight())) { missileOffSetY = -9999; canvas.drawBitmap(explode2, ufoX + 10, ufoY, paint); if (runOnce) { ParallaxView.score = ParallaxView.score + 100; Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(() -> { missileX = randomize((int) (0.75 * screenWidth), 20); ufoX = missileX; ufoY = 0; alienexplode = false; waitForTimer = false; waitForUfoTimer = false; }, 3000); } runOnce = false; waitForUfoTimer = true; waitForTimer = true; if (!alienexplode) { pview.changeText(); } alienexplode = true; return true; } else return false; } //return boolean if fire, boolean which is not yet used private boolean checkFire() { if (System.currentTimeMillis() - fireTimeout >= randomize(30000, 24000)) { // means how often the ufoBitmap fires fireTimeout = System.currentTimeMillis(); missileOffSetY = 0; missileX = ufoX; missileYstart = ufoY; return true; } else return false; } // if buggy was hit by a missile then return true private boolean checkBuggyHitByMissile(Canvas canvas, ParallaxView view, int buggyXDisplacement, double buggyXDistance, Paint paint, Bitmap buggy, int jumpHeight) { if (!UFO.recent && !view.waitForTimer && java.lang.Math.abs(((buggyXDisplacement + buggyXDistance) + buggy.getWidth() / 2) - (missileX + 10 + ufoBitmap.getWidth() / 2)) < buggy.getWidth() / 2 && java.lang.Math.abs((ufoY + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight + buggy.getHeight())) < 65) { UFO.recent = true; canvas.drawBitmap(view.explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - jumpHeight, paint); ParallaxView.bombed--; missileOffSetY = 0; wasHit = true; view.recent = true; Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(() -> { UFO.recent = false; waitForTimer = false; wasHit = false; }, 4500); waitForTimer = true; } else { // buggy was not hit so UFO fires more missiles if (!waitForTimer && !waitForUfoTimer && MoonBackground.checkpoint >= 'A') { canvas.drawText("●", missileX + ufoBitmap.getWidth() / 2 + 10, missileYstart + ufoBitmap.getHeight() + missileOffSetY, paint); missileOffSetY = missileOffSetY + 3; } wasHit = false; } return wasHit; } public boolean drawMissile(ParallaxView view, Canvas canvas, Paint paint, int buggyXDisplacement, double buggyXDistance, Bitmap buggy, int jumpHeight) { checkFire(); return checkBuggyHitByMissile(canvas, view, buggyXDisplacement, buggyXDistance, paint, buggy, jumpHeight); } } ``` **MoonRover.java** ``` public class MoonRover extends MoonSprite { public Bitmap getBitmapRover() { return bitmapRover; } private Bitmap bitmapRover, explode; public int getJumpHeight() { return jumpHeight; } public void setJumpHeight(int jumpHeight) { this.jumpHeight = jumpHeight; } private int jumpHeight; private double retardation = 0.5; private double buggyXdistance = 0; public double getBuggyXdistance() { return buggyXdistance; } public void setBuggyXdistance(double buggyXdistance) { this.buggyXdistance = buggyXdistance; } public void increaseBuggyXdistance(double d) { buggyXdistance = buggyXdistance + d; } public void decreaseBuggyXdistance(double d) { buggyXdistance = buggyXdistance - d; } public double getRetardation() { return retardation; } public void increaseRetardation(double d) { retardation = retardation + d; } public void setRetardation(double retardation) { this.retardation = retardation; } public double getDistanceDelta() { return distanceDelta; } public void setDistanceDelta(double distanceDelta) { this.distanceDelta = distanceDelta; } private double distanceDelta; protected MoonRover(Context context, String name) { super(context, name); this.screenHeight = context.getResources().getDisplayMetrics().heightPixels; this.screenWidth = context.getResources().getDisplayMetrics().widthPixels; int roverId = context.getResources().getIdentifier(name, "drawable", context.getPackageName()); bitmapRover = BitmapFactory.decodeResource(context.getResources(), roverId); int explodeId = context.getResources().getIdentifier("explode", "drawable", context.getPackageName()); explode = BitmapFactory.decodeResource(context.getResources(), explodeId); Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(new Runnable() { @Override public void run() { } }, randomize(20000, 18000)); } //if rover was hit by UFO missile then return true, false otherwise //not implemented yet public boolean isHit(UFO ufo) { boolean isHit = false; return isHit; } //if rover was hit by UFO missile, hits a moon rock or a hole, then explode for some time //and after a while reset to beginning of section public void explode(Canvas canvas, Paint paint, float left, float top) { canvas.drawBitmap(explode, left, top, paint); } //if rover fires a missile then draw the missile //not implemented yet public void fireMissile(Canvas canvas) { } public void draw(Canvas canvas, Paint paint, float left, float top) { canvas.drawBitmap(bitmapRover, left, top, paint); } //if rover jumps then draw the jumping rover public void jump(Canvas canvas, boolean up) { if (up && jumpHeight < 500) { jumpHeight = jumpHeight + 7; if (distanceDelta < 3) distanceDelta = distanceDelta + 0.55; } else if (jumpHeight > 0) { jumpHeight = jumpHeight - 4; if (distanceDelta < 3) distanceDelta = distanceDelta + 0.55; } } } ``` **ParallaxView.java** ``` public class ParallaxView extends SurfaceView implements Runnable, SurfaceHolder.Callback { static int bombed = 5; Rect fromRect1; Rect toRect1; Rect fromRect2; Rect toRect2; boolean waitForTimer = false; boolean recent = false; boolean increment = false; boolean toggleDeltaY = true; boolean toggleGround = true; boolean jump = false; boolean shoot = false; boolean checkpointComplete = false; boolean runOnce = true; boolean passed = false; boolean donotdrawBuggy = false; // keep track of whether to not draw anything at all during the wait between being bombed and getting a new life final int buggyXDisplacement = 450; int numberOfshots = 0; // change to 0 int[] missiles = new int[200]; /* int alienBombYDelta = 0; int alienBombYDelta2 = 0; int alienBombXDelta = 20; int alienBombXDelta2 = 30;*/ int p = 7; int p2 = 13; int index = 0; int missileOffSetY = 0; int jumpHeight = 0; int xbuggy2 = 0; int craterX = -550; long lastTurn2 = System.currentTimeMillis(); long lastTurn3 = System.currentTimeMillis(); TextView tvId1; int sectionComplete = 0; static int score = 0; double lastTurn4 = System.currentTimeMillis(); List<MoonBackground> backgrounds; List<UFO> ufos; int moondRockSmallId, resID, explodeID, explodeID2, alienResID2; private volatile boolean running; private Thread gameThread = null; Bitmap explode, alien, alien2, explode2, spacerock, spacerock3, spacerock2, hole; TextView tvId; TextView checkpointtextview; TextView checkpointtextview2; TextView checkpointtextview3; TextView checkpointtextview4; TextView checkpointtextview5; TextView checkpointtextview6; // For drawing private Paint paint; private Canvas canvas; private SurfaceHolder ourHolder; UFO alien3; UFO alien4; UFO alien5; // Holds a reference to the Activity Context context; ScreenDimension screenDimension; // Control the fps long fps = 60; MoonRover moonRover; // Screen resolution int screenWidth; int screenHeight; boolean bexplode = false; boolean brake = false; boolean scoring = false; public MoonRover getMoonRover() { return moonRover; } // use Handler instead class SetRecent extends TimerTask { public void run() { recent = false; } } // use Handler instead class ResetCheckpoint extends TimerTask { public void run() { Log.d("## sectionComplete", "sectionComplete " + sectionComplete); if (sectionComplete == 0) MoonBackground.checkpoint = 'A'; if (sectionComplete == 1) MoonBackground.checkpoint = 'F'; if (sectionComplete == 2) MoonBackground.checkpoint = 'K'; if (sectionComplete == 3) MoonBackground.checkpoint = 'P'; } } public void surfaceCreated(SurfaceHolder holder) { //Canvas c = getHolder().lockCanvas(); //draw(); //getHolder().unlockCanvasAndPost(c); } public void surfaceDestroyed(SurfaceHolder holder3) { //Canvas c = getHolder().lockCanvas(); //draw(); //getHolder().unlockCanvasAndPost(c); } public void surfaceChanged(SurfaceHolder holder, int i1, int i2, int i3) { //Canvas c = getHolder().lockCanvas(); //draw(); //getHolder().unlockCanvasAndPost(c); } private void update() { // Update all the background positions for (MoonBackground bg : backgrounds) { bg.update(fps); } } public ParallaxView(Context c, AttributeSet a) { super(c, a); this.context = c; MoonBackground.checkpoint--; // why? this.screenWidth = getContext().getResources().getDisplayMetrics().widthPixels; this.screenHeight = getContext().getResources().getDisplayMetrics().heightPixels; screenDimension = new ScreenDimension(getContext().getResources().getDisplayMetrics().widthPixels, getContext().getResources().getDisplayMetrics().heightPixels); // Initialize our drawing objects ourHolder = getHolder(); paint = new Paint(); // Initialize our arraylist backgrounds = new ArrayList<>(); //load the background data into the MoonBackground objects and // place them in our GameObject arraylist backgrounds.add(new MoonBackground( this.context, screenWidth, screenHeight, "bg", 0, 120, 50)); backgrounds.add(new MoonBackground( this.context, screenWidth, screenHeight, "grass", 70, 110, 200)); //Log.d("Timer", "Timer "); resID = context.getResources().getIdentifier("vehicle", "drawable", context.getPackageName()); explodeID = context.getResources().getIdentifier("explode", "drawable", context.getPackageName()); explodeID2 = context.getResources().getIdentifier("explode2", "drawable", context.getPackageName()); moondRockSmallId = context.getResources().getIdentifier("spacerock", "drawable", context.getPackageName()); int spacerock2i = context.getResources().getIdentifier("rock2_hdpi", "drawable", context.getPackageName()); int spacerock3i = context.getResources().getIdentifier("rock3_hdpi", "drawable", context.getPackageName()); int holeid = context.getResources().getIdentifier("hole", "drawable", context.getPackageName()); //buggy = BitmapFactory.decodeResource(context.getResources(), resID); explode = BitmapFactory.decodeResource(context.getResources(), explodeID); explode2 = BitmapFactory.decodeResource(context.getResources(), explodeID2); spacerock = BitmapFactory.decodeResource(context.getResources(), moondRockSmallId); spacerock2 = BitmapFactory.decodeResource(context.getResources(), spacerock2i); spacerock3 = BitmapFactory.decodeResource(context.getResources(), spacerock3i); alienResID2 = context.getResources().getIdentifier("right_side_hdpi", "drawable", context.getPackageName()); int alienResID3 = context.getResources().getIdentifier("spaceship2_hdpi", "drawable", context.getPackageName()); alien = BitmapFactory.decodeResource(context.getResources(), alienResID2); alien2 = BitmapFactory.decodeResource(context.getResources(), alienResID3); hole = BitmapFactory.decodeResource(context.getResources(), holeid); alien3 = new UFO(context, "spaceship2_hdpi", 1); alien4 = new UFO(context, "spaceship3_hdpi", 2); alien5 = new UFO(context, "right_side_hdpi", 3); // Initialize our array list ufos = new ArrayList<>(); ufos.add(alien3); ufos.add(alien4); ufos.add(alien5); moonRover = new MoonRover(context, "vehicle"); } @Override public void run() { while (running) { long startFrameTime = System.currentTimeMillis(); update(); draw(); // Calculate the fps this frame long timeThisFrame = System.currentTimeMillis() - startFrameTime; if (timeThisFrame >= 1) { fps = 1000 / timeThisFrame; } } } private void checkJump() { if (System.currentTimeMillis() - lastTurn3 >= 650) { // 650 means how long the vehicle is in the air at a jump // Change direction here jump = false; lastTurn3 = System.currentTimeMillis(); } } private void drawShots() { for (int i1 = 0; i1 < numberOfshots; i1++) { if (shoot) { canvas.drawText("o", (float) (missiles[i1] + moonRover.getBuggyXdistance() + 450), (float) (screenHeight * 0.7) - moonRover.getJumpHeight(), paint); // add to y the jump height canvas.drawText("o", (float) (moonRover.getBuggyXdistance() + 185 + 400), screenHeight / 110 * 95 - missiles[i1] - xbuggy2, paint); } if (i1 == numberOfshots - 1 && missiles[i1] > screenWidth) { if (numberOfshots > 0) numberOfshots--; if (index > 0) index--; } } } //use a Handler instead private void changeDirections() { if (System.currentTimeMillis() - lastTurn2 >= 7000) { // Change direction here toggleDeltaY = !toggleDeltaY; lastTurn2 = System.currentTimeMillis(); } } //try to improve this private void controlVelocity() { if (!brake && moonRover.getBuggyXdistance() > 0) { moonRover.increaseBuggyXdistance(moonRover.getDistanceDelta()); } else if (brake && moonRover.getBuggyXdistance() > 0) { moonRover.decreaseBuggyXdistance(moonRover.getRetardation()); } } private void makeShots() { for (int n = 0; n < numberOfshots; n++) missiles[n] = missiles[n] + 20; } public void changeText() { if (scoring) { ((Activity) this.getContext()).runOnUiThread(() -> { String str = "Player 1 " + String.format("%06d", score); tvId.setText(str); scoring = false; }); } } //change to handler private void checkFire() { if (System.currentTimeMillis() - lastTurn4 >= 118500) { // it means how often the alien fires lastTurn4 = System.currentTimeMillis(); missileOffSetY = 0; } } private void draw() { if (moonRover.getRetardation() > 0.5) { moonRover.setDistanceDelta(0); } if (moonRover.getDistanceDelta() > 0) //why? moonRover.setRetardation(0.5); if (ourHolder.getSurface().isValid()) { //First we lock the area of memory we will be drawing to canvas = ourHolder.lockCanvas(); if (checkpointComplete) { canvas.drawColor(Color.BLACK); ((ParallaxActivity) getContext()).stopWatch.stop(); paint.setTextSize(60); String s2 = "TIME TO REACH POINT \"" + MoonBackground.checkpoint + "\"\n"; if (runOnce) { for (int q = 0; q < s2.length(); q++) { final String s2f = s2; final int r = q; ((Activity) this.getContext()).runOnUiThread(() -> { checkpointtextview.setTextColor(Color.RED); checkpointtextview.append(Character.toString(s2f.charAt(r))); }); try { Thread.sleep(50); } catch (InterruptedException ie) { } } } String str = String.format("%03d", ((ParallaxActivity) this.getContext()).countUp); String s3 = "YOUR TIME : " + str; if (runOnce) { for (int q = 0; q < s3.length(); q++) { final String s3f = s3; final int r = q; ((Activity) this.getContext()).runOnUiThread(() -> { checkpointtextview2.setTextColor(Color.parseColor("#ADD8E6")); checkpointtextview2.append(Character.toString(s3f.charAt(r))); }); try { Thread.sleep(50); } catch (InterruptedException ie) { } } } String s4 = "THE AVERAGE TIME : 060"; if (runOnce) { for (int q = 0; q < s4.length(); q++) { final String s4f = s4; final int r = q; ((Activity) this.getContext()).runOnUiThread(() -> { checkpointtextview3.setTextColor(Color.parseColor("#ADD8E6")); checkpointtextview3.append(Character.toString(s4f.charAt(r))); }); try { Thread.sleep(50); } catch (InterruptedException ie) { } } } String s5 = "TOP RECORD : 060"; if (runOnce) { for (int q = 0; q < s5.length(); q++) { final String s5f = s5; final int r = q; ((Activity) this.getContext()).runOnUiThread(() -> { checkpointtextview4.setTextColor(Color.RED); checkpointtextview4.append(Character.toString(s5f.charAt(r))); }); try { Thread.sleep(50); } catch (InterruptedException ie) { } } } String s6 = "GOOD BONUS POINTS : 1000"; if (runOnce) { for (int q = 0; q < s6.length(); q++) { final String s6f = s6; final int r = q; ((Activity) this.getContext()).runOnUiThread(() -> { checkpointtextview5.setTextColor(Color.RED); checkpointtextview5.append(Character.toString(s6f.charAt(r))); }); try { Thread.sleep(50); } catch (InterruptedException ie) { } } } if (runOnce) { score = score + 1000; sectionComplete++; recent = true; } runOnce = false; ((Activity) this.getContext()).runOnUiThread(new Runnable() { @Override public void run() { Handler handler = new Handler(); handler.postDelayed(() -> { ((ParallaxActivity) getContext()).startTime = SystemClock.elapsedRealtime(); ((ParallaxActivity) getContext()).stopWatch.setBase(((ParallaxActivity) getContext()).startTime); ((ParallaxActivity) getContext()).stopWatch.start(); checkpointtextview.setText(""); checkpointtextview2.setText(""); checkpointtextview3.setText(""); checkpointtextview4.setText(""); checkpointtextview5.setText(""); checkpointtextview6.setText(""); String str = "Player 1 " + String.format("%06d", score); tvId.setText(str); scoring = false; moonRover.setBuggyXdistance(0); moonRover.setDistanceDelta(0); moonRover.setRetardation(0); checkpointComplete = false; runOnce = true; }, 3000); } }); } else { if (bombed == 0) //GAME OVER { final int duration = Toast.LENGTH_SHORT; ((Activity) this.getContext()).runOnUiThread(new Runnable() { @Override public void run() { final Toast toast = Toast.makeText(context, "GAME OVER!\nScore: " + score, duration); toast.show(); Handler handler = new Handler(); handler.postDelayed(() -> { toast.cancel(); bombed = 5; score = 0; MoonBackground.checkpoint = 'A'; String str = "Player 1 " + String.format("%06d", score); tvId.setText(str); }, 3000); } }); } moonRover.jump(canvas, jump); if (shoot) { xbuggy2 = xbuggy2 + 4; } checkFire(); checkJump(); canvas.drawColor(Color.argb(255, 0, 0, 0)); // Draw the background parallax drawBackground(0); // Draw the rest of the game paint.setTextSize(60); paint.setColor(Color.argb(255, 255, 255, 255)); drawShots(); changeDirections(); for (UFO ufo : ufos) { ufo.update(canvas, paint, toggleDeltaY); } recent = alien3.drawMissile(this, canvas, paint, buggyXDisplacement, moonRover.getBuggyXdistance(), moonRover.getBitmapRover(), moonRover.getJumpHeight()); if (recent) { waitForTimer = true; bexplode = true; UFO.recent = true; } boolean recent2 = alien4.drawMissile(this, canvas, paint, buggyXDisplacement, moonRover.getBuggyXdistance(), moonRover.getBitmapRover(), moonRover.getJumpHeight()); if (recent || recent2) { recent = true; waitForTimer = true; bexplode = true; UFO.recent = true; } boolean recent3 = alien5.drawMissile(this, canvas, paint, buggyXDisplacement, moonRover.getBuggyXdistance(), moonRover.getBitmapRover(), moonRover.getJumpHeight()); //TODO: reset scenario after buggy being hit by UFO missile if (recent || recent2 || recent3) { recent = true; waitForTimer = true; bexplode = true; UFO.recent = true; new Timer().schedule(new SetRecent(), 10000); new Timer().schedule(new ResetCheckpoint(), 1000); Handler handler = new Handler(Looper.getMainLooper()); // this code runs after a while handler.postDelayed(new Runnable() { @Override public void run() { waitForTimer = false; bexplode = false; moonRover.setBuggyXdistance(0); Log.d("postDelayed", "postDelayed "); donotdrawBuggy = true; Handler handler2 = new Handler(Looper.getMainLooper()); handler2.postDelayed(new Runnable() { @Override public void run() { donotdrawBuggy = false; bexplode = false; Handler handler3 = new Handler(Looper.getMainLooper()); handler3.postDelayed(() -> { recent = false; UFO.recent = false; }, 2000); } }, 2000); } }, 2000); } //checkBuggyBombed(); for (int i1 = 0; i1 < numberOfshots; i1++) { alien3.checkBeingHit(missiles, buggyXDisplacement, moonRover.getBuggyXdistance(), canvas, explode2, paint, score, this, i1, xbuggy2); alien4.checkBeingHit(missiles, buggyXDisplacement, moonRover.getBuggyXdistance(), canvas, explode2, paint, score, this, i1, xbuggy2); alien5.checkBeingHit(missiles, buggyXDisplacement, moonRover.getBuggyXdistance(), canvas, explode2, paint, score, this, i1, xbuggy2); } drawBackground(1); // canvas.drawText("X", (float) (50 + buggyXDistance)+moonRover.getBitmapRover().getWidth()/2, (float) (screenHeight * 0.3) - jumpHeight+buggy.getHeight(), paint); paint.setTextSize(60); canvas.drawText("A E J O T Z", (float) (screenWidth * 0.7), (float) (screenHeight * 0.15), paint); // Prevent buggy from moving outside horizontal screen if (!brake && buggyXDisplacement + moonRover.getBuggyXdistance() > screenWidth - moonRover.getBitmapRover().getWidth() - 200) { //buggyXDistance = screenWidth - moonRover.getBitmapRover().getWidth() - 200; moonRover.setBuggyXdistance(screenWidth - moonRover.getBitmapRover().getWidth() - 200); } //Log.d("buggyXDistance", "buggyXDistance " + buggyXDistance); if (!donotdrawBuggy && !bexplode && !waitForTimer && !checkpointComplete) { moonRover.draw(canvas, paint, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight()); } else if (!donotdrawBuggy && bexplode && !checkpointComplete) { moonRover.explode(canvas, paint, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight()); moonRover.setDistanceDelta(0); moonRover.setRetardation(0); } int inc = 0; for (int i = 0; i < bombed; i++) { canvas.drawBitmap(Bitmap.createScaledBitmap(moonRover.getBitmapRover(), (int) (0.50 * (moonRover.getBitmapRover().getWidth() / 3)), (int) (0.50 * moonRover.getBitmapRover().getHeight() / 3), false), inc, 100, paint); inc = inc + getMoonRover().getBitmapRover().getWidth() / 4; } makeShots(); //updateDeltas(); controlVelocity(); } ourHolder.unlockCanvasAndPost(canvas); } } // Clean up our thread if the game is stopped public void pause() { running = false; try { gameThread.join(); } catch (InterruptedException e) { // Error //e.printStackTrace(); } } // Make a new thread and startMissile it // Execution moves to our run method public void resume() { running = true; gameThread = new Thread(this); gameThread.start(); } private void drawBackground(int position) { // Make a copy of the relevant background MoonBackground bg = backgrounds.get(position); // define what portion of images to capture and // what coordinates of screen to draw them at // For the regular bitmap fromRect1 = new Rect(0, 0, bg.width - bg.xClip, bg.height); toRect1 = new Rect(bg.xClip, bg.startY, bg.width, bg.endY); // For the reversed background fromRect2 = new Rect(bg.width - bg.xClip, 0, bg.width, bg.height); toRect2 = new Rect(0, bg.startY, bg.xClip, bg.endY); //draw the two background bitmaps if (!bg.reversedFirst) { if (MoonBackground.checkpoint != '@' && MoonBackground.checkpoint != 'E' && position == 1) { //canvas.drawBitmap(bg.bitmap, fromRect1, toRect1, paint); canvas.drawBitmap(bg.bitmap2, fromRect1, toRect1, paint); } else { canvas.drawBitmap(bg.bitmap, fromRect1, toRect1, paint); } canvas.drawBitmap(bg.bitmapReversed, fromRect2, toRect2, paint); if (MoonBackground.checkpoint != '@' && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'B' && bg.xClip <= 0) { // && position == 2) { canvas.drawBitmap(spacerock3, toRect1.left, toRect1.top, paint); } else if (MoonBackground.checkpoint != '@' && MoonBackground.checkpoint != 'A' && bg.xClip <= 0) { // && position == 2) { canvas.drawBitmap(spacerock2, toRect1.left, toRect1.top, paint); } else if (MoonBackground.checkpoint != '@' && bg.xClip <= 0) { // && position == 2) { canvas.drawBitmap(spacerock, toRect1.left, toRect1.top, paint); } if (position == 1) { paint.setTextSize(160); if (MoonBackground.checkpoint <= 'Z' && MoonBackground.checkpoint >= 'A') { canvas.drawText(Character.toString(MoonBackground.checkpoint), bg.xClip, (float) (bg.startY * 1.4), paint); } if (increment) { MoonBackground.checkpoint++; toggleGround = true; } if (MoonBackground.checkpoint == 'B' && (buggyXDisplacement + moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((buggyXDisplacement + moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < moonRover.getBitmapRover().getWidth()) { passed = true; } if (MoonBackground.checkpoint == 'E' && (buggyXDisplacement + moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((buggyXDisplacement + moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < moonRover.getBitmapRover().getWidth()) { checkpointComplete = true; toggleGround = false; canvas.drawColor(Color.BLACK); return; } else if (MoonBackground.checkpoint == 'J' && (buggyXDisplacement + moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((buggyXDisplacement + moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < moonRover.getBitmapRover().getWidth()) { checkpointComplete = true; canvas.drawColor(Color.BLACK); return; } else if (MoonBackground.checkpoint == 'O' && (buggyXDisplacement + moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((buggyXDisplacement + moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < moonRover.getBitmapRover().getWidth()) { checkpointComplete = true; canvas.drawColor(Color.BLACK); return; } else if (MoonBackground.checkpoint == 'T' && (buggyXDisplacement + moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((buggyXDisplacement + moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < moonRover.getBitmapRover().getWidth()) { checkpointComplete = true; canvas.drawColor(Color.BLACK); return; } else if (MoonBackground.checkpoint == 'Z' && (buggyXDisplacement + moonRover.getBuggyXdistance()) < (bg.xClip + 450) && java.lang.Math.abs((buggyXDisplacement + moonRover.getBuggyXdistance()) - (bg.xClip + 450)) < moonRover.getBitmapRover().getWidth()) { checkpointComplete = true; canvas.drawColor(Color.BLACK); return; } increment = false; if (bg.xClip == bg.width) increment = true; ((Activity) this.getContext()).runOnUiThread(new Runnable() { @Override public void run() { tvId1.setText(Character.toString(MoonBackground.checkpoint)); } }); } } else { if (MoonBackground.checkpoint != '@' && MoonBackground.checkpoint != 'E' && position == 1) canvas.drawBitmap(bg.bitmap2, fromRect2, toRect2, paint); else canvas.drawBitmap(bg.bitmap, fromRect2, toRect2, paint); canvas.drawBitmap(bg.bitmapReversed, fromRect1, toRect1, paint); if (MoonBackground.checkpoint != '@' && position == 1 && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'B' && MoonBackground.checkpoint != 'C' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z') { //if buggy collides with moon rock 3 if (!waitForTimer && !UFO.recent && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z' && MoonBackground.checkpoint != '@' && !recent && (buggyXDisplacement + moonRover.getBuggyXdistance()) < (bg.xClip) && java.lang.Math.abs((screenHeight * 0.5) - moonRover.getJumpHeight() - bg.startY) < 180 && java.lang.Math.abs((buggyXDisplacement + moonRover.getBuggyXdistance()) - (bg.xClip)) < moonRover.getBitmapRover().getWidth()) { canvas.drawBitmap(explode, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight(), paint); bombed--; recent = true; waitForTimer = true; bexplode = true; moonRover.explode(canvas, paint, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight()); moonRover.setDistanceDelta(1.15); moonRover.setRetardation(0.5); jumpHeight = 0; moonRover.setJumpHeight(0); ((Activity) this.getContext()).runOnUiThread(new Runnable() { @Override public void run() { Handler handler = new Handler(); handler.postDelayed(() -> { waitForTimer = false; moonRover.setBuggyXdistance(0); bexplode = false; }, 2000); } }); new Timer().schedule(new SetRecent(), 10000); new Timer().schedule(new ResetCheckpoint(), 1000); } canvas.drawBitmap(spacerock3, toRect1.left, toRect1.top, paint); } else if (MoonBackground.checkpoint != '@' && position == 1 && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'B' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z') { canvas.drawBitmap(spacerock2, toRect1.left, toRect1.top, paint); //if buggy collides with moon rock 2 if (!waitForTimer && !UFO.recent && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z' && MoonBackground.checkpoint != '@' && !recent && (buggyXDisplacement + moonRover.getBuggyXdistance()) < (bg.xClip) && java.lang.Math.abs((screenHeight * 0.5) - moonRover.getJumpHeight() - bg.startY) < 180 && java.lang.Math.abs((buggyXDisplacement + moonRover.getBuggyXdistance()) - (bg.xClip)) < moonRover.getBitmapRover().getWidth()) { // && java.lang.Math.abs((alienBombY + screenHeight / 100 * 25 + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight )) < 65) { //canvas.drawBitmap(explode, (float) (buggyXDisplacement + buggyXDistance), (float) (screenHeight * 0.5) - moonRover.getJumpHeight(), paint); moonRover.explode(canvas, paint, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight()); bombed--; recent = true; waitForTimer = true; bexplode = true; canvas.drawBitmap(explode, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight(), paint); moonRover.setDistanceDelta(1.15); moonRover.setRetardation(0.5); jumpHeight = 0; moonRover.setJumpHeight(0); ((Activity) this.getContext()).runOnUiThread(new Runnable() { @Override public void run() { Handler handler = new Handler(); handler.postDelayed(() -> { waitForTimer = false; moonRover.setBuggyXdistance(0); bexplode = false; }, 2000); } }); new Timer().schedule(new SetRecent(), 10000); new Timer().schedule(new ResetCheckpoint(), 1000); } } else if (MoonBackground.checkpoint != '@' && position == 1 && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z') { canvas.drawBitmap(spacerock, toRect1.left, toRect1.top, paint); //if buggy collides with moon rock 1 if (!waitForTimer && !UFO.recent && MoonBackground.checkpoint != 'A' && MoonBackground.checkpoint != 'E' && MoonBackground.checkpoint != 'J' && MoonBackground.checkpoint != 'T' && MoonBackground.checkpoint != 'O' && MoonBackground.checkpoint != 'Z' && MoonBackground.checkpoint != '@' && !recent && (buggyXDisplacement + moonRover.getBuggyXdistance()) < (bg.xClip) && java.lang.Math.abs((screenHeight * 0.5) - moonRover.getJumpHeight() - bg.startY) < 180 && java.lang.Math.abs((buggyXDisplacement + moonRover.getBuggyXdistance()) - (bg.xClip)) < moonRover.getBitmapRover().getWidth()) { // && java.lang.Math.abs((alienBombY + screenHeight / 100 * 25 + 75 + missileOffSetY) - ((screenHeight * 0.3) - jumpHeight )) < 65) { moonRover.explode(canvas, paint, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight()); bombed--; recent = true; waitForTimer = true; bexplode = true; moonRover.setDistanceDelta(1.15); moonRover.setRetardation(0.5); moonRover.setJumpHeight(0); ((Activity) this.getContext()).runOnUiThread(new Runnable() { @Override public void run() { Handler handler = new Handler(); handler.postDelayed(() -> { waitForTimer = false; moonRover.setBuggyXdistance(0); bexplode = false; }, 2000); } }); new Timer().schedule(new SetRecent(), 10000); new Timer().schedule(new ResetCheckpoint(), 1000); } } } // collide with holes when there are holes if (!waitForTimer && !UFO.recent && bg.reversedFirst && !UFO.recent && position == 1 && moonRover.getJumpHeight() < 20 && java.lang.Math.abs(moonRover.getBuggyXdistance() + craterX + java.lang.Math.abs(bg.xClip - bg.width)) < 20) //(buggyXDisplacement + buggyXDistance) < (bg.xClip) && java.lang.Math.abs((buggyXDisplacement + buggyXDistance) - (bg.xClip)) < moonRover.getBitmapRover().getWidth()) { canvas.drawBitmap(explode, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight(), paint); bombed--; recent = true; waitForTimer = true; bexplode = true; canvas.drawBitmap(explode, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight(), paint); moonRover.setDistanceDelta(1.15); moonRover.setRetardation(0.5); jumpHeight = 0; moonRover.setJumpHeight(0); ((Activity) this.getContext()).runOnUiThread(new Runnable() { @Override public void run() { Handler handler = new Handler(); handler.postDelayed(() -> { waitForTimer = false; moonRover.setBuggyXdistance(0); bexplode = false; }, 2000); } }); new Timer().schedule(new SetRecent(), 10000); new Timer().schedule(new ResetCheckpoint(), 1000); } //Log.d("## hole", "hole " + (int) ((buggyXDistance) + bg.xClip -bg.width)); if (!recent && moonRover.getJumpHeight() < 30 && position == 1 && !bg.reversedFirst && (java.lang.Math.abs((moonRover.getBuggyXdistance() + craterX) - java.lang.Math.abs(bg.xClip)) < 15)) // >1 { canvas.drawBitmap(explode, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight(), paint); // MoonBackground.checkpoint = 'A'; bombed--; recent = true; waitForTimer = true; bexplode = true; canvas.drawBitmap(explode, (float) (buggyXDisplacement + moonRover.getBuggyXdistance()), (float) (screenHeight * 0.5) - moonRover.getJumpHeight(), paint); moonRover.setDistanceDelta(1.15); moonRover.setRetardation(0.5); moonRover.setJumpHeight(0); ((Activity) this.getContext()).runOnUiThread(new Runnable() { @Override public void run() { Handler handler = new Handler(); handler.postDelayed(() -> { waitForTimer = false; moonRover.setBuggyXdistance(0); bexplode = false; }, 2000); } }); new Timer().schedule(new SetRecent(), 10000); new Timer().schedule(new ResetCheckpoint(), 1000); } } // Because we call this from onTouchEvent, this code will be executed for both // normal touch events and for when the system calls this using Accessibility @Override public boolean performClick() { super.performClick(); launchMissile(); return true; } protected void launchMissile() { missiles[index] = 350; // missile distance from buggy index++; xbuggy2 = 0; shoot = true; } // event listener for when the user touches the screen @Override public boolean onTouchEvent(MotionEvent event) { int action = MotionEventCompat.getActionMasked(event); int coordX = (int) event.getX(); int coordY = (int) event.getY(); //Log.d("coordY", "coordY " + coordY); if (coordX < 220 && moonRover.getJumpHeight() == 0 && action == MotionEvent.ACTION_MOVE) { jump = true; shoot = false; lastTurn3 = System.currentTimeMillis(); return true; // do nothing } if (coordX > 219 && action == MotionEvent.ACTION_DOWN) { numberOfshots++; performClick(); return true; } return true; } } ``` **ParallaxActivity.java** ``` public class ParallaxActivity extends Activity implements View.OnClickListener { long startTime; long countUp; TextView textGoesHere; TextView tvId; ParallaxView parallaxView; boolean paused = false; double acceleration = 0; @Override public void onClick(View v) { ParallaxView parallaxView = findViewById(R.id.backgroundImage); switch (v.getId()) { case R.id.button3: //ParallaxView parallaxView = findViewById(R.id.backgroundImage); parallaxView.recent = false; parallaxView.brake = false; parallaxView.getMoonRover().setRetardation(0); //parallaxView.buggyXDistance = parallaxView.buggyXDistance + 3; parallaxView.getMoonRover().increaseBuggyXdistance(3); parallaxView.getMoonRover().setDistanceDelta(parallaxView.getMoonRover().getDistanceDelta() + acceleration); acceleration = acceleration + 0.2; break; case R.id.button4: //ParallaxView parallaxView2 = findViewById(R.id.backgroundImage); parallaxView.recent = false; //parallaxView.buggyXDistance = parallaxView.buggyXDistance - 7; parallaxView.getMoonRover().decreaseBuggyXdistance(7); acceleration = 0; parallaxView.getMoonRover().increaseRetardation(0.2); parallaxView.brake = true; break; case R.id.button2: //ParallaxView parallaxView3 = findViewById(R.id.backgroundImage); parallaxView.numberOfshots++; parallaxView.recent = false; parallaxView.launchMissile(); parallaxView.scoring = true; break; case R.id.button1: //ParallaxView parallaxView4 = findViewById(R.id.backgroundImage); if (parallaxView.getMoonRover().getDistanceDelta() < 3) { // parallaxView4.distanceDelta = parallaxView4.distanceDelta + 0.2; parallaxView.getMoonRover().setDistanceDelta(parallaxView.getMoonRover().getDistanceDelta()+0.2); } parallaxView.jump = true; parallaxView.shoot = false; parallaxView.lastTurn3 = System.currentTimeMillis(); break; case R.id.button5: if (!paused) { paused = true; onPause(); } else { paused = false; onResume(); } break; default: break; } } public void setText(final String s, final TextView tv) { //TextView tv= (TextView) tf.getView().findViewById(R.id.textview1); tv.append(String.valueOf(s)); } Chronometer stopWatch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get a Display object to access screen details Display display = getWindowManager().getDefaultDisplay(); // Load the resolution into a Point object Point resolution = new Point(); display.getSize(resolution); setContentView(R.layout.main_layout); Button btn1 = findViewById(R.id.button3); btn1.setOnClickListener(this); Button btn2 = findViewById(R.id.button4); btn2.setOnClickListener(this); Button btn3 = findViewById(R.id.button2); btn3.setOnClickListener(this); Button btn4 = findViewById(R.id.button1); btn4.setOnClickListener(this); Button btn5 = findViewById(R.id.button5); btn5.setOnClickListener(this); tvId = findViewById(R.id.player1); TextView tvId1 = findViewById(R.id.checkpoint); String s1 = " A "; tvId1.setText(s1); parallaxView = findViewById(R.id.backgroundImage); parallaxView.checkpointtextview = findViewById(R.id.checkpointtext); parallaxView.checkpointtextview.setText(""); parallaxView.checkpointtextview2 = findViewById(R.id.checkpointtext2); parallaxView.checkpointtextview2.setText(""); parallaxView.checkpointtextview3 = findViewById(R.id.checkpointtext3); parallaxView.checkpointtextview3.setText(""); parallaxView.checkpointtextview4 = findViewById(R.id.checkpointtext4); parallaxView.checkpointtextview4.setText(""); parallaxView.checkpointtextview5 = findViewById(R.id.checkpointtext5); parallaxView.checkpointtextview5.setText(""); parallaxView.checkpointtextview6 = findViewById(R.id.checkpointtext6); parallaxView.checkpointtextview6.setText(""); stopWatch = (Chronometer) findViewById(R.id.chrono); startTime = SystemClock.elapsedRealtime(); stopWatch.setBase(startTime); textGoesHere = (TextView) findViewById(R.id.textGoesHere); stopWatch.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() { @Override public void onChronometerTick(Chronometer arg0) { countUp = (SystemClock.elapsedRealtime() - startTime) / 1000; String str = String.format("%04d", countUp); textGoesHere.setText(str); } }); stopWatch.start(); parallaxView.tvId1 = tvId1; parallaxView.tvId = tvId; } // If the Activity is paused make sure to pause our thread @Override protected void onPause() { super.onPause(); parallaxView.pause(); } // If the Activity is resumed make sure to resume our thread @Override protected void onResume() { super.onResume(); parallaxView.resume(); } } ```
2018/07/13
[ "https://codereview.stackexchange.com/questions/198400", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/6426/" ]
My answer will also be short as there are too many things to adress at one time. But there is exactly one thing I am able to say at this point of time: You mixed up model and view. So my suggestion is to first create a model of your game so it is runnable without ANY UI elements and connect the model to the UI afterwards. A good way to learn this kind of separation of concerns is to force yourself writing the model not in the android studio and have the model imported if you think it is "ready". You may also consider to have another UI techonology in the first place like JavaFX. If you import the model to Android at som point you will recognize the elements that you accidently put into the UI as it has been better placed within the model. One other thing I recognized as I had a rough review over the code: your draw()-method is very long. Not that long methods are bad from scratch but your draw method has a lot of logic in it so it would be better split into pieces.
You are probably using Android Studio, which is based on IntelliJ. This IDE offers really many inspections to improve your code. One of them is: ``` variable = variable + 3; ``` Can be replaced with: ``` variable += 3; ``` You should enable all these inspections and decide whether to apply them. Some of the inspections contradict each other, so choose your favorite ones. And don't apply the inspections blindly, only apply them if they actually improve the code. Doing this relieves us humans from boring review tasks so that we can concentrate on the more interesting details in the next review round.
26,367
Currently car boosters (a portable unit charged of an outlet and then connected to the car electrical system to start a car when the car battery is dead) typically use batteries - lead-acid, Li-Ion or LiFePO4. Over several years a battery in the booster will wear out. Would it be practical to use a bank of supercapacitors that are more durable instead of a battery in a booster?
2012/02/09
[ "https://electronics.stackexchange.com/questions/26367", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/3552/" ]
I started this reply expecting the answer to be "not a chance" but a quick look at specs and prices suggests you could do something which was interesting and possible useful to some extent but that its really impractical and certainly not cost effective so far and is unlikely to be cost effective for a few cycles of Moore's law yet. Assume starting requires 500 A at 12v for 1 second. That's far too high in many cases - but lower currents for longer to much longer are common, especially on a very cold morning. Adjust assumptions to suit. Energy in a capacitor \$ = \frac{1}{2}CV^2 \$ \$ = 0.5 \cdot 1 \cdot 144 \$ for 1 Farad at 12 Volt = Say 70 Watt seconds per Farad. Car starting = \$ 12V \cdot 500A \cdot 1 \$ second as above = 6000 Watt seconds. So capacitance required to supply this energy at 12V = \$ \frac{6000}{70} =~ 100 F\$. Most supercaps are 2.5V to 3.3V rated for technical reasons. You can buty modules like [this 42V 100F unit](http://media.digikey.com/pdf/Data%20Sheets/Epcos%20PDFs/B48621A7105Q018.pdf) that measures 550 x 270 x 110 mm and weighs 13 kg. The note it store 88200 Joule so is 88200/6000 ~= 15 times as large in capacity that the single start solution above. To build a 12V cap from 3v3 caps requires 4 in series and from 2V5 = 5 in series. Placing capacitors in series reduces capacitance in inverse proportion to quantity so we would need 400F with 3v3 capacitors and 500F with 2V5 ones. Murphy being active it would be wise to use say 1000F x 12v = 5 x 200F at 2V5. At this stage it get interesting as we find that eg Digikey WILL sell you supercaps in this range. Cost is very roughly 10 cents per Farad so a 200F ~~= $20 an 4 cost $80. Say $1000. A look at the specs shows we are not there yet. NO max discharge current specified but internal resistance of around 10 milliohm.That's perhaps 200+ Amps at short circuit. Loaded for maximum power transfer at Rload = Rinternal = 10 milliohm say, that's 100+A. That's not really grunty enough for car starting, and we have not yet looked at voltage droop to extract energy etc. Note that at \$ \frac{V}{2} \$ a cap has exhausted 75% of its energy. If a cap is double the energy content needed then draining it to 70% will deliver half the internal energy with the other half stored for next time" Pretty clearly, a 'battery' that is good for one start is not usually useful. Much bigger caps at bigger charge are needed. And even then it will not be possible to approach the energy capacity of a battery. So - not practical yet - but slowly heading there. Maybe 10 years (about 7 Moore's law cycles) 470 - 3300 Farad x 2.5 V cells. **Leakage:** Leakage of the above is 0.5C mA - so for a 200 F cap that's 100 mA leakage. A farad will supply that for 10 seconds and drop a volt. So a 200F cap will take \$ 2 \cdot 200F = 400 \$ seconds to drop a volt. Needs work! Some will be much better than this.
Batteries have a relatively flat curve of voltage over charge, up to a point. Capacitors have a linear curve of voltage over charge. With batteries, you can just set up the booster battery pack in a way the voltage fits your need over a wide range of charge percentage. With capacitors, this is not an option, because the voltage would change rapidly with use. To use it at all, you would need some power electronics to supply the correct voltage. Also, currently the specific energy (stored energy per weight) of supercaps is still lower than what batteries provide. This might change within a few years. So, right now, supercaps provide less energy, and need additional power electronics, making their use as power source inefficient.
26,367
Currently car boosters (a portable unit charged of an outlet and then connected to the car electrical system to start a car when the car battery is dead) typically use batteries - lead-acid, Li-Ion or LiFePO4. Over several years a battery in the booster will wear out. Would it be practical to use a bank of supercapacitors that are more durable instead of a battery in a booster?
2012/02/09
[ "https://electronics.stackexchange.com/questions/26367", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/3552/" ]
I started this reply expecting the answer to be "not a chance" but a quick look at specs and prices suggests you could do something which was interesting and possible useful to some extent but that its really impractical and certainly not cost effective so far and is unlikely to be cost effective for a few cycles of Moore's law yet. Assume starting requires 500 A at 12v for 1 second. That's far too high in many cases - but lower currents for longer to much longer are common, especially on a very cold morning. Adjust assumptions to suit. Energy in a capacitor \$ = \frac{1}{2}CV^2 \$ \$ = 0.5 \cdot 1 \cdot 144 \$ for 1 Farad at 12 Volt = Say 70 Watt seconds per Farad. Car starting = \$ 12V \cdot 500A \cdot 1 \$ second as above = 6000 Watt seconds. So capacitance required to supply this energy at 12V = \$ \frac{6000}{70} =~ 100 F\$. Most supercaps are 2.5V to 3.3V rated for technical reasons. You can buty modules like [this 42V 100F unit](http://media.digikey.com/pdf/Data%20Sheets/Epcos%20PDFs/B48621A7105Q018.pdf) that measures 550 x 270 x 110 mm and weighs 13 kg. The note it store 88200 Joule so is 88200/6000 ~= 15 times as large in capacity that the single start solution above. To build a 12V cap from 3v3 caps requires 4 in series and from 2V5 = 5 in series. Placing capacitors in series reduces capacitance in inverse proportion to quantity so we would need 400F with 3v3 capacitors and 500F with 2V5 ones. Murphy being active it would be wise to use say 1000F x 12v = 5 x 200F at 2V5. At this stage it get interesting as we find that eg Digikey WILL sell you supercaps in this range. Cost is very roughly 10 cents per Farad so a 200F ~~= $20 an 4 cost $80. Say $1000. A look at the specs shows we are not there yet. NO max discharge current specified but internal resistance of around 10 milliohm.That's perhaps 200+ Amps at short circuit. Loaded for maximum power transfer at Rload = Rinternal = 10 milliohm say, that's 100+A. That's not really grunty enough for car starting, and we have not yet looked at voltage droop to extract energy etc. Note that at \$ \frac{V}{2} \$ a cap has exhausted 75% of its energy. If a cap is double the energy content needed then draining it to 70% will deliver half the internal energy with the other half stored for next time" Pretty clearly, a 'battery' that is good for one start is not usually useful. Much bigger caps at bigger charge are needed. And even then it will not be possible to approach the energy capacity of a battery. So - not practical yet - but slowly heading there. Maybe 10 years (about 7 Moore's law cycles) 470 - 3300 Farad x 2.5 V cells. **Leakage:** Leakage of the above is 0.5C mA - so for a 200 F cap that's 100 mA leakage. A farad will supply that for 10 seconds and drop a volt. So a 200F cap will take \$ 2 \cdot 200F = 400 \$ seconds to drop a volt. Needs work! Some will be much better than this.
Very interesting discussion; I appreciate the thorough and detailed calculations. Even though the current technology seems to indicate that this is not a practical application, I found a tinkerer who seems to have had success: <http://www.youtube.com/watch?v=GPJao1xLe7w> Here is a commercial product designed for installation on 18-wheelers to ensure starting power; in this design one of the four truck batteries are swapped with the ultracapacitor engine start module, but on it's own wiring: <http://www.maxwell.com/products/ultracapacitors/products/engine-start-module> Maybe with careful design considerations these ultracapacitor arrays can be useful in some situations.
26,367
Currently car boosters (a portable unit charged of an outlet and then connected to the car electrical system to start a car when the car battery is dead) typically use batteries - lead-acid, Li-Ion or LiFePO4. Over several years a battery in the booster will wear out. Would it be practical to use a bank of supercapacitors that are more durable instead of a battery in a booster?
2012/02/09
[ "https://electronics.stackexchange.com/questions/26367", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/3552/" ]
I started this reply expecting the answer to be "not a chance" but a quick look at specs and prices suggests you could do something which was interesting and possible useful to some extent but that its really impractical and certainly not cost effective so far and is unlikely to be cost effective for a few cycles of Moore's law yet. Assume starting requires 500 A at 12v for 1 second. That's far too high in many cases - but lower currents for longer to much longer are common, especially on a very cold morning. Adjust assumptions to suit. Energy in a capacitor \$ = \frac{1}{2}CV^2 \$ \$ = 0.5 \cdot 1 \cdot 144 \$ for 1 Farad at 12 Volt = Say 70 Watt seconds per Farad. Car starting = \$ 12V \cdot 500A \cdot 1 \$ second as above = 6000 Watt seconds. So capacitance required to supply this energy at 12V = \$ \frac{6000}{70} =~ 100 F\$. Most supercaps are 2.5V to 3.3V rated for technical reasons. You can buty modules like [this 42V 100F unit](http://media.digikey.com/pdf/Data%20Sheets/Epcos%20PDFs/B48621A7105Q018.pdf) that measures 550 x 270 x 110 mm and weighs 13 kg. The note it store 88200 Joule so is 88200/6000 ~= 15 times as large in capacity that the single start solution above. To build a 12V cap from 3v3 caps requires 4 in series and from 2V5 = 5 in series. Placing capacitors in series reduces capacitance in inverse proportion to quantity so we would need 400F with 3v3 capacitors and 500F with 2V5 ones. Murphy being active it would be wise to use say 1000F x 12v = 5 x 200F at 2V5. At this stage it get interesting as we find that eg Digikey WILL sell you supercaps in this range. Cost is very roughly 10 cents per Farad so a 200F ~~= $20 an 4 cost $80. Say $1000. A look at the specs shows we are not there yet. NO max discharge current specified but internal resistance of around 10 milliohm.That's perhaps 200+ Amps at short circuit. Loaded for maximum power transfer at Rload = Rinternal = 10 milliohm say, that's 100+A. That's not really grunty enough for car starting, and we have not yet looked at voltage droop to extract energy etc. Note that at \$ \frac{V}{2} \$ a cap has exhausted 75% of its energy. If a cap is double the energy content needed then draining it to 70% will deliver half the internal energy with the other half stored for next time" Pretty clearly, a 'battery' that is good for one start is not usually useful. Much bigger caps at bigger charge are needed. And even then it will not be possible to approach the energy capacity of a battery. So - not practical yet - but slowly heading there. Maybe 10 years (about 7 Moore's law cycles) 470 - 3300 Farad x 2.5 V cells. **Leakage:** Leakage of the above is 0.5C mA - so for a 200 F cap that's 100 mA leakage. A farad will supply that for 10 seconds and drop a volt. So a 200F cap will take \$ 2 \cdot 200F = 400 \$ seconds to drop a volt. Needs work! Some will be much better than this.
As part of my work, I have some tools that compare capacitor banks for a given starting voltage, end voltage, load power, and time. Takes ESR and EOL values into account, too. My databank doesn't have every ultracap in existence, of course, but it's got a number of the most likely suspects. So let's assume the battery you'd normally use would start at 13.2V unloaded, and drop to 7V when loaded to 500A. We can calculate our power from the low-end voltage, since that's clearly enough to start the car. To pull 3500W for one second from an ultracap and still stay in that voltage range, the best combination I see would be two of [these](http://www.digikey.com/product-detail/en/BMOD0165%20P048%20B01/1182-1031-ND/3079295?WT.z_cid=ref_octopart_dkc_buynow) in parallel. So you're talking about >$3k of ultracaps to replace a ~$100 battery. You *might* could get away with one ultracap module instead of two, especially if you don't use end-of-life values, but you'd have much less overhead, and your ESR losses would go up considerably. Even then, and even with direct-from-the-manufacturer quantity pricing you're still talking about $1500. So it's doable, and not *entirely* insane. Whether it's cost-effective or not depends largely on how much your battery costs, and how often you need to replace it in the lifetime of your cap bank. Regarding how you'd charge the ultracap itself, I don't think that's a problem. The terminal voltage on that capacitance at 3500W load after one second is about 10.2V, so we're talking about 11.5 kJ charge lost in the caps. (So we're delivering 3.5 kJ to the load, and 8 kJ lost in ESR!) That can be charged off a wall socket in just a few seconds. If you want a second shot, and have a wall socket anywhere nearby, you should be fine. And you're nowhere near the voltage limit of the capacitors, which means your charger doesn't need to be particularly smart, like a Li charger would have to be. Edit: I came across this question again and reran the numbers based on newer tools, pricing, and available parts. The most cost effective solution now appears to be five of [these](https://www.digikey.com/product-detail/en/BMOD0058%2520E016%2520B02/1182-1027-ND/3079291?WT.z_cid=ref_octopart_dkc_buynow&site=us) in parallel, with a cost of roughly $600. And that's still assuming EOL values on the caps. For nominal, you'd only need three in parallel. Vast improvement over the last two years! It might actually pay for itself!
54,128,277
I am having a problem with one of my table views. I am writing a messaging page for my app that uses a table view to display the messages sent and received. The table cells need to change height based on each cells content. I have the sizing working correctly but I now need to round the cells edges to fit the UI design. The way that I have done this in the past with non-dynamic heights is by calling a function to round each corner in the override function "layoutSubViews()" in the tableViewCell: ``` func roundAllCorners(radius: CGFloat) { let allCorners: UIRectCorner = [.topLeft, .bottomLeft, .bottomRight, .topRight] let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: allCorners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath self.layer.mask = mask } ``` If I try calling this function but the cell is dynamically sized then the left edge cuts off half a centimeter. If you scroll the cell off screen and back again though it fixes it. Hope you can find a solution to my problem, has been a pain in the neck for a while. Thanks.
2019/01/10
[ "https://Stackoverflow.com/questions/54128277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9882015/" ]
It might be you also need to override the setter for frame and call it in there. Any any case this is not a good idea for multiple reasons. The thing is that table view cell has many views (including itself being a view) like content view and background view... I suggest that you add yet another view on the content view which holds all your cell views. Then make this view a subclass and handle all the rounding in there. So from the storyboard perspective you would have something like: ``` - UITableViewCell - contentView - roundedContainer - imageView - button - label ... ``` The rounded view has (or should have) constraints so `layoutSubViews` should be enough to override for setting up corner radius. You can have a neat class you can use to round your view like: ``` class RoundedView: UIView { @IBInspectable var cornerRadius: CGFloat = 0.0 { didSet { refresh() } } @IBInspectable var fullyRounded: Bool = false { didSet { refresh() } } override func layoutSubviews() { super.layoutSubviews() refresh() } private func refresh() { layer.cornerRadius = fullyRounded ? min(bounds.width, bounds.height) : cornerRadius } } ``` As already mentioned by @iDeveloper it might be better to use `cornerRadius` of a layer. But if you need to use a shape layer you can do that as well in this class. Make sure to clip bounds on this view.
Make sure you **RELOAD THE TABLEVIEW** after calling your function ``` yourTableView.reloadData() ```
54,128,277
I am having a problem with one of my table views. I am writing a messaging page for my app that uses a table view to display the messages sent and received. The table cells need to change height based on each cells content. I have the sizing working correctly but I now need to round the cells edges to fit the UI design. The way that I have done this in the past with non-dynamic heights is by calling a function to round each corner in the override function "layoutSubViews()" in the tableViewCell: ``` func roundAllCorners(radius: CGFloat) { let allCorners: UIRectCorner = [.topLeft, .bottomLeft, .bottomRight, .topRight] let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: allCorners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath self.layer.mask = mask } ``` If I try calling this function but the cell is dynamically sized then the left edge cuts off half a centimeter. If you scroll the cell off screen and back again though it fixes it. Hope you can find a solution to my problem, has been a pain in the neck for a while. Thanks.
2019/01/10
[ "https://Stackoverflow.com/questions/54128277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9882015/" ]
It might be you also need to override the setter for frame and call it in there. Any any case this is not a good idea for multiple reasons. The thing is that table view cell has many views (including itself being a view) like content view and background view... I suggest that you add yet another view on the content view which holds all your cell views. Then make this view a subclass and handle all the rounding in there. So from the storyboard perspective you would have something like: ``` - UITableViewCell - contentView - roundedContainer - imageView - button - label ... ``` The rounded view has (or should have) constraints so `layoutSubViews` should be enough to override for setting up corner radius. You can have a neat class you can use to round your view like: ``` class RoundedView: UIView { @IBInspectable var cornerRadius: CGFloat = 0.0 { didSet { refresh() } } @IBInspectable var fullyRounded: Bool = false { didSet { refresh() } } override func layoutSubviews() { super.layoutSubviews() refresh() } private func refresh() { layer.cornerRadius = fullyRounded ? min(bounds.width, bounds.height) : cornerRadius } } ``` As already mentioned by @iDeveloper it might be better to use `cornerRadius` of a layer. But if you need to use a shape layer you can do that as well in this class. Make sure to clip bounds on this view.
You can use self sizing table view cell according to the content. Now you can follow the previous implementation for rounded corner cell. Place the below code inside viewDidLoad. tableView.estimatedRowHeight = YourEstimatedTableViewHeight tableView.rowHeight = UITableViewAutomaticDimension **Note**: You have to give the top and bottom constraints to the content properly. For detailed implementation you can follow [self-sizing-table-view-cells](https://www.raywenderlich.com/8549-self-sizing-table-view-cells)
54,128,277
I am having a problem with one of my table views. I am writing a messaging page for my app that uses a table view to display the messages sent and received. The table cells need to change height based on each cells content. I have the sizing working correctly but I now need to round the cells edges to fit the UI design. The way that I have done this in the past with non-dynamic heights is by calling a function to round each corner in the override function "layoutSubViews()" in the tableViewCell: ``` func roundAllCorners(radius: CGFloat) { let allCorners: UIRectCorner = [.topLeft, .bottomLeft, .bottomRight, .topRight] let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: allCorners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath self.layer.mask = mask } ``` If I try calling this function but the cell is dynamically sized then the left edge cuts off half a centimeter. If you scroll the cell off screen and back again though it fixes it. Hope you can find a solution to my problem, has been a pain in the neck for a while. Thanks.
2019/01/10
[ "https://Stackoverflow.com/questions/54128277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9882015/" ]
Make sure you **RELOAD THE TABLEVIEW** after calling your function ``` yourTableView.reloadData() ```
You can use self sizing table view cell according to the content. Now you can follow the previous implementation for rounded corner cell. Place the below code inside viewDidLoad. tableView.estimatedRowHeight = YourEstimatedTableViewHeight tableView.rowHeight = UITableViewAutomaticDimension **Note**: You have to give the top and bottom constraints to the content properly. For detailed implementation you can follow [self-sizing-table-view-cells](https://www.raywenderlich.com/8549-self-sizing-table-view-cells)
39,442,554
So this one sounds very easy but I am getting some strange behavior. In my program there is the following code: ``` std::cout << "Would you like to generate a complexity graph or calculate global complexity? (graph/global)\n"; char ans[6]; std::cin >> ans; if (ans != "global") std::cout << ">>" << ans << "<<" << std::endl; ``` When I run my program and type in "global" when I'm prompted for input, the program returns: ``` >>global<< ``` Why does the if statement evaluate as `true`?
2016/09/12
[ "https://Stackoverflow.com/questions/39442554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333797/" ]
1. You should use [`strcmp`](http://en.cppreference.com/w/cpp/string/byte/strcmp) or [`strncmp`](http://en.cppreference.com/w/cpp/string/byte/strncmp) for comparison of c-style strings. `ans != "global"` is just comparing the memory address pointed by the pointer, not the content of string. 2. `char ans[6];` should be `char ans[7];`, for `"global"`, you need one more `char` for the terminating null character `'\0'`. You should use `std::string` instead, to avoid such issues.
You declared `ans` as array of char, thus if `if (ans != "global")` expression, `ans` means pointer to the beginning of the string. So you compare two pointers which are obviously not equal and your expression evaluates to true. If you still want to declare `ans` as a C-style string, you may construct an `std::string` from it before comparing: ``` if (std::string(ans) != "global") {......} ``` Or just declare `ans` as `std::string` instead of `char[]`.
12,938,344
I am just building a very simple application. Three buttons. The first opens a browser, the second opens the phone and the third opens the Maps application. The purpose is to learn more about intents triggering the start up of other applications. ``` public void openBrowser(){ //Create intent Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://www.facebook.com")); startActivity(i); } public void openPhone(){ Intent i = new Intent(android.content.Intent.ACTION_DIAL, Uri.parse("tel: +3531234567890")); startActivity(i); } public void openMap(){ Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:53.2803, -6.1529")); startActivity(i); } ``` Should there be an entry in the manifest file for these particular intents? Thanks for the help!
2012/10/17
[ "https://Stackoverflow.com/questions/12938344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1732515/" ]
``` select * from Table3 where id not in ( select id from Table1 --your subquery that returns 1,2,3 union all select id from Table2 --your subquery that returns 4,5 ) ```
``` select * from mytable where id not in ( select id from othertable union select id from othertable2 ) ```
8,363,759
Here is some C++ code: ``` namespace A { int f(int x) { return 0; } int f(long x) { return 1; } template<class T> int g(T x) { return f(x); } } namespace B { struct C {}; } namespace A { int f(B::C x) { return 2; } } void h() { A::g(B::C()); } ``` In namespace A, the code declares a few overloads of a function f, and a templated function g which calls f. Then we declare a new type in namespace B and overload f for the new type *in namespace A*. Compiling with g++ 4.2 gives ``` order.cpp: In function ‘int A::g(T) [with T = B::C]’: order.cpp:21: instantiated from here order.cpp:7: error: no matching function for call to ‘f(B::C&)’ order.cpp:3: note: candidates are: int A::f(int) order.cpp:4: note: int A::f(long int) ``` The code works if I do any of the following: 1. Remove the namespaces. 2. Move the overload of f for B::C into namespace B (thanks to Koenig lookup). 3. Move the declaration of B::C and its f overload above the definition of g(). I'm particularly puzzled by (3), since I was under the impression that overload resolution should be independent of the order of declarations. Is this expected C++ behavior?
2011/12/02
[ "https://Stackoverflow.com/questions/8363759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16480/" ]
Clang gives the following error message, which gives some clues to the problem: ``` $ clang -fsyntax-only test.cc -Wall test.cc:7:10: error: call to function 'f' that is neither visible in the template definition nor found by argument-dependent lookup return f(x); ^ test.cc:21:3: note: in instantiation of function template specialization 'A::g<B::C>' requested here A::g(B::C()); ^ test.cc:17:5: note: 'f' should be declared prior to the call site or in namespace 'B' int f(B::C x) { return 2; } ^ 1 error generated. ``` Specifically, you've run into a detail of two-phase lookup of dependent names in template definitions. In C++98, [temp.dep.candidate] says: > > For a function call that depends on a template parameter, if the function name is an unqualified-id but not a template-id, the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2) except that: > > > * For the part of the lookup using unqualified name lookup (3.4.1), only function declarations with external linkage from the template definition context are found. > * For the part of the lookup using associated namespaces (3.4.2), only function declarations with external linkage found in either the template definition context or the template instantiation context are found. > > > Since `A::f(B::C x)` isn't found using associated namespaces (i.e. argument-dependent lookup), it has to be visible at the template definition site, not just at the point of instantiation.
For instance ``` int f(int x) { return 0; } int f(long x) { return 1; } ``` functions are not template functions (i.e. they don't have a `template <class T>` before them. T is a template parameter.) Therefore they can be compiled on the fly when the templated code is reached.
57,973,941
I'm fairly new to android studio so I will try to explain as best as I can. I've made a menu using fragments, so my `activity_home` is a fragmented activity. Inside the fragmented activity I've created a button that, upon clicking, should open a new activity. The problem is that I don't know how to implement the `onClickListener` inside the fragmented activity. Every tutorial I went trough does it from the beginning. This is my main activity: ``` package com.example.relja.diplomskirad; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(false); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new home(), "Home"); adapter.addFragment(new profil(), "Profil"); adapter.addFragment(new mapa(), "Mapa"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } } ``` This is my main xml: ``` <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMode="fixed" app:tabGravity="fill"/> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </android.support.design.widget.CoordinatorLayout> ``` This is home.java where i want to put the onclick listener: ``` package com.example.relja.diplomskirad; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; public class home extends Fragment { public home() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.activity_home, container, false); } } ``` And this is home xml where the button is: ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".home"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="80dp" android:orientation="vertical"> <LinearLayout android:id="@+id/glavnaStranica1" android:layout_width="match_parent" android:layout_height="200dp" android:orientation="horizontal" android:gravity="center"> <ImageView android:id="@+id/logoSlika" android:layout_width="200dp" android:layout_height="200dp" android:src="@drawable/logo2" android:layout_gravity="center"/> </LinearLayout> <LinearLayout android:id="@+id/glavnaStranica2" android:layout_width="match_parent" android:layout_height="200dp" android:orientation="horizontal" android:gravity="center" android:layout_marginStart="30dp"> <EditText android:id="@+id/search" android:layout_width="250dp" android:layout_height="38dp" android:hint="@string/search" android:background="@drawable/ivica" android:drawableLeft="@drawable/search" android:drawablePadding="10dp" android:inputType="text" /> <Button android:id="@+id/dugme" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/dugme" /> </LinearLayout> <Button android:id="@+id/dugmeLogin" android:layout_width="70dp" android:layout_height="40dp" android:text="@string/dugmeLogin" android:layout_gravity="end" android:layout_marginRight="10dp" android:onClick="loginLogin" style="?android:attr/borderlessButtonStyle"/> </LinearLayout> </RelativeLayout> ```
2019/09/17
[ "https://Stackoverflow.com/questions/57973941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7280627/" ]
Whenever you are dealing with date values, its always better to use Date object. **Note:** month in JS starts with `0` so Jan. is 0 and Sept. is 8 ```js var json = [{ "empId": 175, "Name": "Sai", "Sal": 37000, "doj": "2019-08-15 00:00:00" }, { "empId": 1751, "Name": "Pavan", "Sal": 57000, "doj": "2019-07-15 00:00:00" } ]; var month = '8'; let empData = json.filter(({ doj }) => (new Date(doj)).getMonth() === month - 1); console.log(empData.length) ```
You could slice the wanted part from the timestamp and get a numerical value, then compare with the month. ```js var json = [{ empId: 175, Name: "Sai", Sal: 37000, doj: "2019-08-15 00:00:00" }, { empId: 1751, Name: "Pavan", Sal: 57000, doj: "2019-07-15 00:00:00" }], month = '8', empData = json.filter(({ doj }) => +doj.slice(5, 7) == month); console.log(empData); ``` ```css .as-console-wrapper { max-height: 100% !important; top: 0; } ```
57,973,941
I'm fairly new to android studio so I will try to explain as best as I can. I've made a menu using fragments, so my `activity_home` is a fragmented activity. Inside the fragmented activity I've created a button that, upon clicking, should open a new activity. The problem is that I don't know how to implement the `onClickListener` inside the fragmented activity. Every tutorial I went trough does it from the beginning. This is my main activity: ``` package com.example.relja.diplomskirad; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(false); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new home(), "Home"); adapter.addFragment(new profil(), "Profil"); adapter.addFragment(new mapa(), "Mapa"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } } ``` This is my main xml: ``` <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMode="fixed" app:tabGravity="fill"/> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </android.support.design.widget.CoordinatorLayout> ``` This is home.java where i want to put the onclick listener: ``` package com.example.relja.diplomskirad; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; public class home extends Fragment { public home() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.activity_home, container, false); } } ``` And this is home xml where the button is: ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".home"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="80dp" android:orientation="vertical"> <LinearLayout android:id="@+id/glavnaStranica1" android:layout_width="match_parent" android:layout_height="200dp" android:orientation="horizontal" android:gravity="center"> <ImageView android:id="@+id/logoSlika" android:layout_width="200dp" android:layout_height="200dp" android:src="@drawable/logo2" android:layout_gravity="center"/> </LinearLayout> <LinearLayout android:id="@+id/glavnaStranica2" android:layout_width="match_parent" android:layout_height="200dp" android:orientation="horizontal" android:gravity="center" android:layout_marginStart="30dp"> <EditText android:id="@+id/search" android:layout_width="250dp" android:layout_height="38dp" android:hint="@string/search" android:background="@drawable/ivica" android:drawableLeft="@drawable/search" android:drawablePadding="10dp" android:inputType="text" /> <Button android:id="@+id/dugme" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/dugme" /> </LinearLayout> <Button android:id="@+id/dugmeLogin" android:layout_width="70dp" android:layout_height="40dp" android:text="@string/dugmeLogin" android:layout_gravity="end" android:layout_marginRight="10dp" android:onClick="loginLogin" style="?android:attr/borderlessButtonStyle"/> </LinearLayout> </RelativeLayout> ```
2019/09/17
[ "https://Stackoverflow.com/questions/57973941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7280627/" ]
Whenever you are dealing with date values, its always better to use Date object. **Note:** month in JS starts with `0` so Jan. is 0 and Sept. is 8 ```js var json = [{ "empId": 175, "Name": "Sai", "Sal": 37000, "doj": "2019-08-15 00:00:00" }, { "empId": 1751, "Name": "Pavan", "Sal": 57000, "doj": "2019-07-15 00:00:00" } ]; var month = '8'; let empData = json.filter(({ doj }) => (new Date(doj)).getMonth() === month - 1); console.log(empData.length) ```
Just use `parseInt(afterSplit[1],'10')` ``` var json = [{ "empId": 175, "Name": "Sai", "Sal": 37000, "doj": "2019-08-15 00:00:00" }, { "empId": 1751, "Name": "Pavan", "Sal": 57000, "doj": "2019-07-15 00:00:00" } ]; var month = '8'; let empData = json.filter(function(mgmtmrktshare) { let date = mgmtmrktshare.doj; let afterSplit = date.split("-"); return parseInt(afterSplit[1], 10) == month; }); console.log(empData.length) ```
57,973,941
I'm fairly new to android studio so I will try to explain as best as I can. I've made a menu using fragments, so my `activity_home` is a fragmented activity. Inside the fragmented activity I've created a button that, upon clicking, should open a new activity. The problem is that I don't know how to implement the `onClickListener` inside the fragmented activity. Every tutorial I went trough does it from the beginning. This is my main activity: ``` package com.example.relja.diplomskirad; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(false); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new home(), "Home"); adapter.addFragment(new profil(), "Profil"); adapter.addFragment(new mapa(), "Mapa"); viewPager.setAdapter(adapter); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFragment(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } } ``` This is my main xml: ``` <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> <android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMode="fixed" app:tabGravity="fill"/> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </android.support.design.widget.CoordinatorLayout> ``` This is home.java where i want to put the onclick listener: ``` package com.example.relja.diplomskirad; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; public class home extends Fragment { public home() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.activity_home, container, false); } } ``` And this is home xml where the button is: ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".home"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="80dp" android:orientation="vertical"> <LinearLayout android:id="@+id/glavnaStranica1" android:layout_width="match_parent" android:layout_height="200dp" android:orientation="horizontal" android:gravity="center"> <ImageView android:id="@+id/logoSlika" android:layout_width="200dp" android:layout_height="200dp" android:src="@drawable/logo2" android:layout_gravity="center"/> </LinearLayout> <LinearLayout android:id="@+id/glavnaStranica2" android:layout_width="match_parent" android:layout_height="200dp" android:orientation="horizontal" android:gravity="center" android:layout_marginStart="30dp"> <EditText android:id="@+id/search" android:layout_width="250dp" android:layout_height="38dp" android:hint="@string/search" android:background="@drawable/ivica" android:drawableLeft="@drawable/search" android:drawablePadding="10dp" android:inputType="text" /> <Button android:id="@+id/dugme" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/dugme" /> </LinearLayout> <Button android:id="@+id/dugmeLogin" android:layout_width="70dp" android:layout_height="40dp" android:text="@string/dugmeLogin" android:layout_gravity="end" android:layout_marginRight="10dp" android:onClick="loginLogin" style="?android:attr/borderlessButtonStyle"/> </LinearLayout> </RelativeLayout> ```
2019/09/17
[ "https://Stackoverflow.com/questions/57973941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7280627/" ]
Whenever you are dealing with date values, its always better to use Date object. **Note:** month in JS starts with `0` so Jan. is 0 and Sept. is 8 ```js var json = [{ "empId": 175, "Name": "Sai", "Sal": 37000, "doj": "2019-08-15 00:00:00" }, { "empId": 1751, "Name": "Pavan", "Sal": 57000, "doj": "2019-07-15 00:00:00" } ]; var month = '8'; let empData = json.filter(({ doj }) => (new Date(doj)).getMonth() === month - 1); console.log(empData.length) ```
You can use the below code. ```js var json = [{ "empId": 175, "Name": "Sai", "Sal": 37000, "doj": "2019-08-15 00:00:00" }, { "empId": 1751, "Name": "Pavan", "Sal": 57000, "doj": "2019-07-15 00:00:00" } ]; var month = '8' function search(month, json){ for (var i=0; i < json.length; i++) { if ((json[i].doj).getMonth() === month - 1) { return json[i]; console.log(json[i]) } } } ```
29,792,555
In my iOS application (made in Objective-C) I print a pdf document in a `UIWebView`. This `PDF` is display by my php page using `"Content-type: application/pdf"` I want to get my `PDF` name for saving it in my device after this. How could I do this please ? Just below the code I use to connect to the `webservice` and print my pdf document in my `UIWebview` ``` self.factureWebView.delegate = self; NSURL *lienFacture = [NSURL URLWithString:@"http://aaaa.com/app/facture.php"]; requete = [[NSMutableURLRequest alloc]initWithURL:lienFacture cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; [requete setHTTPMethod:@"POST"]; NSString *post =[[NSString alloc] initWithFormat:@"idC=%@&mdpC=%@&idF=%@",idConnexion, mdpConnexion, idFacture]; NSData *data = [post dataUsingEncoding:NSUTF8StringEncoding]; [requete setHTTPBody:data]; [self.factureWebView loadRequest:requete]; ``` And this is my php file ``` $idConnexion = $_POST['idConnexion']; $mdpConnexion = $_POST['mdpConnexion']; $idFacture = $_POST['idFacture']; ini_set('soap.wsdl_cache_enabled', '0'); $wsdlURL = 'https://xxxx.com/Balm/Services_2_0.wsdl'; $ns = 'https://erp.xxxx.com/developerKey/'; $devKey = 'a1b2c3'; $soap = new SoapClient($wsdlURL); $soap->__setSoapHeaders(new SoapHeader($ns, 'developerKey', $devKey)); $params = new stdClass(); $params->context = 'Client'; $params->login = $idConnexion; $params->password = $mdpConnexion; $res = $soap->GetContactDevKey($params); $devKey2 = $res->result; $soap2 = new SoapClient($wsdlURL); $soap2->__setSoapHeaders(new SoapHeader($ns, 'developerKey', $devKey2)); $res2 = $soap2->Authenticate($params); $token = $res2->result->VisitorToken; $demandsParam = new stdClass(); $demandsParam->visitorKey = $token; $demandsParam->printType = 'PrintBill'; $demandsParam->id = $idFacture; $factures = $soap2->GetClientPrint($demandsParam); echo $factures->result->Content; ```
2015/04/22
[ "https://Stackoverflow.com/questions/29792555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3820640/" ]
No, you don't. Use [digest](http://en.wikipedia.org/wiki/SHA-1#Applications) for duplicates checking. SHA1 is good enough choice. It has constant and small footprint in comparing to base64. Base64 is good for transmitting or exchanging binary data but that's all. In addition, base64 is about 1/3 greater than binary data. [Verifying that two files are identical using pure PHP?](https://stackoverflow.com/questions/18849927/verifying-that-two-files-are-identical-using-pure-php)
You want to use hash functions for that, for example, Sha1. It always returns a 40 character wich you can use to compare.
29,792,555
In my iOS application (made in Objective-C) I print a pdf document in a `UIWebView`. This `PDF` is display by my php page using `"Content-type: application/pdf"` I want to get my `PDF` name for saving it in my device after this. How could I do this please ? Just below the code I use to connect to the `webservice` and print my pdf document in my `UIWebview` ``` self.factureWebView.delegate = self; NSURL *lienFacture = [NSURL URLWithString:@"http://aaaa.com/app/facture.php"]; requete = [[NSMutableURLRequest alloc]initWithURL:lienFacture cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; [requete setHTTPMethod:@"POST"]; NSString *post =[[NSString alloc] initWithFormat:@"idC=%@&mdpC=%@&idF=%@",idConnexion, mdpConnexion, idFacture]; NSData *data = [post dataUsingEncoding:NSUTF8StringEncoding]; [requete setHTTPBody:data]; [self.factureWebView loadRequest:requete]; ``` And this is my php file ``` $idConnexion = $_POST['idConnexion']; $mdpConnexion = $_POST['mdpConnexion']; $idFacture = $_POST['idFacture']; ini_set('soap.wsdl_cache_enabled', '0'); $wsdlURL = 'https://xxxx.com/Balm/Services_2_0.wsdl'; $ns = 'https://erp.xxxx.com/developerKey/'; $devKey = 'a1b2c3'; $soap = new SoapClient($wsdlURL); $soap->__setSoapHeaders(new SoapHeader($ns, 'developerKey', $devKey)); $params = new stdClass(); $params->context = 'Client'; $params->login = $idConnexion; $params->password = $mdpConnexion; $res = $soap->GetContactDevKey($params); $devKey2 = $res->result; $soap2 = new SoapClient($wsdlURL); $soap2->__setSoapHeaders(new SoapHeader($ns, 'developerKey', $devKey2)); $res2 = $soap2->Authenticate($params); $token = $res2->result->VisitorToken; $demandsParam = new stdClass(); $demandsParam->visitorKey = $token; $demandsParam->printType = 'PrintBill'; $demandsParam->id = $idFacture; $factures = $soap2->GetClientPrint($demandsParam); echo $factures->result->Content; ```
2015/04/22
[ "https://Stackoverflow.com/questions/29792555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3820640/" ]
Like the others have said, don't use Base64 as a means of comparing files, it would be much much less expensive to to use something like SHA1, particularly if you are using this for videos. [See the sha1\_file function](http://php.net/sha1_file "see the sha1_file function") For example if you already have a SHA1 sum, it is easy to compare: ``` if ($storedSHA1 == sha1_file($newImage)){ // ...some rejection code } ``` I'd recommend creating a database table that stores the name, size and SHA1 of each file you upload. Then you can run a simple query to check if any of the records match. If you have a match in your database you know you have a duplicate. See the below MySQL query. ``` SELECT SHA1_hash FROM Uploads WHERE SHA1_hash = '<hashOfIncomingImage>'; ```
You want to use hash functions for that, for example, Sha1. It always returns a 40 character wich you can use to compare.
65,372,060
I am trying to get GoogleSign in working with a webapp in flutter, and for that I have been following an article. This is the function they said to use there for the login: ``` Future<String> signInWithGoogle() async { // Initialize Firebase await Firebase.initializeApp(); final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn(); final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication; final AuthCredential credential = GoogleAuthProvider.credential( accessToken: googleSignInAuthentication.accessToken, idToken: googleSignInAuthentication.idToken, ); final UserCredential userCredential = await _auth.signInWithCredential(credential); final User user = userCredential.user; if (user != null) { // Checking if email and name is null assert(user.uid != null); assert(user.email != null); assert(user.displayName != null); assert(user.photoURL != null); uid = user.uid; name = user.displayName; userEmail = user.email; imageUrl = user.photoURL; assert(!user.isAnonymous); assert(await user.getIdToken() != null); final User currentUser = _auth.currentUser; assert(user.uid == currentUser.uid); SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setBool('auth', true); return 'Google sign in successful, User UID: ${user.uid}'; } return null; } ``` It says that SharedPreferences is an undefined class. What does this do? Is it neccesary? If yes, how can I fix this? Thank you very much for your help, as this is my first time working with google sign-in in flutter web.
2020/12/19
[ "https://Stackoverflow.com/questions/65372060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13860161/" ]
``` (letfn [(my-loop [f n result] (if (< n 1) result (recur f (dec n) (f result))))] (my-loop inc 2 1)) ```
Thanks for help, my solution is: ``` (defn my-loop [f n result] (if (< n 1) result (my-loop f (dec n) (f result)))) (my-loop inc 2 1) ```
25,927,521
*The above link to a possible duplicate is not a solution for this case, because the height will be a fixed value for several breakpoints.* I have some DIVs with `display:inline-block`, so they are floating nicely side by side. These DIVs all have the same height, e.g. `height:300px`. Later, I will load an image inside every DIV with Ajax, and I want the DIV to keep the aspect ratio of the image, so they won't wiggle all around, when the image is actually loaded. So when the DIVs are displayed in the browser, the images are not yet there, so fixing the height for the image with `height:auto;` won't work. **Sample code:** ``` <div class="wrapper"> <div class="item">...</div> <div class="item">...</div> <!-- More items here --> </div> ``` **CSS:** ``` .item { display:inline-block; vertical-align:top; height: 300px; width: /* depending on the image ratio */ } ``` Now I know how to **keep the aspect ratio of an element for a given width** (see [here](http://www.mademyday.de/css-height-equals-width-with-pure-css.html) or [here](http://wellcaffeinated.net/articles/2012/12/10/very-simple-css-only-proportional-resizing-of-elements/)). But since my DIVs should all have the same height, how can I keep the aspect ratio and change just the width? One (not really good) solution would be to insert a blank image and to resize this image to the right dimensions. The problem is: when resizing the window, the height of all the DIVs will change, so just calculating the width is not enough. I could recalculate the width with Javascript, but I prefer a plain CSS version (if possible). **So here is my question:** how can I keep the aspect ratio for an element for a given height by CSS only? Thanks
2014/09/19
[ "https://Stackoverflow.com/questions/25927521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1107529/" ]
When running project with cloud9 runners there is Environment popup on the right side of the runner toolbar. You can use it to add environment variables the way you want, but make sure to not add a name to the config since configs with name are automatically saved in .c9/project.settings Another solution is to create a file in the directory not exposed in readOnly mode. e.g ``` echo "password" | sudo tee /xxx ``` you can even edit `/xxx` file using `vi` inside cloud9 terminal. But Of course the best solution is to buy premium subscription, and get more private workspaces:)
You can define environment variables in `~/.profile`. Files outside of the workspace directory `/home/ubuntu/workspace` are not accessible for read only users. You can do e.g. ``` $ echo "export SECRET=geheim" >> ~/.profile ``` to define the variable `SECRET` and then use it through `process.env.SECRET` from your application. The runners (from the "run" button) and the terminal will evaluate `~/.profile` and make the environment variable available to your app.
55,424,709
I have this inside my render: ``` {this.availProps(this.state.data)} ``` `this.state.data` is updated with a fetch when componentOnMount ``` availProps = data =>{ if (data.length == 0) return ( <option>"hello"</option> ) else return ( <option> "hi" </option> ) } ``` It prints out "hi" just fine when the data is done fetching. However, if I use: ``` {this.availProps()} ``` and ``` availProps = () =>{ if (this.state.data.length == 0) return ( <option>"hello"</option> ) else return ( <option> "hi" </option> ) } ``` It will not work. It prints out "hello" instead. Is this because the page is only rerendered if a variable inside the "render" is changed/updated? ( in this case, this.state.data) Thank you edit: here is the componentDidMount ``` componentDidMount() { this.getDataFromDb() } getDataFromDb = () => { fetch("http://localhost:3001/api/property") .then(property => property.json()) .then(res => this.setState({ data: res.data })) .then(() =>{ for(var i = 0; i < this.state.data.length; i++) { if (this.state.data[i].status == 0) this.state.useData.push(this.state.data[i]) } }).then ( ()=> console.log(this.state.useData)) }; ```
2019/03/29
[ "https://Stackoverflow.com/questions/55424709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9474198/" ]
Setting the property directly on `this.state` does not invoke the render method. You will have to use `this.setState({ useData: useData })` so that react will that something has changed which runs the render method. And since the state that is being set is based on the previous state, it is better you use state updater pattern and its callback so that the updated state is available when you try to access it. [Do not update state directly](https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly) ```js getDataFromDb = () => { fetch("http://localhost:3001/api/property") .then(property => property.json()) .then(res => this.setState({ data: res.data })) .then(() => { // Your computations are based on previous state // use the updater function to have access to the latest // state as state updates are asynchronous this.setState((previousState) => { const { data } = previousState; // accessing this.state here might have stale data const updatedUseData = data.reduce((acc, obj) => { if (obj.status === 0) { acc.push(obj); } return acc; }, []); // this will invoke the render again as // a state is updated return { useData: updatedUseData } }, () => { // Use the call back which gets invoked once the state // is updated console.log(this.state.useData) }) }) } ```
A component will rerender by default if a value from `props` or `state` is changed, which is being used in the render or in a function that the render is calling. If you had a class-level variable, such as `this.example` and were using that in the render, changing that value wouldn't make the component rerender. You can also override `shouldComponentUpdate` to prevent the component from re-rendering when certain values of `props` or `state` changes, if you wish to do that. You can read more about that [here](https://reactjs.org/docs/react-component.html#shouldcomponentupdate). As it says, it's not recommended to do this, unless you're confident that you're handling it correctly. --- **EDIT** As the other answer suggests, only values updated using `this.setState` will cause a re-render. Doing something like: ``` this.state.useData.push(this.state.data[i]) ``` will not cause it to update. I'd suggest the following change to `getDataFromDb` to handle this ``` getDataFromDb = () => { fetch("http://localhost:3001/api/property") .then(property => property.json()) .then(res => { this.setState({ data: res.data, useData: res.data.filter(item => item.status === 0) }); }).then ( ()=> console.log(this.state.useData)) }; ``` Just as an aside, `setState` is async so `console.log` on the `.then` won't necessarily see this change yet.
47,640,963
I have a custom class in VBA that pulls historical data from Bloomberg. The class, and the Bloomberg objects it uses, are asynchronous and based on the RTD platform. The issue I'm having is that I run Subs that call this custom class, but the event handling code in the custom class only runs once my Sub is finished. ``` Dim bbHist As New HistDataControl Sub PullDataAndDoStuff() bbHist.MakeHistRequest StockTicker, "MOV_AVG_50D", startDate, Date Call DoStuffWithTheData End Sub Private Sub DoStuffWithTheData() ..... 'None of this works, because MakeHistRequest / bbHist class hasn't run End Sub ``` Is there a way to force Excel to wait until the bbHist has run?
2017/12/04
[ "https://Stackoverflow.com/questions/47640963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/558619/" ]
If it has a property to check to see if it's done, then you can just put a `DoEvents` in a `Do Until` loop, checking that property for its completion.
The problem is that the bbg handler waits. So the solution is to make your sub wait for the bbg query to end, and then call your processing data sub. There are plenty of solutions for that on stackoverflow so I'll let you look for that.
185,254
I am using Microsoft Dynamics NAV 2009's Role-Tailored Client (RTC), which utilizes a 3-tier architecture. The middle tier, which Microsoft calls the service tier, is a non-cluster-aware application that runs as a Windows service. I've identified through [another question](https://serverfault.com/questions/182725/) that I should pursue running a clustered hypervisor with a virtual machine running the NAV Service Tier. Unfortunately, the NAV Service Tier has a recommended maximum user capacity of 50-60 users. With over 100 concurrent users, I will need some mechanism to "load balance" all of the sessions without having to visit each user's workstation and "hard-code" it to a specific server. Sessions will need to be sticky in that every request after the initial request will need to be routed to the same server. How can I load balance a Windows service which is not IIS-based and meets the requirements I've outlined?
2010/09/28
[ "https://serverfault.com/questions/185254", "https://serverfault.com", "https://serverfault.com/users/43374/" ]
I think [Windows Network Load Balancing](http://technet.microsoft.com/en-us/library/cc736597(WS.10).aspx) (NLB) will work for you - it uses multicast to allow multiple servers to be accessed by the same IP address. The servers decide between themselves which one will handle a request. It can be configured to be sticky (session affinity). Be aware however, that it only offers redundancy in terms of whether a server is up or down - it can't decide which server in the cluster is under less load. Most documentation out there will discuss IIS and NLB, but it works for RDP and other applications. I have had some issues using this over Dell PowerConnect switches in a high load scenario, and would be inclined to go for a more heavyweight load balancing solution, but I think for your purposes it is the best place to start. It's free with Windows Server.
How do the clients "find" the middle tier? Is [round robin DNS](http://en.wikipedia.org/wiki/Round_robin_DNS) an option for you?
51,746,687
Hi i am using SAP JCo3 connector along with .dll file provided with the jar. the destination is successfully connected. My problem is that when i am doing the function.execute(destination) the function.getTableParameterList().getTable("PART\_LIST") returns an empty table with zero rows My code to achieve the connectivity is as below ``` JCoDestination dest = JCoDestinationManager.getDestination("EOMP"); dest.ping(); JCoRepository repo= dest.getRepository(); JCoFunctionTemplate ftemplate = repo.getFunctionTemplate("Z_BAPI_GET_ESO_PART"); JCoFunction function = ftemplate.getFunction(); JCoParameterList importParams = function.getImportParameterList(); importParams.setValue("ESO","R1S00444"); importParams.toXML(); function.execute(dest); JCoParameterList tableParamList=function.getTableParameterList(); JCoTable table=tableParamList.getTable("PART_LIST"); ```
2018/08/08
[ "https://Stackoverflow.com/questions/51746687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7516269/" ]
``` =IF(E3="SSCBB",(H3/2.4),IF(E3="SSTCB",(H3/3.2),"")) ``` This method seemed to work. just declaring through data validation list boxes and this IF.
Personaly i'am not sure why you searching for VBA solution but putting this formula to "count will be much better solution in my opinion : =if(A2="SSOBB";B2/2,4;if(A2="SSTCB";B2/2,4;"Nothing to calculate")) \*=if( [your combobox]="Beam type";[your cell with length] / [value you want to divide with]; [ now add another if how many times you need ]; [and in the ind just value you want to show if nothing match])) i hope i helped
10,439,277
In my layout, I have a devise sign in / sign out link, like so: ``` =if user_signed_in? then link_to "_", destroy_user_session_path, :method => :delete else link_to "_", new_user_session_path, :method => :get end ``` This uses the rails helpers to build up the link, and resolves to the following HTML: ``` <a data-method="get" href="/users/sign_in">_</a> ``` I'm converting all links to buttons, and have just passed in URLs to onClick functions to redirect the browser. In this case, I don't think a simple redirect will do the trick, because I need to specify the HTTP method. Is this the right way to do this, and if so, how do I tell Javascript about the HTTP method? Thank you
2012/05/03
[ "https://Stackoverflow.com/questions/10439277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215687/" ]
Ok, I tried XMLHttpRequest, but couldn't get it to work. I ended up doing this, which is kind of hacktastic, but it works: ``` login = function(url) { $.ajax({ url: url, type: "GET" }).done(function(){ window.location.href = url; }); ``` } ``` logout = function(url) { $.ajax({ url: url, type: "DELETE" }).done(function(){ window.location.href = "/"; }); ```
Most browsers do not support the full gamut of HTTP verbs. As such Rails uses a hidden variable to specify the intended HTTP method. You'll need to update the `<input type="hidden" name="_method" ... />` field to alter the HTTP verb that Rails uses during RESTful routing.
8,358,584
For small size image what's (if any) the benefit in loading time using base64 encoded image in a javascript file (or in a plain HTML file)? ``` $(document).ready(function(){ var imgsrc = "../images/icon.png"; var img64 = "P/iaVYUy94mcZxqpf9cfCwtPdXVmBfD49NHxwMraWV/iJErLmNwAGT3//w3NB"; $('img.icon').attr('src', imgsrc); // Type 1 $('img.icon').attr('src', 'data:image/png;base64,' + img64); // Type 2 base64 }); ```
2011/12/02
[ "https://Stackoverflow.com/questions/8358584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/220180/" ]
The benefit is that you have to make one less HTTP request, since the image is "included" in a file you have made a request for anyway. Quantifying that depends on a whole lot of parameters such as caching, image size, network speed, and latency, so the only way is to measure (and the actual measurement would certainly not apply to everyone everywhere). I should mention that another common approach to minimizing the number of HTTP requests is by using [CSS sprites](http://css-tricks.com/158-css-sprites/) to put many images into one file. This would arguably be an even more efficient approach, since it also results in less *bytes* being transferred over (base64 bloats the byte size by a factor of about 1.33). Of course, you do end up paying a price for this: decreased convenience of modifying your graphics assets.
It saves you a request to the server. When you reference an image through the src-property, it'll load the page, and then do the additional request to fetch the image. When you use the base64 encoded image, it'll save you that delay.
8,358,584
For small size image what's (if any) the benefit in loading time using base64 encoded image in a javascript file (or in a plain HTML file)? ``` $(document).ready(function(){ var imgsrc = "../images/icon.png"; var img64 = "P/iaVYUy94mcZxqpf9cfCwtPdXVmBfD49NHxwMraWV/iJErLmNwAGT3//w3NB"; $('img.icon').attr('src', imgsrc); // Type 1 $('img.icon').attr('src', 'data:image/png;base64,' + img64); // Type 2 base64 }); ```
2011/12/02
[ "https://Stackoverflow.com/questions/8358584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/220180/" ]
You need to make multiple server requests, lets say you download a contrived bit of HTML such as: ``` <img src="bar.jpg" /> ``` You already needed to make a request to get that. A TCP/IP socket was created, negotiated, downloaded that HTML, and closed. This happens for every file you download. So off your browser goes to create a new connection and download that jpg, `P/iaVYUy94mcZxqpf9cfCwtPdXVmBfD49NHxwMraWV/iJErLmNwAGT3//w3NB` The time to transfer that tiny bit of text was massive, not because of the file download, but simply because of the negotiation to get to the download part. That's a lot of work for one image, so you can in-line the image with base64 encoding. This doesn't work with legacy browsers mind you, only modern ones. The same idea behind base64 inline data is why we've done things like closure compiler (optimizes speed of download against execution time), and CSS Spirtes (get as much data from one request as we can, without being too slow). There's other uses for base64 inline data, but your question was about performance. Be careful not to think that the HTTP overhead is so massive and you should only make one request-- that's just silly. You don't want to go overboard and inline all the things, just really trivial bits. It's not something you should be using in a lot of places. Seperation of concerns is good, don't start abusing this because you think your pages will be faster (they'll actually be slower because the download for a single file is massive, and your page won't start pre-rendering till it's done).
It saves you a request to the server. When you reference an image through the src-property, it'll load the page, and then do the additional request to fetch the image. When you use the base64 encoded image, it'll save you that delay.
8,358,584
For small size image what's (if any) the benefit in loading time using base64 encoded image in a javascript file (or in a plain HTML file)? ``` $(document).ready(function(){ var imgsrc = "../images/icon.png"; var img64 = "P/iaVYUy94mcZxqpf9cfCwtPdXVmBfD49NHxwMraWV/iJErLmNwAGT3//w3NB"; $('img.icon').attr('src', imgsrc); // Type 1 $('img.icon').attr('src', 'data:image/png;base64,' + img64); // Type 2 base64 }); ```
2011/12/02
[ "https://Stackoverflow.com/questions/8358584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/220180/" ]
The benefit is that you have to make one less HTTP request, since the image is "included" in a file you have made a request for anyway. Quantifying that depends on a whole lot of parameters such as caching, image size, network speed, and latency, so the only way is to measure (and the actual measurement would certainly not apply to everyone everywhere). I should mention that another common approach to minimizing the number of HTTP requests is by using [CSS sprites](http://css-tricks.com/158-css-sprites/) to put many images into one file. This would arguably be an even more efficient approach, since it also results in less *bytes* being transferred over (base64 bloats the byte size by a factor of about 1.33). Of course, you do end up paying a price for this: decreased convenience of modifying your graphics assets.
You need to make multiple server requests, lets say you download a contrived bit of HTML such as: ``` <img src="bar.jpg" /> ``` You already needed to make a request to get that. A TCP/IP socket was created, negotiated, downloaded that HTML, and closed. This happens for every file you download. So off your browser goes to create a new connection and download that jpg, `P/iaVYUy94mcZxqpf9cfCwtPdXVmBfD49NHxwMraWV/iJErLmNwAGT3//w3NB` The time to transfer that tiny bit of text was massive, not because of the file download, but simply because of the negotiation to get to the download part. That's a lot of work for one image, so you can in-line the image with base64 encoding. This doesn't work with legacy browsers mind you, only modern ones. The same idea behind base64 inline data is why we've done things like closure compiler (optimizes speed of download against execution time), and CSS Spirtes (get as much data from one request as we can, without being too slow). There's other uses for base64 inline data, but your question was about performance. Be careful not to think that the HTTP overhead is so massive and you should only make one request-- that's just silly. You don't want to go overboard and inline all the things, just really trivial bits. It's not something you should be using in a lot of places. Seperation of concerns is good, don't start abusing this because you think your pages will be faster (they'll actually be slower because the download for a single file is massive, and your page won't start pre-rendering till it's done).
24,550,706
it is possible to change the url rewrite in a cake app ? Actually it's like this : > > <http://myapp.fr/myapp/admin/users/view/30> > > > I want to hide everything after the ".fr" in every page, like this : > > <http://myapp.fr/> > > > Thank you for your help.
2014/07/03
[ "https://Stackoverflow.com/questions/24550706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2914289/" ]
A foreign key constraint is from one table's columns to another's columns, so, no. Of course the database should have a table COUNTRY(country\_id). Commenters have pointed out that your admin is imposing an anti-pattern. Good, you are aware that you can define a column and set it to the value you want and make the foreign key on that. That is an idiom used for avoiding triggers in constraining some subtyping schemes. You may be able to compute a 'COUNTRY' column depending on your DBMS, at least. Your question is essentially [this one](https://dba.stackexchange.com/questions/62537/how-can-i-create-a-foreign-key-to-a-compound-primary-key-with-a-single-column), see the end of the question & the comments & answers. (Lots of functionality would be trivial to implement. Perhaps the difficulty (besides ignorance of consumers) is that arbitrary constraints become quickly expensive computationally. That might just get vendors aggravation. Also, optimization in SQL is impeded by its differences from the relatonal model.)
For Posrgres not having computed (or constant) columns, you can force them to a fixed value column, using `DEFAULT` plus (maybe) a check. This may be ugly, but it works: ``` CREATE TABLE dictionaries ( id integer primary key , typename varchar NOT NULL CHECK ( typename IN ('person' ,'animal' ,'plant' )) , content varchar NOT NULL -- ... , UNIQUE (typename, id) , UNIQUE (typename, content) ); CREATE TABLE person ( id integer primary key , typename varchar NOT NULL DEFAULT 'person' CHECK( typename IN ('person' )) , species_id integer -- ... , FOREIGN KEY (typename, species_id) REFERENCES dictionaries(typename, id) -- DEFERRABLE INITIALLY DEFERRED ); INSERT INTO dictionaries( id, typename, content) VALUES ( 1 , 'person' , 'Bob') ,( 2 , 'person' , 'Alice') ,( 11 , 'animal' , 'monkey') ,( 12 , 'animal' , 'cat') ,( 13 , 'animal' , 'dog') ,( 21 , 'plant' , 'cabbage') ; SELECT * FROM dictionaries; -- this should succeed INSERT INTO person( id, species_id) VALUES ( 1,1 ) ,( 2,2 ) ; -- this should fail INSERT INTO person( id, species_id) VALUES ( 3,11 ) ,( 4,12 ) ; ```
10,532,001
Programming in C# I got an Xml.XpathNodeList object "ResultsPartRel.nodeList". Debugging it with Visual Studio I can read "Results View ; Expanding the Results View will enumerate the IEnumerable" **Questions:** 1.- Which is the best way to read those nodes? 2.- I program the next code but I dont get the expected results. I get the same result twice. (ResultsPartRel.nodeList contains 2 nodes) ``` List<string> childrenName = new List<string>(); foreach (XmlElement node in ResultsPartRel.nodeList) { string nameChildren = node.SelectSingleNode("//related_id/Item/keyed_name").InnerText; childrenName.Add(nameChildren); } ``` Thank you in advance. **EDIT** ``` <related_id> <Item> <classification>Component</classification> <id></id> <keyed_name>glass</keyed_name> <!-- I want to get this InnerText --> </Item> </related_id> <source_id>968C45A47942454DA9B34245A9F72A8C</source_id> <itemtype>5E9C5A12CC58413A8670CF4003C57848</itemtype> ```
2012/05/10
[ "https://Stackoverflow.com/questions/10532001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1214129/" ]
Well we really need to see the XML sample and a verbal explanation of which data you want to extract. Currently you do a `node.SelectSingleNode(...)` so that looks as if you want to select a path relative to `node` but then you use an absolute path starting with `//`, that is why you get the same result twice. So you want `node.SelectSingleNode(".//related_id/Item/keyed_name")` or perhaps even `node.SelectSingleNode("related_id/Item/keyed_name")`, depending on the XML you have.
You can get the first element. (With the "//" means search for all following tags, so you will probably get more results).When you want the first element write "//related\_id/Item/keyed\_name\**[1](https://addons.mozilla.org/en-US/firefox/addon/xpath-checker/)*\*". Or you can write the exact path.(this is the safest way) To make it easy for yourself there is a Firefox extension [xPath Checker](https://addons.mozilla.org/en-US/firefox/addon/xpath-checker/) load the document in firefox than right click the element and show Xpath. Then you get a exact path.
892
Is there a method for storing one-to-many relationships within a table? Say I had a Player, and the player had multiple Tickets. How could I store multiple ticket primary keys within one player?
2018/06/16
[ "https://eosio.stackexchange.com/questions/892", "https://eosio.stackexchange.com", "https://eosio.stackexchange.com/users/1195/" ]
> > I have bought some eos on Binance. Now i m looking a way to create a wallet on eos mainnet in order to get my eos from Binance. But There is no simple way and decentralized information about HOW to create a wallet and account. > > > Please confirm Binance are allowing withdrawals and that they aren't offering an account creation service. Accounts can only be registered by another EOS account on the main net as it costs to do so. Wallet wise, we'll take it from the start. If you have cleos installed on your local machine then keosd should run in order to create a wallet. Create a blank wallet with `cleos create wallet` This will return a password to open the wallet, store this safe, write it down, make sure you have a copy of this outside of your computer generating it. Create a new EOS keypair on your local computer using cleos, this is the best method IMO, it's bad practice to use random key generators on the net. `cleos create key` Now, we can import this into the wallet with `cleos wallet import *Private Key*` It should return the public key back, copy this in your clipboard. > > For what i have understood, FIRST\_PUB\_KEY is the key from the account eosio and the SECOND\_PUB\_KEY is a key generated by myself from the above link generator. > > > No, `FIRST_PUB_KEY` and `SECOND_PUB_KEY` are both for your account, the first public key determines the public key for the owner permission, the second determines the active permission. Both of these keys are something only you know and generate. In this example, we can use the same public key twice, however, if you'd like to be more secure then just repeat the commands. `cleos create wallet` `cleos import wallet *private key*` *Clipboard the returned public key* To create an account, assuming the IP in the -u switch is <http://130.211.59.178:8888> is an endpoint which goes to the main net. ``` cleos -u http://130.211.59.178:8888 system newaccount --stake-net "0.1000 EOS" --stake-cpu "0.1000 EOS" --buy-ram-kbytes 8 eosio myDesiredAccountName *Clipboard key* *Clipboard key* ```
If you don't have an EOS account yet, you need to go through an account creation service like the one I created: <https://eos-account-creator.com/> Once your new EOS account is created, you can withdraw your EOS tokens to it.
27,783,268
I have a php statement to insert a bit of information into my mySQL database. the connection works perfectly. The problem I am having is I am getting the following error code: > > Error: INSERT INTO tasks ('taskName', 'requestedBy', 'details', > 'dateAdded') VALUES ('test1' ,'test3' ,'test3', 2015-01-05') You have > an error in your SQL syntax; check the manual that corresponds to your > MySQL server version for the right syntax to use near ''taskName', > 'requestedBy', 'details', 'dateAdded') VALUES ('test1' ,'test3' ,'te' > at line 1 > > > the function is as follows ``` if(isset($_POST["submitTask"])){ insertTask(); }; function insertTask(){ $servername = "localhost"; $username = "tasktrack"; $password = ""; $dbname = "tasktrack"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $taskname = $_POST["task_name"]; $requestedby= $_POST["requested_by"]; $details = $_POST["details"]; $datenow = date("Y-m-d"); $sql = "INSERT INTO tasks ('taskName', 'requestedBy', 'details', 'dateAdded') VALUES ('$taskname' ,'$requestedby' ,'$details', $datenow')"; if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); }; ``` I have tried multiple different solution with the `$sql` line as seen below ``` $sql = "INSERT INTO tasks ('taskName', 'requestedBy', 'details', 'dateAdded') VALUES ('$taskname' ,'$requestedby' ,'$details', $datenow')"; $sql = "INSERT INTO tasks (taskName, requestedBy, details, dateAdded) VALUES ($taskname ,$requestedb ,$details, $datenow)"; $sql = "INSERT INTO tasks (`taskName`, `requestedBy`, `details`, `dateAdded`) VALUES (`$taskname` ,`$requestedb` ,`$details`, `$datenow`)"; ``` Now I am just stuck and can't think of any more things to try.
2015/01/05
[ "https://Stackoverflow.com/questions/27783268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3266752/" ]
``` $sql = "INSERT INTO tasks (taskName, requestedBy, details, dateAdded) VALUES ('$taskname' ,'$requestedby' ,'$details', '$datenow')"; // Removed quotes from columns, and added missing quote on datenow ``` Please note, this technique for adding values into the database is very insecure, and is prone to SQL injection attacks.
You must not enclose the field names in apostrophes or quotes. Either enclose them in back quotes (`) or use them as they are. ``` $sql = "INSERT INTO tasks (`taskName`, `requestedBy`, `details`, `dateAdded`) VALUES ('$taskname' ,'$requestedby' ,'$details', '$datenow')"; ``` or ``` $sql = "INSERT INTO tasks (taskName, requestedBy, details, dateAdded) VALUES ('$taskname' ,'$requestedby' ,'$details', '$datenow')"; ``` However, if the field name is a MySQL keyword or if it contains spaces, quotes, commas, parenthesis, operators or other characters that have special meaning in SQL then you have to enclose them in back quotes or MySQL will report a syntax error at the special character.
3,469,669
I am planning to create a pricing matrix for a project in Rails. It's supposed to be a table of destinations and departure locations, and prices depending on where you came and are planning to go. I am kinda undecided on how to better do this: either making a table in the db for this matrix, or making a mega array of constants. Problem is, the client should be able to edit this matrix so its most likely going the database route. Anyhow, what's a good schema for this? Destination id, Departure id, then price? destination and departure ids will be foreign keys for a table containing all possible locations. Is there a better way of doing this?
2010/08/12
[ "https://Stackoverflow.com/questions/3469669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/334545/" ]
Make it a db table. The only thing constant about prices is that they change. Added: Pricing (also called product factoring) is something that I have a lot of experience with. Your clients may also ask/or appreciate added pricing tools to help them get things right. Eg, your sw: * could have reports that show the the prices in a manner that is designed for the people doing the pricing. * report on the highest, lowest prices (to help catch data entry errors) * Check out visual design of quantitative information for ideas on how to visually show the prices for the destination pairs * make sure that a destination/departure pair is only added exactly once. (No duplicates in the other direction.) * etc You may also need to worry about effective dates for the pricing. Ie how to roll-out a new set of prices in a co-ordinated way.
I would add this to a 3-column table because it's not necessarily a matrix - you might not travel from all places to all other places. You want to be able to edit it. As soon as you are done with your hard-coded version, you'll be asked to edit it. ``` LeavingFrom, TravellingTo, Price ``` Also, as the list of destinations grows, query performance and code maintenance will become a factor.
3,469,669
I am planning to create a pricing matrix for a project in Rails. It's supposed to be a table of destinations and departure locations, and prices depending on where you came and are planning to go. I am kinda undecided on how to better do this: either making a table in the db for this matrix, or making a mega array of constants. Problem is, the client should be able to edit this matrix so its most likely going the database route. Anyhow, what's a good schema for this? Destination id, Departure id, then price? destination and departure ids will be foreign keys for a table containing all possible locations. Is there a better way of doing this?
2010/08/12
[ "https://Stackoverflow.com/questions/3469669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/334545/" ]
Make it a db table. The only thing constant about prices is that they change. Added: Pricing (also called product factoring) is something that I have a lot of experience with. Your clients may also ask/or appreciate added pricing tools to help them get things right. Eg, your sw: * could have reports that show the the prices in a manner that is designed for the people doing the pricing. * report on the highest, lowest prices (to help catch data entry errors) * Check out visual design of quantitative information for ideas on how to visually show the prices for the destination pairs * make sure that a destination/departure pair is only added exactly once. (No duplicates in the other direction.) * etc You may also need to worry about effective dates for the pricing. Ie how to roll-out a new set of prices in a co-ordinated way.
I would use two tables, Location and TravelPrice. ``` Location ---------- LocationID --PK Name TravelPrice ------------- TravelPriceID --PK DepartureLocationID --FK to Location DestinationLocationID --FK to Location Price StartDate --date the price is effective from EndDate --date the price is effective to (or NULL) ``` This allows you to keep a price history, important for reporting, billing, etc. Ideally you would have trigger on the `TravelPrice` table ensuring that there are no gaps or overlaps in dates for a given `DepartureLocationID`/`DestinationLocationID` combination, and that there is only one record with a NULL `EndDate` for that pair.
3,469,669
I am planning to create a pricing matrix for a project in Rails. It's supposed to be a table of destinations and departure locations, and prices depending on where you came and are planning to go. I am kinda undecided on how to better do this: either making a table in the db for this matrix, or making a mega array of constants. Problem is, the client should be able to edit this matrix so its most likely going the database route. Anyhow, what's a good schema for this? Destination id, Departure id, then price? destination and departure ids will be foreign keys for a table containing all possible locations. Is there a better way of doing this?
2010/08/12
[ "https://Stackoverflow.com/questions/3469669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/334545/" ]
I would use two tables, Location and TravelPrice. ``` Location ---------- LocationID --PK Name TravelPrice ------------- TravelPriceID --PK DepartureLocationID --FK to Location DestinationLocationID --FK to Location Price StartDate --date the price is effective from EndDate --date the price is effective to (or NULL) ``` This allows you to keep a price history, important for reporting, billing, etc. Ideally you would have trigger on the `TravelPrice` table ensuring that there are no gaps or overlaps in dates for a given `DepartureLocationID`/`DestinationLocationID` combination, and that there is only one record with a NULL `EndDate` for that pair.
I would add this to a 3-column table because it's not necessarily a matrix - you might not travel from all places to all other places. You want to be able to edit it. As soon as you are done with your hard-coded version, you'll be asked to edit it. ``` LeavingFrom, TravellingTo, Price ``` Also, as the list of destinations grows, query performance and code maintenance will become a factor.
182,932
I want to use Avahi tools for mDNS service discovery in CentOS 6.6. I have installed the following packages: avahi, avahi-tools, nss-mdns. I checked the Avahi daemon and it is running: ``` $ service avahi-daemon status avahi-daemon (pid 1365) is running... ``` But when I tried running the following avahi-browse command, it halted there and returned nothing: ``` $ avahi-browse --all ``` When I tried to launch the Avahi GUI window like the following: ``` $ avahi-discover bash: avahi-discover: command not found ``` Then I searched what Avahi-related packages are on my system: ``` $ rpm -qa | grep avahi avahi-autoipd-0.6.25-15.el6.x86_64 avahi-tools-0.6.25-15.el6.x86_64 avahi-glib-0.6.25-15.el6.x86_64 avahi-0.6.25-15.el6.x86_64 avahi-libs-0.6.25-15.el6.x86_64 avahi-ui-0.6.25-15.el6.x86_64 ``` I tried on another computer which runs on Ubuntu Linux and both avahi-browse and avahi-discover work fine. So why don't `avahi-browse` and `avahi-discover` work on my CentOS 6.6?
2015/02/04
[ "https://unix.stackexchange.com/questions/182932", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/33477/" ]
avahi-browse, avahi-discover is part of avahi-tools rpm in centos 6.x ``` sudo yum install avahi-tools avahi-ui-tools ``` to find out: ``` sudo yum provides avahi-browser ```
Make sure not just avahi-daemon works and is installed, but also avahi-utils. That was my problem. On debian its ``` sudo apt-get install avahi-utils ``` I've never used CentOS, so I don't know how the package manager works, but it should be something similar.
61,995,920
There is a file that is sometimes not owned by root I want my perl script in linux to basically check if a file is owned by root if it is delete it. Currently what I have `unlink("$File_Path/File_Name");` but this just deletes the file I want it to check if it's owned by root first then delete otherwise ignore. can you please guide me how I can achieve this I am out of ideas?
2020/05/25
[ "https://Stackoverflow.com/questions/61995920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13610996/" ]
The documentation for [stat](https://perldoc.perl.org/functions/stat.html) shows that the fifth element in the returned list is "*numeric user ID of file's owner*". The superuser account on \*nix *must* have uid of `0`, so ``` if ( (stat $fqn)[4] == 0 ) { unlink $fqn or die "Error with unlink($fqn): $!"; } ```
If you're doing this to a bunch of files in a folder somewhere, you might be better off by just one of these: ``` find /folder/somewhere/ -type f -user root -exec rm {} \; find /folder/somewhere/ -type f -user root -exec rm -i {} \; #interactive y/n each file find /folder/somewhere/ -type f -user root -print0 | xargs -r0 rm ``` You might also need `sudo` in front of `find`. Careful though, this is a kind of command that can do a lot of harm...
114,392
I have two Ghost 14 backups of my machine. One for the machine fully configured with apps after and XP install and one of the last update before i re-imaged it (it's XP, I re-image about once every six months). I recently wanted to try simply using my initial image in a virtual environment to do my testing that generally causes me to need to re-image. I used the VMWare converter to convert the Ghost images to a virtual machine to use in Virtual box but they fail to properly boot. They get stuck after the bios loads and windows begins loading. If I power down the machine and refire it it will go to the error screen in windows that asks if you would like to boot to a different mode. none selected make any difference. What are some possible errors I should look for in the conversion process or in my settings for the converter?
2010/02/28
[ "https://superuser.com/questions/114392", "https://superuser.com", "https://superuser.com/users/23312/" ]
**SphereXP** - the world's number one three-dimensional desktop. ![alt text](https://i.stack.imgur.com/OJxbp.jpg) **[YODM 3D](http://yodm-3d.uptodown.com/en/)** - Virtual Desktop Manager featuring the Cube 3D effect ![alt text](https://i.stack.imgur.com/gCnS9.png) **[Matodate](http://madotate.en.softonic.com/)** - Manage windows more easily in a 3D desktop ![alt text](https://i.stack.imgur.com/rBey4.jpg) **[BumpTop™](http://bumptop.com/)** is a fun, intuitive 3D desktop that keeps you organized and makes you more productive. ![alt text](https://i.stack.imgur.com/B1mJK.jpg)
Possibly [Shock 4Way3D](http://www.docs.kr/entry/Download-Shock-4Way3D-en)? ![alt text](https://i.stack.imgur.com/ntVWu.png)