qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
45,988
On Windows I can use Utilu Firefox collection (there also ie collection on his site). How can I use multiple browser versions to see how my website works in different versions of different browsers in OS X? For example I want to install [browsers with biggest market share](https://en.wikipedia.org/wiki/Browser_market_share#Summary_table): * Internet Explorer * Firefox 3.6, latest and previous * Google Chrome latest and previous * Safari (any older versions possible) * Opera
2012/03/26
[ "https://apple.stackexchange.com/questions/45988", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/14692/" ]
Firefox ------- [Firefoxes](https://github.com/omgmog/install-all-firefox) is a shell scripts that will install all major versions of Firefox on OS X, and set up separate profiles so you can use them simultaneously. Currently it installs: * Firefox 2.0.0.20 * Firefox 3.0.19 * Firefox 3.5.9 * Firefox 3.6.28 * Firefox 4.0.1 * Firefox 5.0.1 * Firefox 6.0.1 * Firefox 7.0.1 * Firefox 8.0.1 * Firefox 9.0.1 * Firefox 10.0.2 * Firefox 11.0 * Firefox Beta * Firefox Aurora * Firefox Nightly * Firefox UX Nightly You can set it up so it only installs the specific versions you want. Optionally, the script can install Firebug for each version of Firefox too. It will also set icons that contain the version number: ![](https://i.stack.imgur.com/FnlXM.png) Safari ------ For Safari, check out [Multi-Safari](http://michelf.com/projects/multi-safari/). Chrome/Chromium --------------- For Chrome/Chromium, install any version you want, change the app name from `Chromium.app` to e.g. `Chromium 19.app` for clarity, then [disable auto-updates](http://dev.chromium.org/administrators/turning-off-auto-updates) for that version. Opera ----- Download old Opera versions here: <ftp://ftp.opera.com/pub/opera/mac/> IE -- Get VirtualBox and then run [this `ievms` script](https://github.com/xdissent/ievms). It will automatically download legal Windows images for testing purposes and set up virtual machines for every IE version you need.
While not actually on your machine, you can also use a web application like [BrowserShots.org](http://browsershots.org/) to deliver you screenshots of the page rendered in a multitude of browsers or something like [Adobe's BrowserLab](https://browserlab.adobe.com/en-us/index.html#).
38,210,037
I have a console script in a Yii2 advanced installation from which I can successfully use several models under 'common\models\modelName', but when I try to use a model from under 'backend\models\db\AuthAssignment' I get the following error: > > Exception 'yii\base\UnknownClassException' with message 'Unable to find 'backend\models\db\AuthAssignment' in file: /var/www/html/mvu/backend/models/db/AuthAssignment.php. Namespace missing?' > > > This model file starts as follows: ``` <?php namespace app\models\db; use Yii; class AuthAssignment extends \yii\db\ActiveRecord { ``` And the call from the console\controller file is as follows: ``` <?php namespace console\controllers; use Yii; use yii\console\Controller; use backend\models\db\AuthAssignment; use common\models\CourseLessons; use common\models\Courses; use common\models\Customer; use common\models\Users; class MijnvuController extends Controller { ``` What namespace could the error mean here and where to include it?
2016/07/05
[ "https://Stackoverflow.com/questions/38210037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3197616/" ]
Turns out that I needed to produce a duplicate of the specific model under 'frontend\models\db\AuthAssignment' because frontend and backend have similar functionality while running different databases. Called it accordingly and it works: ``` <?php namespace console\controllers; use Yii; use yii\console\Controller; use backend\models\db\AuthAssignment; use common\models\CourseLessons; use common\models\Courses; use common\models\Customer; use common\models\Users; class MijnvuController extends Controller { ```
You can not directly extend/use models from backend directory. To use models as per you requirements you need to add those models classes under console/models directory. and then in your console controller use like: ``` use app/models/Classname; ``` Try this link for more details <http://latcoding.com/2015/08/27/run-controller-yii2-via-console/>
47,820,182
I have a query (below) that uses ldap connection to retrieve AD related info. However, the issue is this query provide all of the employees. I am only looking for current employees. I was told to use following information to pull "Active only" employees: > > OU=CompanyName Users,DC=CompanyName,DC=local > > > I tried to modify below select statement to add OU related information, but query keeps failing. Anyone know how to convert above string into a proper ldap location? ``` SELECT * FROM OPENQUERY( ADLink, ' SELECT employeeNumber, name FROM ''LDAP://ldap.CompanyName.local/DC=CompanyName;DC=local'' WHERE objectClass = ''user'' AND objectCategory = ''Person'' ORDER BY title asc ') A ```
2017/12/14
[ "https://Stackoverflow.com/questions/47820182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2055916/" ]
To prevent error you have now - just make `sort` parameter non optional (move it to the beginning of parameter list and remove = `null`). If it fails to bind (for example, no sort is specified in query string) - it will have `null` value anyway, so there is no reason to have `= null` default in this case. Now, your sort specification is split over multiple query string parameters: ``` sort[0][field‌​]=tradeName&sort[0][‌​dir]=asc ``` so to bind it to your model, you will need a custom model binder. First create class to represent sort specification: ``` public class KendoSortSpecifier { public string Field { get; set; } public string Direction { get; set; } } ``` Then custom model binder (this is just an example, adjust to your own needs if necessary): ``` public class KendoSortSpecifierBinder : System.Web.Http.ModelBinding.IModelBinder { private static readonly Regex _sortFieldMatcher; private static readonly Regex _sortDirMatcher; const int MaxSortSpecifiers = 5; static KendoSortSpecifierBinder() { _sortFieldMatcher = new Regex(@"^sort\[(?<index>\d+)\](\[field\]|\.field)$", RegexOptions.Singleline | RegexOptions.Compiled); _sortDirMatcher = new Regex(@"^sort\[(?<index>\d+)\](\[dir\]|\.dir)$", RegexOptions.Singleline | RegexOptions.Compiled); } public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext) { if (bindingContext.ModelType != typeof(KendoSortSpecifier[])) return false; var request = actionContext.Request; var queryString = request.GetQueryNameValuePairs(); var result = new List<KendoSortSpecifier>(); foreach (var kv in queryString) { var match = _sortFieldMatcher.Match(kv.Key); if (match.Success) { var index = int.Parse(match.Groups["index"].Value); if (index >= MaxSortSpecifiers) continue; while (result.Count <= index) { result.Add(new KendoSortSpecifier()); } result[index].Field = kv.Value; } else { match = _sortDirMatcher.Match(kv.Key); if (match.Success) { var index = int.Parse(match.Groups["index"].Value); if (index >= MaxSortSpecifiers) continue; while (result.Count <= index) { result.Add(new KendoSortSpecifier()); } result[index].Direction = kv.Value; } } } bindingContext.Model = result.Where(c => !String.IsNullOrEmpty(c.Field)).ToArray(); return true; } } ``` And finally your controller method signature: ``` public IHttpActionResult GetTrades( [System.Web.Http.ModelBinding.ModelBinder(typeof(KendoSortSpecifierBinder))] KendoSortSpecifier[] sort, int page = -1, int pageSize = -1, int skip = -1, int take = -1) ``` Now you have strongly typed model of your sort (except `Direction` can be represented by enum instead of string) and can use it as necessary to sort your data.
I suggest you refactor your API method. Instead of feeding it route parameters, use a DTO like this: ``` public IHttpActionResult GetTrades(GetTradesRequestDTO model) { // method body } ``` This is a best-practice anyway, and model-binding issues are minimized. Also I'm not sure why you're giving default values of **-1** to your parameters. Instead use a zero-based index. This might be a personal preference but I'm not sure what is being achieved by these negative values. And finally your sort parameter needs a refactor too. It could be a list of strings, or a collection of strongly-typed models, each defining a sort action. i.e. `List<SortAction> sort;`. How you use this information and implement your back-end data access is irrelevant here. Refactoring your action method, model-binding and parameter data types should resolve your issue. Although I'm writing this from experience and haven't actually tested your code on my machine.
11,121,193
I found a way to write the `if` statement in another way (I think) while searching in the source code of a website. Instead of: ``` if(a)b; ``` or: ``` a?b:''; ``` I read: ``` !a||b; ``` Is the third way the same as the first two? And if yes, why we would use the third way?
2012/06/20
[ "https://Stackoverflow.com/questions/11121193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1365010/" ]
The third way is the same as the previous ones. One argument to use it is saving bytes. A strong argument against using it is readability. You'd better focus on readability in writing code, and use a minimizer (such as [Google Closure Compiler](http://closure-compiler.appspot.com)) to save bytes. It can be even shorter: ``` a && b; /* !a||b means: (not a) OR b which is equivalent to a AND b which turns out to be a && b */ ```
Welcome to the concept of [short-circuit evaluation](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Logical_Operators). This is well known property of logical operators, employed in different languages. Most often this'll be used as subexpression inside proper `if` or any other flow control statement, or to express condition short enough so it retains readability in this way, or by automatic transformation to save bytes. There's even tag for question regarding those: [short-circuiting](/questions/tagged/short-circuiting "show questions tagged 'short-circuiting'").
11,121,193
I found a way to write the `if` statement in another way (I think) while searching in the source code of a website. Instead of: ``` if(a)b; ``` or: ``` a?b:''; ``` I read: ``` !a||b; ``` Is the third way the same as the first two? And if yes, why we would use the third way?
2012/06/20
[ "https://Stackoverflow.com/questions/11121193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1365010/" ]
The third way is the same as the previous ones. One argument to use it is saving bytes. A strong argument against using it is readability. You'd better focus on readability in writing code, and use a minimizer (such as [Google Closure Compiler](http://closure-compiler.appspot.com)) to save bytes. It can be even shorter: ``` a && b; /* !a||b means: (not a) OR b which is equivalent to a AND b which turns out to be a && b */ ```
The result of the boolean expression sometimes can be evaluated without evaluating all the sub-expressions. If we have `A||B`, and `A` is true there's no need to even evaluate `B`, because the result will be true anyway. This behavior is called "shortcut boolean evaluation" and is defacto standard in most programming languages. It allows to write expressions like `if (i < A.length && A[i] == ...)` without evaluating the `A[i]` operand which can lead to an exception if `i` value is incorrect. In this particular case, `!a||b` is the same as `if(a)b`, yes, but the readability and maintainability of such code is a question though.
11,121,193
I found a way to write the `if` statement in another way (I think) while searching in the source code of a website. Instead of: ``` if(a)b; ``` or: ``` a?b:''; ``` I read: ``` !a||b; ``` Is the third way the same as the first two? And if yes, why we would use the third way?
2012/06/20
[ "https://Stackoverflow.com/questions/11121193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1365010/" ]
Welcome to the concept of [short-circuit evaluation](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Logical_Operators). This is well known property of logical operators, employed in different languages. Most often this'll be used as subexpression inside proper `if` or any other flow control statement, or to express condition short enough so it retains readability in this way, or by automatic transformation to save bytes. There's even tag for question regarding those: [short-circuiting](/questions/tagged/short-circuiting "show questions tagged 'short-circuiting'").
The result of the boolean expression sometimes can be evaluated without evaluating all the sub-expressions. If we have `A||B`, and `A` is true there's no need to even evaluate `B`, because the result will be true anyway. This behavior is called "shortcut boolean evaluation" and is defacto standard in most programming languages. It allows to write expressions like `if (i < A.length && A[i] == ...)` without evaluating the `A[i]` operand which can lead to an exception if `i` value is incorrect. In this particular case, `!a||b` is the same as `if(a)b`, yes, but the readability and maintainability of such code is a question though.
59,584,189
My problem: Want to display every letter after 1 second, but instead of this I display all the letters immediately. I have tried many ways to do this but still can't. My code: ``` const [parrot, setParrot] = useState({ content: ' ' }); const displayText = () => { let text = 'Parrot'; let freeLetters = [...text]; let sumOfLetters = []; for (let k = 0; k < freeLetters.length; k++) { (function() { let j = k; setTimeout(() => { sumOfLetters.push(freeLetters[j]); console.log(sumOfLetters); setParrot({ content: sumOfLetters.join(' ') }); console.log(parrot.content); }, 1000); })(); } }; return ( <div className={classes.contentwrapper}> <h1 onClick={() => displayText()}>Click me, {parrot.content}</h1> </div> ); ```
2020/01/03
[ "https://Stackoverflow.com/questions/59584189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11449471/" ]
Your timeouts are all set to 1000 milliseconds, you should multiply the timeout by the current index of the loop. What you need to do is increase the setTimeout wait value on each iteration of your loop. See a working example below. ``` const [parrot, setParrot] = useState({ content: ' ' }); const displayText = () => { let text = 'Parrot'; let freeLetters = [...text]; let sumOfLetters = []; for (let k = 0; k < freeLetters.length; k++) { (function() { let j = k; setTimeout(() => { sumOfLetters.push(freeLetters[j]); console.log(sumOfLetters); setParrot({ content: sumOfLetters.join(' ') }); console.log(parrot.content); }, 1000 * (j + 1)); // j + 1 because the loop starts at 0. // For the second iteration this will be 2000 ms // For the third, 3000 ms // Etc. })(); } }; return ( <div className={classes.contentwrapper}> <h1 onClick={() => displayText()}>Click me, {parrot.content}</h1> </div> ); ```
You're loop is just firing off an function that says in 1000ms do something. The loop will just continue to iterate and until the condition meets and then in your 1000ms, all of the setTimeouts will trigger almost back to back. You could either use the setInterval or maybe rewrite this to use a recursion loop based on some condition.
55,454
It's 2016, but for some reason, the Cold War never ended. You've been inspired by your (for some inexplicable reason) favorite movie, Indiana Jones 4, to start a new business: building refrigerators. However, the market is so saturated that in order to distinguish yourself with a nice marketing campaign, you decide to make them **NUKEPROOF!** The refrigerator should be: 1. Usable as a real refrigerator would be. 2. No bigger than standard double door refrigerator, so no room-sized walk-in refrigerator. Though, you *can* add some additional size for additional armor, for example, in **reasonable** margins, so nothing like 10 meters of iron from one side. 3. Protect one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion. How are you going to design it and what materials are you going to use?
2016/09/15
[ "https://worldbuilding.stackexchange.com/questions/55454", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/26768/" ]
While the it's-not-possible answers are correct for the question you intended to ask lets try another approach: For colder climates it's technically possible (but economic insanity) to build a refrigerator that contains no cooling element at all. Lets make the Green Fridge (tm): No ozone-destroying Freon! No toxic ammonia! No risk of incomplete combustion of the propane causing CO poisoning! Uses far less electricity than a normal refrigerator! You'll be safe against anything less than a direct hit by a nuke! Dig a big, deep hole. In the hole we put a large, very well insulated, very strong walk-in cooled space. Note that this will be at at least the sub-basement level, ideally it would be accessed by stairs or a ramp going down so as to minimize the air spill when the door is opened. There are two holes in the ceiling of the cooled space. Above the cooled space, separated by the insulation layer is a large concrete box. One of the holes from the ceiling connects to a U-shaped pipe (so the opening points down) in one corner of the box, the other to a pipe in the opposite corner that connects to the top, again with a U on the end. There is a large bimetallic thermometer on the first pipe that opens or closes a baffle in the pipe. There also must be a drain for the box. A pipe heading up goes into the third corner of the box, the box is filled with large gravel, a pipe is added in the last corner and it's roofed over and likewise very well insulated. Pipe #3 is insulated and extended to a surface air intake. There is a fan in this pipe (the only powered component in the whole thing!) that turns on when the outside air is colder than the air in the box. The final pipe vents back to the surface, ideally after running a bit through the ground first to dump its cold into the soil. Now the whole thing is covered over except for the vent pipes and however you plan to get to your storage space. You want some feet of dirt and then a moisture barrier layer and more dirt. Assuming you sized it big enough and the winters are cold enough this will work--you get a cold space for no more operating costs than running a fan in the winter. Note that so long as you are dealing with an airburst this should survive anything, although escape might be problematic. You have basically perfect radiation shielding, the only modification you'll need to make to ride out the nuke attack is to add a supply of compressed air to use while the firestorm burns overhead. (Note: In practice you would put the cold space on the bottom and use a fan to bring up the air, I was going for ultimate green. Also, the thermal mass needed is simply too great to be worth it. However, a related idea is in actual use by some people: Bury your house as indicated, run the air feeds through enough ground and you can climate-control your house with nothing but a fan. While the total heating/cooling needed is a lot greater the outside air will be in the right direction far more often and the natural ground temperature isn't too far below what you want for your house anyway.)
Add an asterisk to "Protect": > > Protect\* one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion. > > > \* Protect: the explosion will not kill you and the nuke will leave no lasting ill effects. Protection may also apply to others near fridge. Simply make a normal fridge with small extra box with a piece of string hanging out. "Nuke conversion"-kits also sold separately. In the event of an imminent nearby nuclear explosion simply enter the fridge, pull the string and the 40 kg of TNT in the box will explode, preventing the nuclear blast from killing you. Double your money back if the nuke kills you, upon personal application.
55,454
It's 2016, but for some reason, the Cold War never ended. You've been inspired by your (for some inexplicable reason) favorite movie, Indiana Jones 4, to start a new business: building refrigerators. However, the market is so saturated that in order to distinguish yourself with a nice marketing campaign, you decide to make them **NUKEPROOF!** The refrigerator should be: 1. Usable as a real refrigerator would be. 2. No bigger than standard double door refrigerator, so no room-sized walk-in refrigerator. Though, you *can* add some additional size for additional armor, for example, in **reasonable** margins, so nothing like 10 meters of iron from one side. 3. Protect one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion. How are you going to design it and what materials are you going to use?
2016/09/15
[ "https://worldbuilding.stackexchange.com/questions/55454", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/26768/" ]
**It's Not Possible** You have asked for a **Science-Based** answer, and it's just not going to happen. Despite what Indiana Jones says, it's impossible to build a nuke-proof fridge. Even if the fridge itself is basically OK, the concussive force it went under would jar it severely (and rattle anyone inside of it to death) - or the heat of the blast would cook you inside of it. So to answer your question about what I would make it out of, since I'm selling snake oil anyway I would build it with the CHEAPEST things I could, put a basic lead plating around it all so people thought it was built in a sturdy fashion, then make profit. And shortly after selling a few I'd close up shop and drop the alias I was using. If I were to try to answer this more to the spirit of your question than how it was asked, to survive the nuke you would want to build the fridge out of lead (obviously). Your trouble would come where you would want your fridge to have enough air to breathe for awhile (you know the nuke is coming, but not exactly when, so you would hide in there for a bit). At that point you can either make holes in your fridge - drastically reducing its efficacy as a food chiller and as a life saving device - or install some kind of oxygen tank and air scrubber. Those however are going to take up a lot of space. Some other downsides: The air tank may explode due to the concussive force of the blast. And when your house is on fire, opening a door and releasing a lot of oxygen into the room will result in you being lit on fire. Of course, not opening the door will ALSO result in your death because that fridge will heat up as the house burns. If your house collapses though, it's a bit of a moot point as you'll be trapped in your fridge and won't have to worry about picking one or there other. . **Update\*** Because the comments pointed out the OP updated the question with a specific distance a nuclear yield, let's make sure it's still impossible. According to [NUKEMAP](http://nuclearsecrecy.com/nukemap/) a 1.2 Megaton nuke has the following effects at 2km: **Outside of Fireball Radius (1.04km)** Well, that's good! **Inside or Radiation Radius (2.56km)** Less good. 500rem (5 Sv) of radiation - [that's lethal](https://www.standeyo.com/News_Files/NBC/Roentgen.chart.html)! We need to get that down to about 200rem (2 Sv; the "largest dose that does not cause illness severe enough to require medical care in over 90% of people" per previous link). The best possible shielding wouldn't be Lead, it would actually be Tungsten. To be safe, we'll use two halving-factors, which would actually reduce radiation to ~125rem (1.25 Sv; a hair over the "Smallest dose causing loss of hair after 2 weeks in at least 10% of people"). Link: [Half-Value Layers](https://www.nde-ed.org/EducationResources/CommunityCollege/Radiography/Physics/HalfValueLayer.htm) If we used Lead, we would need to line the fridge with: 0.98" (24.9 mm; let's call it 1" or 25.4 mm to be safe). If we used Tungsten, we would need to line the fridge with: 0.62" (15.8 mm; let's call it 0.7" or 17.8 mm to be safe). Well, that's possible to accommodate - you're still alive! **Inside 20PSI (138 kPa) Air Blast Radius (3km)** Per NUKEMAP, at 20PSI (138 kPa) heavy concrete buildings are severely damaged or demolished. Unless you are living underground or in a very fortunate large concrete building, **per [FEMA](http://www.fema.gov/pdf/plan/prevent/rms/155/e155_unit_vi.pdf), you are dead**. You cannot expect the fridge to withstand this blast. **Inside 5PSI (34.5 kPa) Air Blast Radius (7.4km)** Per NUKEMAP, at 5PSI (34.5 kPa) residential buildings can be expected to collapse. If you are in your fridge and cannot escape due to the roof having collapsed in front of the door, **you will be trapped and die**. **Inside the Thermal Radiation Radius (13.6km)** Per NUKEMAP, within this radius 3rd degree burns can be expected. At this point your house has collapsed on you and spontaneously combusted. If you were lucky enough to survive the pressure (doubtful), **you are now roasting alive in your Tungsten-lined tomb**. ***There is no such thing as being "safe" 2km from any instrument of mass thermonuclear war, least of all in a REFRIGERATOR.***
Well, I'm going to say, my refrigerator is a SpaceX dragon launch abort system with a baggy of ice inside. The total volume of the capsule is 25 cubic meters, which is the equivalent of a 2.9m x 2.9m x 3.0m cube, or a refrigerated room, as seen in grocery stores. According to the spaceX website, the capsule can move a crew (of 3) vertically upwards about 5000 feet (0.9 miles, or 1.5km), which means that it could travel about 7070 feet (2.15km) laterally. This would carry you out from 2km off the blast range to 4.15km. While most buildings would still be completely demolished, you, being in the air, would be perfectly fine with no debris to fall on you. Maybe a bit toasty, but hey, why do you think it has a bag of Ice?
55,454
It's 2016, but for some reason, the Cold War never ended. You've been inspired by your (for some inexplicable reason) favorite movie, Indiana Jones 4, to start a new business: building refrigerators. However, the market is so saturated that in order to distinguish yourself with a nice marketing campaign, you decide to make them **NUKEPROOF!** The refrigerator should be: 1. Usable as a real refrigerator would be. 2. No bigger than standard double door refrigerator, so no room-sized walk-in refrigerator. Though, you *can* add some additional size for additional armor, for example, in **reasonable** margins, so nothing like 10 meters of iron from one side. 3. Protect one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion. How are you going to design it and what materials are you going to use?
2016/09/15
[ "https://worldbuilding.stackexchange.com/questions/55454", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/26768/" ]
GrinningX has quite a good answer but I would like to amend it slightly. The stats quoted appear to refer to a ground burst. Ground bursts are not thought to be targeted against cities because air bursts are more damaging to them. Ground bursts are expected to be used against hardened targets like ICBM silos. However, if a 1.2MT ground burst did occur in your city it the fridge owner would die for sure. Ground bursts generate enormous quantities of fallout. (Air bursts generate almost no fallout.) Fallout is created when energetic neutrons in the fireball touch heavy matter, converting it into unstable isotopes. Air burst neutrons interact with gasses, and the radioactive isotopes they make from this gas tends to stay aloft. The fallout from such a ground burst would be lethal for weeks to months - far too long to be hiding inside a refrigerator. On the other hand, an air burst produces almost no radiation on the ground (neither prompt nor fallout) so the radiation shielding would be largely unneeded. The most important need would be (in this following order of events) 1) protection from the flash (just being inside your house and away from windows is probably good enough), 2) protection from blast (sturdy steel construction and being securely bolted to a sturdy foundation would keep you alive), 3) protection from the heat and fumes from your house burning down, and 4) a mechanism to allow you to exit the fridge even though it has been buried by the debris of your house. Numbers 3 and 4 are quite a bit more difficult and complicated than 1 and 2. For surviving the fire, maybe some kind of hand-cranked air pump which pulled air in from outside and percolated it through a container of water (to cool the air and remove smoke)? That would help, but would not do anything to reduce carbon monoxide or lethal carbon dioxide levels. Heat would be less of a problem. Fridges are designed to be insulated, so just make sure the gaskets are fire resistant and increase the R value enough to survive. I'm honestly not sure how to handle egress. It's hard to guess what debris will be on the fridge and how it will be shaped. I don't have any good ideas for this one.
The it's not possible answers are correct if you interpret the requirements strictly in light of the scene from the movie, where the fridge is directly exposed to the nuclear explosion. Having said that, your company could legitimately market a fridge that would be of benefit, within certain limitations. 1. The fridge would require to be installed in a cellar, or ideally in a reinforced shelter dug into your garden. At a time of heightened nuclear tension digging a shelter may be something people are prepared to do, similarly to how Anderson shelters were dug in many gardens in the UK in World War 2. A shelter intended for protection from a nuclear device should ideally have a zigzag tunnel leading to it: the earth will provides a significant amount of protection from direct gamma, neutron and thermal radiation. 2. The fridge should have a large dedicated compartment for fresh water, sufficient for an entire family to drink for at least a couple of days while you trek out of the fallout zone. 3. The fridge should have a (non-refrigerated) compartment for other emergency supplies, particularly enough P-3 particulate masks for the entire family. As above, these will be used during the first couple of days after the explosion while you trek out of the fallout zone, to prevent internal contamination. Other useful items: ear plugs (your eardrums will likely rupture thus providing a route for contamination particles into the lungs / stomach, so you will want to block your ears), disposable razors (contamination will be trapped quite effectively in hair so you will need to ensure everybody gets a close all-over shave, to reduce contamination), basic medical kit including splints and burns dressings. 4. The fridge should have a lead-acid battery backup, for when the power goes down, and beefy EMP protection. 5. The fridge should feature a pull-out strong metal frame so that it can serve the function of a Morrison shelter and protect the users from falling rubble if the building above collapses on the cellar, or the roof of the garden shelter falls in. It should also have a shovel and combination hammer / crowbar / wrench in case you need to dig your way out of the rubble. It doesn't really work in the same way as the Indiana Jones fridge, but I'd still be pretty happy to have such a fridge in a shelter in my garden if I was worried about possible nuclear attack. Obviously nothing would protect you from a direct hit, but the fridge would considerably enhance a shelter capable of supporting survival in the scenario you outlined as long as sufficient warning was provided to allow you to get into your shelter before the blast.
55,454
It's 2016, but for some reason, the Cold War never ended. You've been inspired by your (for some inexplicable reason) favorite movie, Indiana Jones 4, to start a new business: building refrigerators. However, the market is so saturated that in order to distinguish yourself with a nice marketing campaign, you decide to make them **NUKEPROOF!** The refrigerator should be: 1. Usable as a real refrigerator would be. 2. No bigger than standard double door refrigerator, so no room-sized walk-in refrigerator. Though, you *can* add some additional size for additional armor, for example, in **reasonable** margins, so nothing like 10 meters of iron from one side. 3. Protect one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion. How are you going to design it and what materials are you going to use?
2016/09/15
[ "https://worldbuilding.stackexchange.com/questions/55454", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/26768/" ]
It's George Lucas's marketing manager here. We are now working on a new Indiana Jones movie: Indiana Jones and the Blastproof Fridge, where Indiana Jones goes for a quest to find the sacred Superfridge, made by God himself. We're now developing a new blastproof fridge, which will not only be used in our movie, but also put into sale. Here's how it looks like inside: [![The SUPER FRIDGE](https://i.stack.imgur.com/2Rh4j.png)](https://i.stack.imgur.com/2Rh4j.png) Notes: * the water is accessible from the food storage * the oxygen is stored in liquid/solid state, at around 30K. This provides a cooling feature on top of all - cold air circulates from the tanks (if it melts from heat inside the fridge) to the fridge, and then back through the air filter. * The cushioning would be ideally made from polystyren, because it also isolates the inside (but that's for a 10% surcharge) How it looks on the outside ([source](http://www.heyuguys.com/indiana-jones-5-what-they-need-to-get-right/)): [![THE SUPER FRIDGE](https://i.stack.imgur.com/IGAnH.jpg)](https://i.stack.imgur.com/IGAnH.jpg) Hope this helped will get us some money!
While the it's-not-possible answers are correct for the question you intended to ask lets try another approach: For colder climates it's technically possible (but economic insanity) to build a refrigerator that contains no cooling element at all. Lets make the Green Fridge (tm): No ozone-destroying Freon! No toxic ammonia! No risk of incomplete combustion of the propane causing CO poisoning! Uses far less electricity than a normal refrigerator! You'll be safe against anything less than a direct hit by a nuke! Dig a big, deep hole. In the hole we put a large, very well insulated, very strong walk-in cooled space. Note that this will be at at least the sub-basement level, ideally it would be accessed by stairs or a ramp going down so as to minimize the air spill when the door is opened. There are two holes in the ceiling of the cooled space. Above the cooled space, separated by the insulation layer is a large concrete box. One of the holes from the ceiling connects to a U-shaped pipe (so the opening points down) in one corner of the box, the other to a pipe in the opposite corner that connects to the top, again with a U on the end. There is a large bimetallic thermometer on the first pipe that opens or closes a baffle in the pipe. There also must be a drain for the box. A pipe heading up goes into the third corner of the box, the box is filled with large gravel, a pipe is added in the last corner and it's roofed over and likewise very well insulated. Pipe #3 is insulated and extended to a surface air intake. There is a fan in this pipe (the only powered component in the whole thing!) that turns on when the outside air is colder than the air in the box. The final pipe vents back to the surface, ideally after running a bit through the ground first to dump its cold into the soil. Now the whole thing is covered over except for the vent pipes and however you plan to get to your storage space. You want some feet of dirt and then a moisture barrier layer and more dirt. Assuming you sized it big enough and the winters are cold enough this will work--you get a cold space for no more operating costs than running a fan in the winter. Note that so long as you are dealing with an airburst this should survive anything, although escape might be problematic. You have basically perfect radiation shielding, the only modification you'll need to make to ride out the nuke attack is to add a supply of compressed air to use while the firestorm burns overhead. (Note: In practice you would put the cold space on the bottom and use a fan to bring up the air, I was going for ultimate green. Also, the thermal mass needed is simply too great to be worth it. However, a related idea is in actual use by some people: Bury your house as indicated, run the air feeds through enough ground and you can climate-control your house with nothing but a fan. While the total heating/cooling needed is a lot greater the outside air will be in the right direction far more often and the natural ground temperature isn't too far below what you want for your house anyway.)
55,454
It's 2016, but for some reason, the Cold War never ended. You've been inspired by your (for some inexplicable reason) favorite movie, Indiana Jones 4, to start a new business: building refrigerators. However, the market is so saturated that in order to distinguish yourself with a nice marketing campaign, you decide to make them **NUKEPROOF!** The refrigerator should be: 1. Usable as a real refrigerator would be. 2. No bigger than standard double door refrigerator, so no room-sized walk-in refrigerator. Though, you *can* add some additional size for additional armor, for example, in **reasonable** margins, so nothing like 10 meters of iron from one side. 3. Protect one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion. How are you going to design it and what materials are you going to use?
2016/09/15
[ "https://worldbuilding.stackexchange.com/questions/55454", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/26768/" ]
GrinningX has quite a good answer but I would like to amend it slightly. The stats quoted appear to refer to a ground burst. Ground bursts are not thought to be targeted against cities because air bursts are more damaging to them. Ground bursts are expected to be used against hardened targets like ICBM silos. However, if a 1.2MT ground burst did occur in your city it the fridge owner would die for sure. Ground bursts generate enormous quantities of fallout. (Air bursts generate almost no fallout.) Fallout is created when energetic neutrons in the fireball touch heavy matter, converting it into unstable isotopes. Air burst neutrons interact with gasses, and the radioactive isotopes they make from this gas tends to stay aloft. The fallout from such a ground burst would be lethal for weeks to months - far too long to be hiding inside a refrigerator. On the other hand, an air burst produces almost no radiation on the ground (neither prompt nor fallout) so the radiation shielding would be largely unneeded. The most important need would be (in this following order of events) 1) protection from the flash (just being inside your house and away from windows is probably good enough), 2) protection from blast (sturdy steel construction and being securely bolted to a sturdy foundation would keep you alive), 3) protection from the heat and fumes from your house burning down, and 4) a mechanism to allow you to exit the fridge even though it has been buried by the debris of your house. Numbers 3 and 4 are quite a bit more difficult and complicated than 1 and 2. For surviving the fire, maybe some kind of hand-cranked air pump which pulled air in from outside and percolated it through a container of water (to cool the air and remove smoke)? That would help, but would not do anything to reduce carbon monoxide or lethal carbon dioxide levels. Heat would be less of a problem. Fridges are designed to be insulated, so just make sure the gaskets are fire resistant and increase the R value enough to survive. I'm honestly not sure how to handle egress. It's hard to guess what debris will be on the fridge and how it will be shaped. I don't have any good ideas for this one.
Your customers will need to: Put your fridge underground in the cellar; Reinforce the cellar walls to withstand the shockwave of the blast and the collapse of the house on top. Add shielding in 2 layers, preferably tungsten, 0.5" each layer, since lead is just messy, on the outer side of the body, and on the inside, just behind the fibreglass interior. Put the insulation in between the two layers of tungsten. The piping and wiring to the outside from the inner compartment should leave through the bottom of the fridge. Recommend buyers get **TWO** fridges, or one for every member of the family and a spare for actually keeping food in.
55,454
It's 2016, but for some reason, the Cold War never ended. You've been inspired by your (for some inexplicable reason) favorite movie, Indiana Jones 4, to start a new business: building refrigerators. However, the market is so saturated that in order to distinguish yourself with a nice marketing campaign, you decide to make them **NUKEPROOF!** The refrigerator should be: 1. Usable as a real refrigerator would be. 2. No bigger than standard double door refrigerator, so no room-sized walk-in refrigerator. Though, you *can* add some additional size for additional armor, for example, in **reasonable** margins, so nothing like 10 meters of iron from one side. 3. Protect one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion. How are you going to design it and what materials are you going to use?
2016/09/15
[ "https://worldbuilding.stackexchange.com/questions/55454", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/26768/" ]
Your customers will need to: Put your fridge underground in the cellar; Reinforce the cellar walls to withstand the shockwave of the blast and the collapse of the house on top. Add shielding in 2 layers, preferably tungsten, 0.5" each layer, since lead is just messy, on the outer side of the body, and on the inside, just behind the fibreglass interior. Put the insulation in between the two layers of tungsten. The piping and wiring to the outside from the inner compartment should leave through the bottom of the fridge. Recommend buyers get **TWO** fridges, or one for every member of the family and a spare for actually keeping food in.
Add an asterisk to "Protect": > > Protect\* one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion. > > > \* Protect: the explosion will not kill you and the nuke will leave no lasting ill effects. Protection may also apply to others near fridge. Simply make a normal fridge with small extra box with a piece of string hanging out. "Nuke conversion"-kits also sold separately. In the event of an imminent nearby nuclear explosion simply enter the fridge, pull the string and the 40 kg of TNT in the box will explode, preventing the nuclear blast from killing you. Double your money back if the nuke kills you, upon personal application.
55,454
It's 2016, but for some reason, the Cold War never ended. You've been inspired by your (for some inexplicable reason) favorite movie, Indiana Jones 4, to start a new business: building refrigerators. However, the market is so saturated that in order to distinguish yourself with a nice marketing campaign, you decide to make them **NUKEPROOF!** The refrigerator should be: 1. Usable as a real refrigerator would be. 2. No bigger than standard double door refrigerator, so no room-sized walk-in refrigerator. Though, you *can* add some additional size for additional armor, for example, in **reasonable** margins, so nothing like 10 meters of iron from one side. 3. Protect one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion. How are you going to design it and what materials are you going to use?
2016/09/15
[ "https://worldbuilding.stackexchange.com/questions/55454", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/26768/" ]
Well, I'm going to say, my refrigerator is a SpaceX dragon launch abort system with a baggy of ice inside. The total volume of the capsule is 25 cubic meters, which is the equivalent of a 2.9m x 2.9m x 3.0m cube, or a refrigerated room, as seen in grocery stores. According to the spaceX website, the capsule can move a crew (of 3) vertically upwards about 5000 feet (0.9 miles, or 1.5km), which means that it could travel about 7070 feet (2.15km) laterally. This would carry you out from 2km off the blast range to 4.15km. While most buildings would still be completely demolished, you, being in the air, would be perfectly fine with no debris to fall on you. Maybe a bit toasty, but hey, why do you think it has a bag of Ice?
GrinningX has quite a good answer but I would like to amend it slightly. The stats quoted appear to refer to a ground burst. Ground bursts are not thought to be targeted against cities because air bursts are more damaging to them. Ground bursts are expected to be used against hardened targets like ICBM silos. However, if a 1.2MT ground burst did occur in your city it the fridge owner would die for sure. Ground bursts generate enormous quantities of fallout. (Air bursts generate almost no fallout.) Fallout is created when energetic neutrons in the fireball touch heavy matter, converting it into unstable isotopes. Air burst neutrons interact with gasses, and the radioactive isotopes they make from this gas tends to stay aloft. The fallout from such a ground burst would be lethal for weeks to months - far too long to be hiding inside a refrigerator. On the other hand, an air burst produces almost no radiation on the ground (neither prompt nor fallout) so the radiation shielding would be largely unneeded. The most important need would be (in this following order of events) 1) protection from the flash (just being inside your house and away from windows is probably good enough), 2) protection from blast (sturdy steel construction and being securely bolted to a sturdy foundation would keep you alive), 3) protection from the heat and fumes from your house burning down, and 4) a mechanism to allow you to exit the fridge even though it has been buried by the debris of your house. Numbers 3 and 4 are quite a bit more difficult and complicated than 1 and 2. For surviving the fire, maybe some kind of hand-cranked air pump which pulled air in from outside and percolated it through a container of water (to cool the air and remove smoke)? That would help, but would not do anything to reduce carbon monoxide or lethal carbon dioxide levels. Heat would be less of a problem. Fridges are designed to be insulated, so just make sure the gaskets are fire resistant and increase the R value enough to survive. I'm honestly not sure how to handle egress. It's hard to guess what debris will be on the fridge and how it will be shaped. I don't have any good ideas for this one.
55,454
It's 2016, but for some reason, the Cold War never ended. You've been inspired by your (for some inexplicable reason) favorite movie, Indiana Jones 4, to start a new business: building refrigerators. However, the market is so saturated that in order to distinguish yourself with a nice marketing campaign, you decide to make them **NUKEPROOF!** The refrigerator should be: 1. Usable as a real refrigerator would be. 2. No bigger than standard double door refrigerator, so no room-sized walk-in refrigerator. Though, you *can* add some additional size for additional armor, for example, in **reasonable** margins, so nothing like 10 meters of iron from one side. 3. Protect one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion. How are you going to design it and what materials are you going to use?
2016/09/15
[ "https://worldbuilding.stackexchange.com/questions/55454", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/26768/" ]
Well, I'm going to say, my refrigerator is a SpaceX dragon launch abort system with a baggy of ice inside. The total volume of the capsule is 25 cubic meters, which is the equivalent of a 2.9m x 2.9m x 3.0m cube, or a refrigerated room, as seen in grocery stores. According to the spaceX website, the capsule can move a crew (of 3) vertically upwards about 5000 feet (0.9 miles, or 1.5km), which means that it could travel about 7070 feet (2.15km) laterally. This would carry you out from 2km off the blast range to 4.15km. While most buildings would still be completely demolished, you, being in the air, would be perfectly fine with no debris to fall on you. Maybe a bit toasty, but hey, why do you think it has a bag of Ice?
While the it's-not-possible answers are correct for the question you intended to ask lets try another approach: For colder climates it's technically possible (but economic insanity) to build a refrigerator that contains no cooling element at all. Lets make the Green Fridge (tm): No ozone-destroying Freon! No toxic ammonia! No risk of incomplete combustion of the propane causing CO poisoning! Uses far less electricity than a normal refrigerator! You'll be safe against anything less than a direct hit by a nuke! Dig a big, deep hole. In the hole we put a large, very well insulated, very strong walk-in cooled space. Note that this will be at at least the sub-basement level, ideally it would be accessed by stairs or a ramp going down so as to minimize the air spill when the door is opened. There are two holes in the ceiling of the cooled space. Above the cooled space, separated by the insulation layer is a large concrete box. One of the holes from the ceiling connects to a U-shaped pipe (so the opening points down) in one corner of the box, the other to a pipe in the opposite corner that connects to the top, again with a U on the end. There is a large bimetallic thermometer on the first pipe that opens or closes a baffle in the pipe. There also must be a drain for the box. A pipe heading up goes into the third corner of the box, the box is filled with large gravel, a pipe is added in the last corner and it's roofed over and likewise very well insulated. Pipe #3 is insulated and extended to a surface air intake. There is a fan in this pipe (the only powered component in the whole thing!) that turns on when the outside air is colder than the air in the box. The final pipe vents back to the surface, ideally after running a bit through the ground first to dump its cold into the soil. Now the whole thing is covered over except for the vent pipes and however you plan to get to your storage space. You want some feet of dirt and then a moisture barrier layer and more dirt. Assuming you sized it big enough and the winters are cold enough this will work--you get a cold space for no more operating costs than running a fan in the winter. Note that so long as you are dealing with an airburst this should survive anything, although escape might be problematic. You have basically perfect radiation shielding, the only modification you'll need to make to ride out the nuke attack is to add a supply of compressed air to use while the firestorm burns overhead. (Note: In practice you would put the cold space on the bottom and use a fan to bring up the air, I was going for ultimate green. Also, the thermal mass needed is simply too great to be worth it. However, a related idea is in actual use by some people: Bury your house as indicated, run the air feeds through enough ground and you can climate-control your house with nothing but a fan. While the total heating/cooling needed is a lot greater the outside air will be in the right direction far more often and the natural ground temperature isn't too far below what you want for your house anyway.)
55,454
It's 2016, but for some reason, the Cold War never ended. You've been inspired by your (for some inexplicable reason) favorite movie, Indiana Jones 4, to start a new business: building refrigerators. However, the market is so saturated that in order to distinguish yourself with a nice marketing campaign, you decide to make them **NUKEPROOF!** The refrigerator should be: 1. Usable as a real refrigerator would be. 2. No bigger than standard double door refrigerator, so no room-sized walk-in refrigerator. Though, you *can* add some additional size for additional armor, for example, in **reasonable** margins, so nothing like 10 meters of iron from one side. 3. Protect one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion. How are you going to design it and what materials are you going to use?
2016/09/15
[ "https://worldbuilding.stackexchange.com/questions/55454", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/26768/" ]
It's George Lucas's marketing manager here. We are now working on a new Indiana Jones movie: Indiana Jones and the Blastproof Fridge, where Indiana Jones goes for a quest to find the sacred Superfridge, made by God himself. We're now developing a new blastproof fridge, which will not only be used in our movie, but also put into sale. Here's how it looks like inside: [![The SUPER FRIDGE](https://i.stack.imgur.com/2Rh4j.png)](https://i.stack.imgur.com/2Rh4j.png) Notes: * the water is accessible from the food storage * the oxygen is stored in liquid/solid state, at around 30K. This provides a cooling feature on top of all - cold air circulates from the tanks (if it melts from heat inside the fridge) to the fridge, and then back through the air filter. * The cushioning would be ideally made from polystyren, because it also isolates the inside (but that's for a 10% surcharge) How it looks on the outside ([source](http://www.heyuguys.com/indiana-jones-5-what-they-need-to-get-right/)): [![THE SUPER FRIDGE](https://i.stack.imgur.com/IGAnH.jpg)](https://i.stack.imgur.com/IGAnH.jpg) Hope this helped will get us some money!
Your customers will need to: Put your fridge underground in the cellar; Reinforce the cellar walls to withstand the shockwave of the blast and the collapse of the house on top. Add shielding in 2 layers, preferably tungsten, 0.5" each layer, since lead is just messy, on the outer side of the body, and on the inside, just behind the fibreglass interior. Put the insulation in between the two layers of tungsten. The piping and wiring to the outside from the inner compartment should leave through the bottom of the fridge. Recommend buyers get **TWO** fridges, or one for every member of the family and a spare for actually keeping food in.
55,454
It's 2016, but for some reason, the Cold War never ended. You've been inspired by your (for some inexplicable reason) favorite movie, Indiana Jones 4, to start a new business: building refrigerators. However, the market is so saturated that in order to distinguish yourself with a nice marketing campaign, you decide to make them **NUKEPROOF!** The refrigerator should be: 1. Usable as a real refrigerator would be. 2. No bigger than standard double door refrigerator, so no room-sized walk-in refrigerator. Though, you *can* add some additional size for additional armor, for example, in **reasonable** margins, so nothing like 10 meters of iron from one side. 3. Protect one person from up to 1.2 megatonnes of a TNT nuke at a minimum distance of 2 km from the explosion. How are you going to design it and what materials are you going to use?
2016/09/15
[ "https://worldbuilding.stackexchange.com/questions/55454", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/26768/" ]
GrinningX has quite a good answer but I would like to amend it slightly. The stats quoted appear to refer to a ground burst. Ground bursts are not thought to be targeted against cities because air bursts are more damaging to them. Ground bursts are expected to be used against hardened targets like ICBM silos. However, if a 1.2MT ground burst did occur in your city it the fridge owner would die for sure. Ground bursts generate enormous quantities of fallout. (Air bursts generate almost no fallout.) Fallout is created when energetic neutrons in the fireball touch heavy matter, converting it into unstable isotopes. Air burst neutrons interact with gasses, and the radioactive isotopes they make from this gas tends to stay aloft. The fallout from such a ground burst would be lethal for weeks to months - far too long to be hiding inside a refrigerator. On the other hand, an air burst produces almost no radiation on the ground (neither prompt nor fallout) so the radiation shielding would be largely unneeded. The most important need would be (in this following order of events) 1) protection from the flash (just being inside your house and away from windows is probably good enough), 2) protection from blast (sturdy steel construction and being securely bolted to a sturdy foundation would keep you alive), 3) protection from the heat and fumes from your house burning down, and 4) a mechanism to allow you to exit the fridge even though it has been buried by the debris of your house. Numbers 3 and 4 are quite a bit more difficult and complicated than 1 and 2. For surviving the fire, maybe some kind of hand-cranked air pump which pulled air in from outside and percolated it through a container of water (to cool the air and remove smoke)? That would help, but would not do anything to reduce carbon monoxide or lethal carbon dioxide levels. Heat would be less of a problem. Fridges are designed to be insulated, so just make sure the gaskets are fire resistant and increase the R value enough to survive. I'm honestly not sure how to handle egress. It's hard to guess what debris will be on the fridge and how it will be shaped. I don't have any good ideas for this one.
While the it's-not-possible answers are correct for the question you intended to ask lets try another approach: For colder climates it's technically possible (but economic insanity) to build a refrigerator that contains no cooling element at all. Lets make the Green Fridge (tm): No ozone-destroying Freon! No toxic ammonia! No risk of incomplete combustion of the propane causing CO poisoning! Uses far less electricity than a normal refrigerator! You'll be safe against anything less than a direct hit by a nuke! Dig a big, deep hole. In the hole we put a large, very well insulated, very strong walk-in cooled space. Note that this will be at at least the sub-basement level, ideally it would be accessed by stairs or a ramp going down so as to minimize the air spill when the door is opened. There are two holes in the ceiling of the cooled space. Above the cooled space, separated by the insulation layer is a large concrete box. One of the holes from the ceiling connects to a U-shaped pipe (so the opening points down) in one corner of the box, the other to a pipe in the opposite corner that connects to the top, again with a U on the end. There is a large bimetallic thermometer on the first pipe that opens or closes a baffle in the pipe. There also must be a drain for the box. A pipe heading up goes into the third corner of the box, the box is filled with large gravel, a pipe is added in the last corner and it's roofed over and likewise very well insulated. Pipe #3 is insulated and extended to a surface air intake. There is a fan in this pipe (the only powered component in the whole thing!) that turns on when the outside air is colder than the air in the box. The final pipe vents back to the surface, ideally after running a bit through the ground first to dump its cold into the soil. Now the whole thing is covered over except for the vent pipes and however you plan to get to your storage space. You want some feet of dirt and then a moisture barrier layer and more dirt. Assuming you sized it big enough and the winters are cold enough this will work--you get a cold space for no more operating costs than running a fan in the winter. Note that so long as you are dealing with an airburst this should survive anything, although escape might be problematic. You have basically perfect radiation shielding, the only modification you'll need to make to ride out the nuke attack is to add a supply of compressed air to use while the firestorm burns overhead. (Note: In practice you would put the cold space on the bottom and use a fan to bring up the air, I was going for ultimate green. Also, the thermal mass needed is simply too great to be worth it. However, a related idea is in actual use by some people: Bury your house as indicated, run the air feeds through enough ground and you can climate-control your house with nothing but a fan. While the total heating/cooling needed is a lot greater the outside air will be in the right direction far more often and the natural ground temperature isn't too far below what you want for your house anyway.)
206,671
**EDIT** After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references. For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question: * a 4 hours pre-interview, offsite programming test is not usual but * many people pointed it out that for some companies you would interview for much-much longer than that all together * it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company * all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances I wanted my original question to be about how *reasonable* to expect 4 hours from me, and how *ethical* to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange. However, I found all your answers valuable and thanks for sharing. **ORIGINAL POST** I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own. Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in. Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than **4 hours**. Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test) Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated. What I came up as a conclusion with this company is that either: 1) My motivation is not good and probably they are looking for someone else 2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them 3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...) How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?
2013/07/31
[ "https://softwareengineering.stackexchange.com/questions/206671", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/30439/" ]
**No, not typical**, why are you solving their problems for free? (4 hours) 1 hour is typical for a programming test. In the past our programming test was 4 questions. First 3 questions took 1/2 hour, last one 1/2 hour. We also gave the test to existing hires in house to make sure we were in the expected timeframe and the test was fair and adjusted accordlingly. The first few question(s) were "Fizz Buzz" type to weed out people who can't program. They got progressively harder. The last question was a problem solving exercise. Generally we tried to limit the amount of code written to around a few hundred lines (total) and not require any clever tricks. We also scored people on error handling, style, syntax, organization, etc. The questions were not related to our business but rather the skills and technology that the current platform was written in. Typically, great candidates finished in less time than was allotted. Sometimes people requested extra time which we allowed because of the stress involved in taking a quiz, but we capped everyone at a certain limit. The quiz was in the current development environment and people had access to the internet for reference information. We also went over the expectations of the quiz to every candidate. At one time we did discuss incorporating our code base (real world) into the quiz but we eventually discarded that due to concerns that code copied off/stolen/etc (our boss was a bit paranoid). Eventually we just went with a separate `quiz.sln` in an isolated development machine. Finally, we found it was hard to come up with a test that was fair, but neither too hard nor too easy. We always asked our candidates about the quiz after they took it and garnered their feedback to refine it for future candidates.
I find coding tests in interview are a load of tosh anyway. No-one codes anything but the simplest routine under pressure without the usual environment and tools, so the results you get are dubious at best. What I have found to be really good tests of a programmer's ability is to give him some project code and ask him to review it, this works really well if the code has several obvious bugs, several obvious code issues, and a few questionable practices. A good coder will tell you all of them, and will engage with you in discussion of why some code isn't 'wrong' but could be done better to ease maintenance or so. A poor programmer will find a bug and stop. Any job that expects you to do a test that takes more than half an hour just hasn't spent even that long working out a good, targetted test that provides them with more than a vague idea of your skills. (most companies find it very hard to spend any time working on pre-interview setup). If I was given a test like you'd got, I'd write the answer in pseudo-code. That should be enough to demonstrate my understanding of coding and design, without going through the entire compile, build and test phases you would for a normal work project.
206,671
**EDIT** After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references. For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question: * a 4 hours pre-interview, offsite programming test is not usual but * many people pointed it out that for some companies you would interview for much-much longer than that all together * it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company * all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances I wanted my original question to be about how *reasonable* to expect 4 hours from me, and how *ethical* to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange. However, I found all your answers valuable and thanks for sharing. **ORIGINAL POST** I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own. Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in. Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than **4 hours**. Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test) Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated. What I came up as a conclusion with this company is that either: 1) My motivation is not good and probably they are looking for someone else 2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them 3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...) How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?
2013/07/31
[ "https://softwareengineering.stackexchange.com/questions/206671", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/30439/" ]
Let me take the company's side for a moment, since the other answers haven't so far. It would be nearly impossible to build a usable code base out of a conglomeration of 4-hour coding test submissions from people whose qualifications are completely unknown. Creating a detailed enough specification, vetting the responses, and integrating it with the rest of your code would take longer than 4 hours. Not to mention most useful enterprise-level software projects require thousands of man hours. The thought of building a business on splitting that out into 4-hour increments with weeks of turnaround time each is frankly ridiculous. Giving a real life problem of the business is one of the best ways to determine if someone will be good at, shockingly, solving real life problems of the business. I do this frequently in interviews (although I ask for general design principles and not 4 hours worth of code), and every single time it has been a problem I have already solved. If I hadn't already solved it, the test would lose almost all probative value. Whether a 4-hour test is worth it to you is a personal decision. I was always taught to treat looking for full-time work as a full time job. When you're unemployed or underemployed and spending 8 hours a day looking for work, a 4-hour coding test is nothing. I've spent far longer than that on tasks like brushing up on rusty languages, writing portfolio programs, and customizing resumes for specific positions. On the other hand, some of the best workers are already gainfully employed, and only casually looking for better opportunities. People in that situation are unlikely to go through the rigamarole of a 4-hour test, unless the opportunity is stellar. However, that's the company's problem, not yours. As far as discerning what it means about the company's attitude toward their employees, I don't think you can really say anything either way, other than they are probably tired of dealing with unqualified applicants, to a degree that they're willing to throw out some of the good with the bad.
**No, not typical**, why are you solving their problems for free? (4 hours) 1 hour is typical for a programming test. In the past our programming test was 4 questions. First 3 questions took 1/2 hour, last one 1/2 hour. We also gave the test to existing hires in house to make sure we were in the expected timeframe and the test was fair and adjusted accordlingly. The first few question(s) were "Fizz Buzz" type to weed out people who can't program. They got progressively harder. The last question was a problem solving exercise. Generally we tried to limit the amount of code written to around a few hundred lines (total) and not require any clever tricks. We also scored people on error handling, style, syntax, organization, etc. The questions were not related to our business but rather the skills and technology that the current platform was written in. Typically, great candidates finished in less time than was allotted. Sometimes people requested extra time which we allowed because of the stress involved in taking a quiz, but we capped everyone at a certain limit. The quiz was in the current development environment and people had access to the internet for reference information. We also went over the expectations of the quiz to every candidate. At one time we did discuss incorporating our code base (real world) into the quiz but we eventually discarded that due to concerns that code copied off/stolen/etc (our boss was a bit paranoid). Eventually we just went with a separate `quiz.sln` in an isolated development machine. Finally, we found it was hard to come up with a test that was fair, but neither too hard nor too easy. We always asked our candidates about the quiz after they took it and garnered their feedback to refine it for future candidates.
206,671
**EDIT** After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references. For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question: * a 4 hours pre-interview, offsite programming test is not usual but * many people pointed it out that for some companies you would interview for much-much longer than that all together * it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company * all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances I wanted my original question to be about how *reasonable* to expect 4 hours from me, and how *ethical* to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange. However, I found all your answers valuable and thanks for sharing. **ORIGINAL POST** I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own. Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in. Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than **4 hours**. Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test) Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated. What I came up as a conclusion with this company is that either: 1) My motivation is not good and probably they are looking for someone else 2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them 3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...) How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?
2013/07/31
[ "https://softwareengineering.stackexchange.com/questions/206671", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/30439/" ]
**No, not typical**, why are you solving their problems for free? (4 hours) 1 hour is typical for a programming test. In the past our programming test was 4 questions. First 3 questions took 1/2 hour, last one 1/2 hour. We also gave the test to existing hires in house to make sure we were in the expected timeframe and the test was fair and adjusted accordlingly. The first few question(s) were "Fizz Buzz" type to weed out people who can't program. They got progressively harder. The last question was a problem solving exercise. Generally we tried to limit the amount of code written to around a few hundred lines (total) and not require any clever tricks. We also scored people on error handling, style, syntax, organization, etc. The questions were not related to our business but rather the skills and technology that the current platform was written in. Typically, great candidates finished in less time than was allotted. Sometimes people requested extra time which we allowed because of the stress involved in taking a quiz, but we capped everyone at a certain limit. The quiz was in the current development environment and people had access to the internet for reference information. We also went over the expectations of the quiz to every candidate. At one time we did discuss incorporating our code base (real world) into the quiz but we eventually discarded that due to concerns that code copied off/stolen/etc (our boss was a bit paranoid). Eventually we just went with a separate `quiz.sln` in an isolated development machine. Finally, we found it was hard to come up with a test that was fair, but neither too hard nor too easy. We always asked our candidates about the quiz after they took it and garnered their feedback to refine it for future candidates.
I took a 6 hour coding test at one point. When I took this test I had fairly high confidence I would be hired - while it came true, I wasn't all that satisfied with the follow-on. Obviously having lots of employers each asking for 4 hours is excessive. What the person was looking for in the test I took was my coding style - I was hired because mine was 'closest' to his. In this context, look at the problem from this perspective: First, is it an interesting problem that solving is worthwhile to you in any case? After all, you could learn something valuable. Second, if you can 'pass' the test does it mean you're hired? If this isn't fairly obvious then you have to decide whether there are other reasons to do it anyway. Third, they might estimate that it takes '4 hours', but you might find out differently. Do they really know how long this should take? Most likely the answer is no. Therefore, they are going to keep testing people on 4 hour deadlines until they realize it won't fit in four hours. In that case you're wasting your time. The best approach then is to get aggressive with the hiring manager, and figure out whether you should stop at four hours and give them what you have, or continue until it's done and tell them how long it took. In short, there may be a character test wrapped up in this, and simply trying to accept it on their terms may reveal inexperience.
206,671
**EDIT** After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references. For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question: * a 4 hours pre-interview, offsite programming test is not usual but * many people pointed it out that for some companies you would interview for much-much longer than that all together * it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company * all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances I wanted my original question to be about how *reasonable* to expect 4 hours from me, and how *ethical* to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange. However, I found all your answers valuable and thanks for sharing. **ORIGINAL POST** I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own. Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in. Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than **4 hours**. Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test) Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated. What I came up as a conclusion with this company is that either: 1) My motivation is not good and probably they are looking for someone else 2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them 3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...) How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?
2013/07/31
[ "https://softwareengineering.stackexchange.com/questions/206671", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/30439/" ]
**No, not typical**, why are you solving their problems for free? (4 hours) 1 hour is typical for a programming test. In the past our programming test was 4 questions. First 3 questions took 1/2 hour, last one 1/2 hour. We also gave the test to existing hires in house to make sure we were in the expected timeframe and the test was fair and adjusted accordlingly. The first few question(s) were "Fizz Buzz" type to weed out people who can't program. They got progressively harder. The last question was a problem solving exercise. Generally we tried to limit the amount of code written to around a few hundred lines (total) and not require any clever tricks. We also scored people on error handling, style, syntax, organization, etc. The questions were not related to our business but rather the skills and technology that the current platform was written in. Typically, great candidates finished in less time than was allotted. Sometimes people requested extra time which we allowed because of the stress involved in taking a quiz, but we capped everyone at a certain limit. The quiz was in the current development environment and people had access to the internet for reference information. We also went over the expectations of the quiz to every candidate. At one time we did discuss incorporating our code base (real world) into the quiz but we eventually discarded that due to concerns that code copied off/stolen/etc (our boss was a bit paranoid). Eventually we just went with a separate `quiz.sln` in an isolated development machine. Finally, we found it was hard to come up with a test that was fair, but neither too hard nor too easy. We always asked our candidates about the quiz after they took it and garnered their feedback to refine it for future candidates.
You may not have 4 hours, but somebody more interested in their company certainly will. I was essentially hired based on a similar task that a company asked me to do beforehand on the task alone. Apparently, writing clean and understandable code, thorough test cases and understandable and coherent design documentation is an abnormality. Actually seeing someone do it blew people away. Anyways, everyone I spoke with at the interview commended me on what I did and I felt like I had to impress nobody in the interview because they had already made up their mind. It was simply a matter of me not giving them a reason to say no by doing something stupid. So while I agree 4 hours is a fairly large time investment, it also means the task is of sufficient size that you have an opportunity to really show what you are capable of. Your work very well may speak volumes more than you ever could in an actual interview situation. As a side note: I have tried a similar thing lately but using a much smaller problem and I haven't been happy with the results. Small problems are to trivial to demonstrate enough of the person's knowledge. Plus, trivial problems tend to require the person to recognize some trick/detail necessary to solve the problem. Thus, there is some balance between taking up too much of a person's time versus not gaining any real benefits because the task is to trivial. I would think a 4 hour task is probably the right amount of time to be complex enough for candidates to demonstrate their skills and not be so long that nobody would bother.
206,671
**EDIT** After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references. For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question: * a 4 hours pre-interview, offsite programming test is not usual but * many people pointed it out that for some companies you would interview for much-much longer than that all together * it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company * all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances I wanted my original question to be about how *reasonable* to expect 4 hours from me, and how *ethical* to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange. However, I found all your answers valuable and thanks for sharing. **ORIGINAL POST** I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own. Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in. Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than **4 hours**. Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test) Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated. What I came up as a conclusion with this company is that either: 1) My motivation is not good and probably they are looking for someone else 2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them 3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...) How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?
2013/07/31
[ "https://softwareengineering.stackexchange.com/questions/206671", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/30439/" ]
Let me take the company's side for a moment, since the other answers haven't so far. It would be nearly impossible to build a usable code base out of a conglomeration of 4-hour coding test submissions from people whose qualifications are completely unknown. Creating a detailed enough specification, vetting the responses, and integrating it with the rest of your code would take longer than 4 hours. Not to mention most useful enterprise-level software projects require thousands of man hours. The thought of building a business on splitting that out into 4-hour increments with weeks of turnaround time each is frankly ridiculous. Giving a real life problem of the business is one of the best ways to determine if someone will be good at, shockingly, solving real life problems of the business. I do this frequently in interviews (although I ask for general design principles and not 4 hours worth of code), and every single time it has been a problem I have already solved. If I hadn't already solved it, the test would lose almost all probative value. Whether a 4-hour test is worth it to you is a personal decision. I was always taught to treat looking for full-time work as a full time job. When you're unemployed or underemployed and spending 8 hours a day looking for work, a 4-hour coding test is nothing. I've spent far longer than that on tasks like brushing up on rusty languages, writing portfolio programs, and customizing resumes for specific positions. On the other hand, some of the best workers are already gainfully employed, and only casually looking for better opportunities. People in that situation are unlikely to go through the rigamarole of a 4-hour test, unless the opportunity is stellar. However, that's the company's problem, not yours. As far as discerning what it means about the company's attitude toward their employees, I don't think you can really say anything either way, other than they are probably tired of dealing with unqualified applicants, to a degree that they're willing to throw out some of the good with the bad.
I find coding tests in interview are a load of tosh anyway. No-one codes anything but the simplest routine under pressure without the usual environment and tools, so the results you get are dubious at best. What I have found to be really good tests of a programmer's ability is to give him some project code and ask him to review it, this works really well if the code has several obvious bugs, several obvious code issues, and a few questionable practices. A good coder will tell you all of them, and will engage with you in discussion of why some code isn't 'wrong' but could be done better to ease maintenance or so. A poor programmer will find a bug and stop. Any job that expects you to do a test that takes more than half an hour just hasn't spent even that long working out a good, targetted test that provides them with more than a vague idea of your skills. (most companies find it very hard to spend any time working on pre-interview setup). If I was given a test like you'd got, I'd write the answer in pseudo-code. That should be enough to demonstrate my understanding of coding and design, without going through the entire compile, build and test phases you would for a normal work project.
206,671
**EDIT** After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references. For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question: * a 4 hours pre-interview, offsite programming test is not usual but * many people pointed it out that for some companies you would interview for much-much longer than that all together * it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company * all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances I wanted my original question to be about how *reasonable* to expect 4 hours from me, and how *ethical* to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange. However, I found all your answers valuable and thanks for sharing. **ORIGINAL POST** I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own. Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in. Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than **4 hours**. Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test) Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated. What I came up as a conclusion with this company is that either: 1) My motivation is not good and probably they are looking for someone else 2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them 3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...) How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?
2013/07/31
[ "https://softwareengineering.stackexchange.com/questions/206671", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/30439/" ]
I find coding tests in interview are a load of tosh anyway. No-one codes anything but the simplest routine under pressure without the usual environment and tools, so the results you get are dubious at best. What I have found to be really good tests of a programmer's ability is to give him some project code and ask him to review it, this works really well if the code has several obvious bugs, several obvious code issues, and a few questionable practices. A good coder will tell you all of them, and will engage with you in discussion of why some code isn't 'wrong' but could be done better to ease maintenance or so. A poor programmer will find a bug and stop. Any job that expects you to do a test that takes more than half an hour just hasn't spent even that long working out a good, targetted test that provides them with more than a vague idea of your skills. (most companies find it very hard to spend any time working on pre-interview setup). If I was given a test like you'd got, I'd write the answer in pseudo-code. That should be enough to demonstrate my understanding of coding and design, without going through the entire compile, build and test phases you would for a normal work project.
I took a 6 hour coding test at one point. When I took this test I had fairly high confidence I would be hired - while it came true, I wasn't all that satisfied with the follow-on. Obviously having lots of employers each asking for 4 hours is excessive. What the person was looking for in the test I took was my coding style - I was hired because mine was 'closest' to his. In this context, look at the problem from this perspective: First, is it an interesting problem that solving is worthwhile to you in any case? After all, you could learn something valuable. Second, if you can 'pass' the test does it mean you're hired? If this isn't fairly obvious then you have to decide whether there are other reasons to do it anyway. Third, they might estimate that it takes '4 hours', but you might find out differently. Do they really know how long this should take? Most likely the answer is no. Therefore, they are going to keep testing people on 4 hour deadlines until they realize it won't fit in four hours. In that case you're wasting your time. The best approach then is to get aggressive with the hiring manager, and figure out whether you should stop at four hours and give them what you have, or continue until it's done and tell them how long it took. In short, there may be a character test wrapped up in this, and simply trying to accept it on their terms may reveal inexperience.
206,671
**EDIT** After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references. For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question: * a 4 hours pre-interview, offsite programming test is not usual but * many people pointed it out that for some companies you would interview for much-much longer than that all together * it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company * all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances I wanted my original question to be about how *reasonable* to expect 4 hours from me, and how *ethical* to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange. However, I found all your answers valuable and thanks for sharing. **ORIGINAL POST** I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own. Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in. Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than **4 hours**. Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test) Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated. What I came up as a conclusion with this company is that either: 1) My motivation is not good and probably they are looking for someone else 2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them 3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...) How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?
2013/07/31
[ "https://softwareengineering.stackexchange.com/questions/206671", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/30439/" ]
I find coding tests in interview are a load of tosh anyway. No-one codes anything but the simplest routine under pressure without the usual environment and tools, so the results you get are dubious at best. What I have found to be really good tests of a programmer's ability is to give him some project code and ask him to review it, this works really well if the code has several obvious bugs, several obvious code issues, and a few questionable practices. A good coder will tell you all of them, and will engage with you in discussion of why some code isn't 'wrong' but could be done better to ease maintenance or so. A poor programmer will find a bug and stop. Any job that expects you to do a test that takes more than half an hour just hasn't spent even that long working out a good, targetted test that provides them with more than a vague idea of your skills. (most companies find it very hard to spend any time working on pre-interview setup). If I was given a test like you'd got, I'd write the answer in pseudo-code. That should be enough to demonstrate my understanding of coding and design, without going through the entire compile, build and test phases you would for a normal work project.
You may not have 4 hours, but somebody more interested in their company certainly will. I was essentially hired based on a similar task that a company asked me to do beforehand on the task alone. Apparently, writing clean and understandable code, thorough test cases and understandable and coherent design documentation is an abnormality. Actually seeing someone do it blew people away. Anyways, everyone I spoke with at the interview commended me on what I did and I felt like I had to impress nobody in the interview because they had already made up their mind. It was simply a matter of me not giving them a reason to say no by doing something stupid. So while I agree 4 hours is a fairly large time investment, it also means the task is of sufficient size that you have an opportunity to really show what you are capable of. Your work very well may speak volumes more than you ever could in an actual interview situation. As a side note: I have tried a similar thing lately but using a much smaller problem and I haven't been happy with the results. Small problems are to trivial to demonstrate enough of the person's knowledge. Plus, trivial problems tend to require the person to recognize some trick/detail necessary to solve the problem. Thus, there is some balance between taking up too much of a person's time versus not gaining any real benefits because the task is to trivial. I would think a 4 hour task is probably the right amount of time to be complex enough for candidates to demonstrate their skills and not be so long that nobody would bother.
206,671
**EDIT** After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references. For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question: * a 4 hours pre-interview, offsite programming test is not usual but * many people pointed it out that for some companies you would interview for much-much longer than that all together * it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company * all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances I wanted my original question to be about how *reasonable* to expect 4 hours from me, and how *ethical* to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange. However, I found all your answers valuable and thanks for sharing. **ORIGINAL POST** I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own. Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in. Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than **4 hours**. Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test) Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated. What I came up as a conclusion with this company is that either: 1) My motivation is not good and probably they are looking for someone else 2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them 3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...) How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?
2013/07/31
[ "https://softwareengineering.stackexchange.com/questions/206671", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/30439/" ]
Let me take the company's side for a moment, since the other answers haven't so far. It would be nearly impossible to build a usable code base out of a conglomeration of 4-hour coding test submissions from people whose qualifications are completely unknown. Creating a detailed enough specification, vetting the responses, and integrating it with the rest of your code would take longer than 4 hours. Not to mention most useful enterprise-level software projects require thousands of man hours. The thought of building a business on splitting that out into 4-hour increments with weeks of turnaround time each is frankly ridiculous. Giving a real life problem of the business is one of the best ways to determine if someone will be good at, shockingly, solving real life problems of the business. I do this frequently in interviews (although I ask for general design principles and not 4 hours worth of code), and every single time it has been a problem I have already solved. If I hadn't already solved it, the test would lose almost all probative value. Whether a 4-hour test is worth it to you is a personal decision. I was always taught to treat looking for full-time work as a full time job. When you're unemployed or underemployed and spending 8 hours a day looking for work, a 4-hour coding test is nothing. I've spent far longer than that on tasks like brushing up on rusty languages, writing portfolio programs, and customizing resumes for specific positions. On the other hand, some of the best workers are already gainfully employed, and only casually looking for better opportunities. People in that situation are unlikely to go through the rigamarole of a 4-hour test, unless the opportunity is stellar. However, that's the company's problem, not yours. As far as discerning what it means about the company's attitude toward their employees, I don't think you can really say anything either way, other than they are probably tired of dealing with unqualified applicants, to a degree that they're willing to throw out some of the good with the bad.
I took a 6 hour coding test at one point. When I took this test I had fairly high confidence I would be hired - while it came true, I wasn't all that satisfied with the follow-on. Obviously having lots of employers each asking for 4 hours is excessive. What the person was looking for in the test I took was my coding style - I was hired because mine was 'closest' to his. In this context, look at the problem from this perspective: First, is it an interesting problem that solving is worthwhile to you in any case? After all, you could learn something valuable. Second, if you can 'pass' the test does it mean you're hired? If this isn't fairly obvious then you have to decide whether there are other reasons to do it anyway. Third, they might estimate that it takes '4 hours', but you might find out differently. Do they really know how long this should take? Most likely the answer is no. Therefore, they are going to keep testing people on 4 hour deadlines until they realize it won't fit in four hours. In that case you're wasting your time. The best approach then is to get aggressive with the hiring manager, and figure out whether you should stop at four hours and give them what you have, or continue until it's done and tell them how long it took. In short, there may be a character test wrapped up in this, and simply trying to accept it on their terms may reveal inexperience.
206,671
**EDIT** After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references. For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question: * a 4 hours pre-interview, offsite programming test is not usual but * many people pointed it out that for some companies you would interview for much-much longer than that all together * it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company * all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances I wanted my original question to be about how *reasonable* to expect 4 hours from me, and how *ethical* to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange. However, I found all your answers valuable and thanks for sharing. **ORIGINAL POST** I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own. Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in. Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than **4 hours**. Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test) Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated. What I came up as a conclusion with this company is that either: 1) My motivation is not good and probably they are looking for someone else 2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them 3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...) How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?
2013/07/31
[ "https://softwareengineering.stackexchange.com/questions/206671", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/30439/" ]
Let me take the company's side for a moment, since the other answers haven't so far. It would be nearly impossible to build a usable code base out of a conglomeration of 4-hour coding test submissions from people whose qualifications are completely unknown. Creating a detailed enough specification, vetting the responses, and integrating it with the rest of your code would take longer than 4 hours. Not to mention most useful enterprise-level software projects require thousands of man hours. The thought of building a business on splitting that out into 4-hour increments with weeks of turnaround time each is frankly ridiculous. Giving a real life problem of the business is one of the best ways to determine if someone will be good at, shockingly, solving real life problems of the business. I do this frequently in interviews (although I ask for general design principles and not 4 hours worth of code), and every single time it has been a problem I have already solved. If I hadn't already solved it, the test would lose almost all probative value. Whether a 4-hour test is worth it to you is a personal decision. I was always taught to treat looking for full-time work as a full time job. When you're unemployed or underemployed and spending 8 hours a day looking for work, a 4-hour coding test is nothing. I've spent far longer than that on tasks like brushing up on rusty languages, writing portfolio programs, and customizing resumes for specific positions. On the other hand, some of the best workers are already gainfully employed, and only casually looking for better opportunities. People in that situation are unlikely to go through the rigamarole of a 4-hour test, unless the opportunity is stellar. However, that's the company's problem, not yours. As far as discerning what it means about the company's attitude toward their employees, I don't think you can really say anything either way, other than they are probably tired of dealing with unqualified applicants, to a degree that they're willing to throw out some of the good with the bad.
You may not have 4 hours, but somebody more interested in their company certainly will. I was essentially hired based on a similar task that a company asked me to do beforehand on the task alone. Apparently, writing clean and understandable code, thorough test cases and understandable and coherent design documentation is an abnormality. Actually seeing someone do it blew people away. Anyways, everyone I spoke with at the interview commended me on what I did and I felt like I had to impress nobody in the interview because they had already made up their mind. It was simply a matter of me not giving them a reason to say no by doing something stupid. So while I agree 4 hours is a fairly large time investment, it also means the task is of sufficient size that you have an opportunity to really show what you are capable of. Your work very well may speak volumes more than you ever could in an actual interview situation. As a side note: I have tried a similar thing lately but using a much smaller problem and I haven't been happy with the results. Small problems are to trivial to demonstrate enough of the person's knowledge. Plus, trivial problems tend to require the person to recognize some trick/detail necessary to solve the problem. Thus, there is some balance between taking up too much of a person's time versus not gaining any real benefits because the task is to trivial. I would think a 4 hour task is probably the right amount of time to be complex enough for candidates to demonstrate their skills and not be so long that nobody would bother.
206,671
**EDIT** After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references. For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question: * a 4 hours pre-interview, offsite programming test is not usual but * many people pointed it out that for some companies you would interview for much-much longer than that all together * it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company * all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances I wanted my original question to be about how *reasonable* to expect 4 hours from me, and how *ethical* to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange. However, I found all your answers valuable and thanks for sharing. **ORIGINAL POST** I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own. Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in. Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than **4 hours**. Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test) Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated. What I came up as a conclusion with this company is that either: 1) My motivation is not good and probably they are looking for someone else 2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them 3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...) How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?
2013/07/31
[ "https://softwareengineering.stackexchange.com/questions/206671", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/30439/" ]
You may not have 4 hours, but somebody more interested in their company certainly will. I was essentially hired based on a similar task that a company asked me to do beforehand on the task alone. Apparently, writing clean and understandable code, thorough test cases and understandable and coherent design documentation is an abnormality. Actually seeing someone do it blew people away. Anyways, everyone I spoke with at the interview commended me on what I did and I felt like I had to impress nobody in the interview because they had already made up their mind. It was simply a matter of me not giving them a reason to say no by doing something stupid. So while I agree 4 hours is a fairly large time investment, it also means the task is of sufficient size that you have an opportunity to really show what you are capable of. Your work very well may speak volumes more than you ever could in an actual interview situation. As a side note: I have tried a similar thing lately but using a much smaller problem and I haven't been happy with the results. Small problems are to trivial to demonstrate enough of the person's knowledge. Plus, trivial problems tend to require the person to recognize some trick/detail necessary to solve the problem. Thus, there is some balance between taking up too much of a person's time versus not gaining any real benefits because the task is to trivial. I would think a 4 hour task is probably the right amount of time to be complex enough for candidates to demonstrate their skills and not be so long that nobody would bother.
I took a 6 hour coding test at one point. When I took this test I had fairly high confidence I would be hired - while it came true, I wasn't all that satisfied with the follow-on. Obviously having lots of employers each asking for 4 hours is excessive. What the person was looking for in the test I took was my coding style - I was hired because mine was 'closest' to his. In this context, look at the problem from this perspective: First, is it an interesting problem that solving is worthwhile to you in any case? After all, you could learn something valuable. Second, if you can 'pass' the test does it mean you're hired? If this isn't fairly obvious then you have to decide whether there are other reasons to do it anyway. Third, they might estimate that it takes '4 hours', but you might find out differently. Do they really know how long this should take? Most likely the answer is no. Therefore, they are going to keep testing people on 4 hour deadlines until they realize it won't fit in four hours. In that case you're wasting your time. The best approach then is to get aggressive with the hiring manager, and figure out whether you should stop at four hours and give them what you have, or continue until it's done and tell them how long it took. In short, there may be a character test wrapped up in this, and simply trying to accept it on their terms may reveal inexperience.
10,739
I'm currently working on a novel, in which one of the POV characters is a slave. He was born to a slave (so he was born a slave) of a rich merchant family and was treated well most of his life. One day he travels with his master to a foreign country where slavery had been abolished. The interaction with the foreign "free" people makes him doubt his position. Might be relevant that he is of a different race than his masters, and the population of the foreign country he travels to belongs to his race. Initially I want him to not see the injustice in his state and to love his master (they have a close relationship since they grew up together), yet I (born into a *mostly* slave-free world) have no idea how to portray him. Almost anything I try to write about him feels contrived. How could I better identify with him? or Any reference to a novel (historical fiction preferred, could be any period in history) with a slave POV character (third-person preferred) will do.
2014/04/16
[ "https://writers.stackexchange.com/questions/10739", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/8048/" ]
If you're looking for first-hand accounts, I'd recommend [Ten Years a Slave](http://www.amazon.co.uk/gp/product/1499102534/ref=as_li_ss_il?ie=UTF8&camp=1634&creative=19450&creativeASIN=1499102534&linkCode=as2&tag=nonshewro0a-21). It's an autobiographical account of a free black man who was forced into slavery, and it's pretty shocking. It was also made into a (wonderful/horrific) film last year, which I'd recommend looking out for. For a short-read, there's [A Letter to my Old Master](http://www.lettersofnote.com/2012/01/to-my-old-master.html), a letter - believed to be real - from a freed slave to his old master, who asked him to return to work. It's not quite a first-hand account, but I'd also recommend looking up the YouTube series Ask a Slave; it's based on the real-life, modern experiences of an actress working in a historical house, where she portrayed a slave and had to answer questions from visitors about her 'daily life'. What's quite interesting is seeing the inherent beliefs and misunderstandings people still have today about slavery and race. Also, I don't have any books to recommend but it might be worth looking into Stockholme Syndrome and domestic abuse as well as slavery, to help with the angle of your character loving the slave owner. It might help your character feel less contrived if, instead of being naive, he's been manipulated. I think you can believe anything is 'your fault' if someone tells you so long enough. For some more generic thoughts about your story, a person who has been raised in slavery from birth would most likely be indoctrined in the religion and custom of their slavers, which could potentially help mould the thoughts of your character. I'm not certain if your story takes place in this world? It might help your story to create some specific, rather racist religion if it doesn't, but even if it does some people have interpreted the Curse of Ham in the Bible as a condemnation of dark skin - as if it's something you're cursed with - and the Book of Mormon has mentions of God 'setting a mark upon' sinners, which has been interpreted as meaning giving them dark skin. Now obviously that's hogswash, but if you lived in a culture of slavery, you would want to find reasons to justify your actions and ways of seeing your slaves as something lesser than you, and you could easily find meanings in religious passages to support your needs. In Ten Years a Slave, the slave owners regularly gather the slaves to listen to Christian sermons and speeches, and if you were brought up having people read from important-sounding books every day, and explaining that the passages mean you're indebted to them, you might well believe it yourself. However, I think the older you got, the more difficult it would be to believe. As What said, you would most likely be aware of the injustice. I think it would be entirely human to ask, 'Why me? What's the difference between me and my master?' You would compare yourself to them, especially if you were brought up together, and I'm sure more than once you'd see injustice directly, even if it was small - say he hit you with a stick or stole sweets from the pantry. When *his* skin didn't 'darken' and he wasn't beaten, you would have to question why. It gets harder if there are more slaves, as there are likely to be, as you would be exposed to more points of view which would likely be different, and it would be very easy to be jaded and bitter from very early on. Even 'kind' masters didn't treat their slaves *well*; a slave is a slave. I don't know how grim a story yours is, but in American slavery, we have accounts of children being taken away from parents and sold, and young women being raped; it would be pretty easy to see the injustice there. Still, as Craig pointed out, some slaves in America stayed with their masters because it was the only life they'd known - a home and daily meals (and not being killed for running away) would seem the sensible option to many people. That doesn't mean they were *happy*. It's not really comparable but just as an example of human psychology, in 2011 Gallup reported 71% of American workers hate their jobs - I think it's fair to say a lot of people, no matter the situation, will take the devil they know. I think there's a very interesting and complex psychology there to explore. Good luck!
Although not a slave in the sense you're describing, I would recommend reading Nelson Mandela's first volume of his auto biography, Long Walk To Freedom. What is quite interesting in this book is that he starts off not really seeing the injustice of his situation, or that of his people, primarily because of where he is raised, how he is raised, the education he receives, and the benefits that he gets from his situation (for example, access to education that is done to make him and other black South Africans be more like a British concept of a 'gentleman'). While he was among a small minority that could get education, the general populace were left to live as they always had, and given the "freedom" to do so. There is one particular moment I recall in the book where Mandela is undergoing his right of passage to becoming a man in Xhosa culture, and a local chief who was the guest speaker (I forget who, apologies) gives a speech about how the Xhosa people are not free, and Mandela gets angry thinking this man is being so ungrateful for what they have. True, Mandela was not directly a slave, or owned by someone, but the same principles apply: you grow up in a world where you don't know any better, and you're often purposefully left uneducated so you don't ask awkward questions, but given enough to improve your lot that you are grateful. Even during slavery in America, slaves often stayed with their masters not just because of the threat of violence or intimidation, but were content with their lot, often because many didn't know anything different, were uneducated, and only knew how to perform manual labour. They had somewhere to live, food, and some were given autonomy to practise various manual skills and even hire out their skills for a wage. Their friends and family were around them, and they lived in places that they considered their homes. I know in South Africa, religion was often a powerful tool to keep people in line too, where it was adapted to show the inferiority of other races to the white man, and I suspect something similar occurred during slavery as well. The prison of the mind is far more effective in controlling people than the stick, so if your character loves his master, it's likely because he's grateful for his position in relation to a situation where no-one knows any different. For example, his master may allow some leniency that others don't: perhaps teaching him carpentry, brick laying or other skills. Maybe his master welcomes him into his home regularly, gives him a good place to live while many others may not be so fortunate etc. Maybe his master saved his life once when he was being attacked by those who were racist or xenophobic, or even helped deliver his slave's son. People are complex, and while things like slavery are often portrayed in binary terms, it's never so neat as we make out when we're dealing with real people.
10,739
I'm currently working on a novel, in which one of the POV characters is a slave. He was born to a slave (so he was born a slave) of a rich merchant family and was treated well most of his life. One day he travels with his master to a foreign country where slavery had been abolished. The interaction with the foreign "free" people makes him doubt his position. Might be relevant that he is of a different race than his masters, and the population of the foreign country he travels to belongs to his race. Initially I want him to not see the injustice in his state and to love his master (they have a close relationship since they grew up together), yet I (born into a *mostly* slave-free world) have no idea how to portray him. Almost anything I try to write about him feels contrived. How could I better identify with him? or Any reference to a novel (historical fiction preferred, could be any period in history) with a slave POV character (third-person preferred) will do.
2014/04/16
[ "https://writers.stackexchange.com/questions/10739", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/8048/" ]
Sounds like from the description, you are writing a "slave narrative." This was a popular literary genre in the US around the Civil War. It can either be fiction or non-fiction. One of the most famous examples and my personal suggestion is the *Life of Fredrick Douglas*. He was born a slave and later became a leader in the American Abolition Movement. What I learned from his book is that freedom isn't inherently obvious. Before Douglas was taught to read by his master, he was very happy as a slave. His realization that he was a free-born person came slowly over time and then he was compelled to run away as slavery became an unbearable condition. The problem was not that his master was cruel, but the knowledge about the alternative. That seems to a theme in your book, so that's why I suggest it as a starting place for your research. The WPA's Federal Writer's Project did 2300 interviews ex-slaves during the Great Depression. That research is available [here.](http://memory.loc.gov/ammem/snhtml/snhome.html) That seems like a great resource to understand what the average slave thought about slavery.
Although not a slave in the sense you're describing, I would recommend reading Nelson Mandela's first volume of his auto biography, Long Walk To Freedom. What is quite interesting in this book is that he starts off not really seeing the injustice of his situation, or that of his people, primarily because of where he is raised, how he is raised, the education he receives, and the benefits that he gets from his situation (for example, access to education that is done to make him and other black South Africans be more like a British concept of a 'gentleman'). While he was among a small minority that could get education, the general populace were left to live as they always had, and given the "freedom" to do so. There is one particular moment I recall in the book where Mandela is undergoing his right of passage to becoming a man in Xhosa culture, and a local chief who was the guest speaker (I forget who, apologies) gives a speech about how the Xhosa people are not free, and Mandela gets angry thinking this man is being so ungrateful for what they have. True, Mandela was not directly a slave, or owned by someone, but the same principles apply: you grow up in a world where you don't know any better, and you're often purposefully left uneducated so you don't ask awkward questions, but given enough to improve your lot that you are grateful. Even during slavery in America, slaves often stayed with their masters not just because of the threat of violence or intimidation, but were content with their lot, often because many didn't know anything different, were uneducated, and only knew how to perform manual labour. They had somewhere to live, food, and some were given autonomy to practise various manual skills and even hire out their skills for a wage. Their friends and family were around them, and they lived in places that they considered their homes. I know in South Africa, religion was often a powerful tool to keep people in line too, where it was adapted to show the inferiority of other races to the white man, and I suspect something similar occurred during slavery as well. The prison of the mind is far more effective in controlling people than the stick, so if your character loves his master, it's likely because he's grateful for his position in relation to a situation where no-one knows any different. For example, his master may allow some leniency that others don't: perhaps teaching him carpentry, brick laying or other skills. Maybe his master welcomes him into his home regularly, gives him a good place to live while many others may not be so fortunate etc. Maybe his master saved his life once when he was being attacked by those who were racist or xenophobic, or even helped deliver his slave's son. People are complex, and while things like slavery are often portrayed in binary terms, it's never so neat as we make out when we're dealing with real people.
10,739
I'm currently working on a novel, in which one of the POV characters is a slave. He was born to a slave (so he was born a slave) of a rich merchant family and was treated well most of his life. One day he travels with his master to a foreign country where slavery had been abolished. The interaction with the foreign "free" people makes him doubt his position. Might be relevant that he is of a different race than his masters, and the population of the foreign country he travels to belongs to his race. Initially I want him to not see the injustice in his state and to love his master (they have a close relationship since they grew up together), yet I (born into a *mostly* slave-free world) have no idea how to portray him. Almost anything I try to write about him feels contrived. How could I better identify with him? or Any reference to a novel (historical fiction preferred, could be any period in history) with a slave POV character (third-person preferred) will do.
2014/04/16
[ "https://writers.stackexchange.com/questions/10739", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/8048/" ]
Although not a slave in the sense you're describing, I would recommend reading Nelson Mandela's first volume of his auto biography, Long Walk To Freedom. What is quite interesting in this book is that he starts off not really seeing the injustice of his situation, or that of his people, primarily because of where he is raised, how he is raised, the education he receives, and the benefits that he gets from his situation (for example, access to education that is done to make him and other black South Africans be more like a British concept of a 'gentleman'). While he was among a small minority that could get education, the general populace were left to live as they always had, and given the "freedom" to do so. There is one particular moment I recall in the book where Mandela is undergoing his right of passage to becoming a man in Xhosa culture, and a local chief who was the guest speaker (I forget who, apologies) gives a speech about how the Xhosa people are not free, and Mandela gets angry thinking this man is being so ungrateful for what they have. True, Mandela was not directly a slave, or owned by someone, but the same principles apply: you grow up in a world where you don't know any better, and you're often purposefully left uneducated so you don't ask awkward questions, but given enough to improve your lot that you are grateful. Even during slavery in America, slaves often stayed with their masters not just because of the threat of violence or intimidation, but were content with their lot, often because many didn't know anything different, were uneducated, and only knew how to perform manual labour. They had somewhere to live, food, and some were given autonomy to practise various manual skills and even hire out their skills for a wage. Their friends and family were around them, and they lived in places that they considered their homes. I know in South Africa, religion was often a powerful tool to keep people in line too, where it was adapted to show the inferiority of other races to the white man, and I suspect something similar occurred during slavery as well. The prison of the mind is far more effective in controlling people than the stick, so if your character loves his master, it's likely because he's grateful for his position in relation to a situation where no-one knows any different. For example, his master may allow some leniency that others don't: perhaps teaching him carpentry, brick laying or other skills. Maybe his master welcomes him into his home regularly, gives him a good place to live while many others may not be so fortunate etc. Maybe his master saved his life once when he was being attacked by those who were racist or xenophobic, or even helped deliver his slave's son. People are complex, and while things like slavery are often portrayed in binary terms, it's never so neat as we make out when we're dealing with real people.
I recently read a novel with this very theme: ["The Story of Jonas"](https://www.kirkusreviews.com/book-reviews/maurine-f-dahlberg/the-story-of-jonas/). However, while the book was quite well written, I personally found that aspect of it --the slave who doesn't initially question his servitude --to be implausible. A better example might be Ursula LeGuin's *[The Tombs of Atuan](https://en.wikipedia.org/wiki/The_Tombs_of_Atuan)* whose main character does not initially understand that she is oppressed because she has been led to believe she is favored. My advice to you would be to emphasize the indoctrination process. People don't come into this world believing they are born to be servile, they learn to believe it because that's what people tell them. Show how everyone around him is constantly telling your protagonist how lucky he is, and how well-treated, and how he has advanced as high up as anyone from his race and background possibly could. Then, when he sees counter-examples to the propaganda, you can contrast those with what he has always been told. This also offers a narrative opportunity to drive a wedge between slave and beloved master, when they respond with opposite emotions and reactions to the discovery of a functional free society composed entirely of people from the protagonists' group.
10,739
I'm currently working on a novel, in which one of the POV characters is a slave. He was born to a slave (so he was born a slave) of a rich merchant family and was treated well most of his life. One day he travels with his master to a foreign country where slavery had been abolished. The interaction with the foreign "free" people makes him doubt his position. Might be relevant that he is of a different race than his masters, and the population of the foreign country he travels to belongs to his race. Initially I want him to not see the injustice in his state and to love his master (they have a close relationship since they grew up together), yet I (born into a *mostly* slave-free world) have no idea how to portray him. Almost anything I try to write about him feels contrived. How could I better identify with him? or Any reference to a novel (historical fiction preferred, could be any period in history) with a slave POV character (third-person preferred) will do.
2014/04/16
[ "https://writers.stackexchange.com/questions/10739", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/8048/" ]
If you're looking for first-hand accounts, I'd recommend [Ten Years a Slave](http://www.amazon.co.uk/gp/product/1499102534/ref=as_li_ss_il?ie=UTF8&camp=1634&creative=19450&creativeASIN=1499102534&linkCode=as2&tag=nonshewro0a-21). It's an autobiographical account of a free black man who was forced into slavery, and it's pretty shocking. It was also made into a (wonderful/horrific) film last year, which I'd recommend looking out for. For a short-read, there's [A Letter to my Old Master](http://www.lettersofnote.com/2012/01/to-my-old-master.html), a letter - believed to be real - from a freed slave to his old master, who asked him to return to work. It's not quite a first-hand account, but I'd also recommend looking up the YouTube series Ask a Slave; it's based on the real-life, modern experiences of an actress working in a historical house, where she portrayed a slave and had to answer questions from visitors about her 'daily life'. What's quite interesting is seeing the inherent beliefs and misunderstandings people still have today about slavery and race. Also, I don't have any books to recommend but it might be worth looking into Stockholme Syndrome and domestic abuse as well as slavery, to help with the angle of your character loving the slave owner. It might help your character feel less contrived if, instead of being naive, he's been manipulated. I think you can believe anything is 'your fault' if someone tells you so long enough. For some more generic thoughts about your story, a person who has been raised in slavery from birth would most likely be indoctrined in the religion and custom of their slavers, which could potentially help mould the thoughts of your character. I'm not certain if your story takes place in this world? It might help your story to create some specific, rather racist religion if it doesn't, but even if it does some people have interpreted the Curse of Ham in the Bible as a condemnation of dark skin - as if it's something you're cursed with - and the Book of Mormon has mentions of God 'setting a mark upon' sinners, which has been interpreted as meaning giving them dark skin. Now obviously that's hogswash, but if you lived in a culture of slavery, you would want to find reasons to justify your actions and ways of seeing your slaves as something lesser than you, and you could easily find meanings in religious passages to support your needs. In Ten Years a Slave, the slave owners regularly gather the slaves to listen to Christian sermons and speeches, and if you were brought up having people read from important-sounding books every day, and explaining that the passages mean you're indebted to them, you might well believe it yourself. However, I think the older you got, the more difficult it would be to believe. As What said, you would most likely be aware of the injustice. I think it would be entirely human to ask, 'Why me? What's the difference between me and my master?' You would compare yourself to them, especially if you were brought up together, and I'm sure more than once you'd see injustice directly, even if it was small - say he hit you with a stick or stole sweets from the pantry. When *his* skin didn't 'darken' and he wasn't beaten, you would have to question why. It gets harder if there are more slaves, as there are likely to be, as you would be exposed to more points of view which would likely be different, and it would be very easy to be jaded and bitter from very early on. Even 'kind' masters didn't treat their slaves *well*; a slave is a slave. I don't know how grim a story yours is, but in American slavery, we have accounts of children being taken away from parents and sold, and young women being raped; it would be pretty easy to see the injustice there. Still, as Craig pointed out, some slaves in America stayed with their masters because it was the only life they'd known - a home and daily meals (and not being killed for running away) would seem the sensible option to many people. That doesn't mean they were *happy*. It's not really comparable but just as an example of human psychology, in 2011 Gallup reported 71% of American workers hate their jobs - I think it's fair to say a lot of people, no matter the situation, will take the devil they know. I think there's a very interesting and complex psychology there to explore. Good luck!
I recently read a novel with this very theme: ["The Story of Jonas"](https://www.kirkusreviews.com/book-reviews/maurine-f-dahlberg/the-story-of-jonas/). However, while the book was quite well written, I personally found that aspect of it --the slave who doesn't initially question his servitude --to be implausible. A better example might be Ursula LeGuin's *[The Tombs of Atuan](https://en.wikipedia.org/wiki/The_Tombs_of_Atuan)* whose main character does not initially understand that she is oppressed because she has been led to believe she is favored. My advice to you would be to emphasize the indoctrination process. People don't come into this world believing they are born to be servile, they learn to believe it because that's what people tell them. Show how everyone around him is constantly telling your protagonist how lucky he is, and how well-treated, and how he has advanced as high up as anyone from his race and background possibly could. Then, when he sees counter-examples to the propaganda, you can contrast those with what he has always been told. This also offers a narrative opportunity to drive a wedge between slave and beloved master, when they respond with opposite emotions and reactions to the discovery of a functional free society composed entirely of people from the protagonists' group.
10,739
I'm currently working on a novel, in which one of the POV characters is a slave. He was born to a slave (so he was born a slave) of a rich merchant family and was treated well most of his life. One day he travels with his master to a foreign country where slavery had been abolished. The interaction with the foreign "free" people makes him doubt his position. Might be relevant that he is of a different race than his masters, and the population of the foreign country he travels to belongs to his race. Initially I want him to not see the injustice in his state and to love his master (they have a close relationship since they grew up together), yet I (born into a *mostly* slave-free world) have no idea how to portray him. Almost anything I try to write about him feels contrived. How could I better identify with him? or Any reference to a novel (historical fiction preferred, could be any period in history) with a slave POV character (third-person preferred) will do.
2014/04/16
[ "https://writers.stackexchange.com/questions/10739", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/8048/" ]
Sounds like from the description, you are writing a "slave narrative." This was a popular literary genre in the US around the Civil War. It can either be fiction or non-fiction. One of the most famous examples and my personal suggestion is the *Life of Fredrick Douglas*. He was born a slave and later became a leader in the American Abolition Movement. What I learned from his book is that freedom isn't inherently obvious. Before Douglas was taught to read by his master, he was very happy as a slave. His realization that he was a free-born person came slowly over time and then he was compelled to run away as slavery became an unbearable condition. The problem was not that his master was cruel, but the knowledge about the alternative. That seems to a theme in your book, so that's why I suggest it as a starting place for your research. The WPA's Federal Writer's Project did 2300 interviews ex-slaves during the Great Depression. That research is available [here.](http://memory.loc.gov/ammem/snhtml/snhome.html) That seems like a great resource to understand what the average slave thought about slavery.
I recently read a novel with this very theme: ["The Story of Jonas"](https://www.kirkusreviews.com/book-reviews/maurine-f-dahlberg/the-story-of-jonas/). However, while the book was quite well written, I personally found that aspect of it --the slave who doesn't initially question his servitude --to be implausible. A better example might be Ursula LeGuin's *[The Tombs of Atuan](https://en.wikipedia.org/wiki/The_Tombs_of_Atuan)* whose main character does not initially understand that she is oppressed because she has been led to believe she is favored. My advice to you would be to emphasize the indoctrination process. People don't come into this world believing they are born to be servile, they learn to believe it because that's what people tell them. Show how everyone around him is constantly telling your protagonist how lucky he is, and how well-treated, and how he has advanced as high up as anyone from his race and background possibly could. Then, when he sees counter-examples to the propaganda, you can contrast those with what he has always been told. This also offers a narrative opportunity to drive a wedge between slave and beloved master, when they respond with opposite emotions and reactions to the discovery of a functional free society composed entirely of people from the protagonists' group.
1,331,178
I'm new to DDD and NHibernate. In my current project, I have an entity Person, that contains a value object, let's say Address. Today, this is fine. But maybe one day I will have a requirement that my value object (in this case Address), will have to become an entity. Before trying to model this on a DDD-way, in a more data-centric approach, I had a table Person, with an Id, and another table Address, whose PK was actually an FK, it was the Id of a Person (ie, a one-to-one relationship). I've been reading that when I map a Value Object as a Component, its value will get mapped as columns on my Entity table (so, I would not have the one-to-one relationship). My idea was that, when needed, I would simply add a surrogate key to my Address table, and then it becomes an Entity. How should I design this using NHibernate? Should I already make my Address object an Entity? Sorry, I don't even know if my questions are clear, I'm really lost here.
2009/08/25
[ "https://Stackoverflow.com/questions/1331178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150339/" ]
In the system we are building, we put Value-Objects in separate tables. As far as I know, NHibernate requires that an `id` must added to the object, but we ignore this and treat the object as a Value-Object in the system. As you probably know, a Value-Object is an object that you don't need to track, so we simply overlook the `id` in the object. This makes us freer to model the database the way we want and model the domain model the way we want.
You can Join and make it a Component allowing nHibernate to map it as a proper value object instead of an entity. This way you won't need any virtual properties nor an empty protected ctor (it can be private). ``` Join("PROPOSAL_PRODUCT", product => { product.Schema(IsaSchema.PROPOSALOWN); product.KeyColumn("PROPOSAL_ID"); product.Component(Reveal.Member<Proposal, Product>("_product"), proposalProduct => { proposalProduct.Map... }); }); ```
51,710,761
I'm new to mongodb , and i try to insert data in database through my html page using post method. and i use mongoose in server side. here is my code look like. ``` var LoginInfoSchema = new mongoose.Schema ({ _id : String, user: String, password: String }); var user = mongoose.model('user',LoginInfoSchema); app.post('/login', function(req, res) { new user({ _id : req.body.email, user : req.body.user, password : req.body.password }).save(function(err,doc){ if(err) res.json(err); else res.redirect('/'); }); mongoose.connect('mongodb://localhost:27017/UserInfo',function(err,db){ if(err) console.log(err); db.collection("users").insertOne(user, function(error, result) { if(error) console.log(error); console.log("1 document inserted"); db.close(); }); }); }); ``` whenever i insert data from localhost html page it will inserted successfully , i see that from mongo.exe terminal but i got error that is name: 'MongoError', message: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', ok: 0, errmsg: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', code: 16, codeName: 'InvalidLength', [Symbol(mongoErrorContextSymbol)]: {} } i search everywhere i cannot solve it . what its exactly mean please answer.
2018/08/06
[ "https://Stackoverflow.com/questions/51710761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7611778/" ]
First I would use mongoose.connect() on top of your file and outside from the route handler. Then when you use user.save(), you have already saved data into your DB and thanks to the callback function you can handle potential errors or display some success message. So db.collection.("users").insertOne() is kind of redundant. Try this code maybe ? : ``` mongoose.connect('mongodb://localhost:27017/UserInfo'); var LoginInfoSchema = new mongoose.Schema({ _id : String, user: String, password: String }); var user = mongoose.model('user',LoginInfoSchema); app.post('/login', function(req, res) { new user({ _id : req.body.email, user : req.body.user, password : req.body.password }).save(function(err,doc) { if(err) res.json(err); res.redirect('/'); }); }); ``` Hope that helps, Cheers
I spent the last two weeks with this error and just got it resolved. I am using kotlin on jetty and the official MongoDB drive. This link in stackoverflow was the closest result I got. In the end, I was missing the to call `documentCodec?.encode(writer, document, encoderContext)` at the end of the "encode" funcion. *The code bellow got rid of the error:* ``` override fun encode(writer: BsonWriter?, value: User?, encoderContext: EncoderContext?) { document["_id"] = value?._id document["name"] = value?.name documentCodec?.encode(writer, document, encoderContext) }` ```
51,710,761
I'm new to mongodb , and i try to insert data in database through my html page using post method. and i use mongoose in server side. here is my code look like. ``` var LoginInfoSchema = new mongoose.Schema ({ _id : String, user: String, password: String }); var user = mongoose.model('user',LoginInfoSchema); app.post('/login', function(req, res) { new user({ _id : req.body.email, user : req.body.user, password : req.body.password }).save(function(err,doc){ if(err) res.json(err); else res.redirect('/'); }); mongoose.connect('mongodb://localhost:27017/UserInfo',function(err,db){ if(err) console.log(err); db.collection("users").insertOne(user, function(error, result) { if(error) console.log(error); console.log("1 document inserted"); db.close(); }); }); }); ``` whenever i insert data from localhost html page it will inserted successfully , i see that from mongo.exe terminal but i got error that is name: 'MongoError', message: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', ok: 0, errmsg: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', code: 16, codeName: 'InvalidLength', [Symbol(mongoErrorContextSymbol)]: {} } i search everywhere i cannot solve it . what its exactly mean please answer.
2018/08/06
[ "https://Stackoverflow.com/questions/51710761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7611778/" ]
First I would use mongoose.connect() on top of your file and outside from the route handler. Then when you use user.save(), you have already saved data into your DB and thanks to the callback function you can handle potential errors or display some success message. So db.collection.("users").insertOne() is kind of redundant. Try this code maybe ? : ``` mongoose.connect('mongodb://localhost:27017/UserInfo'); var LoginInfoSchema = new mongoose.Schema({ _id : String, user: String, password: String }); var user = mongoose.model('user',LoginInfoSchema); app.post('/login', function(req, res) { new user({ _id : req.body.email, user : req.body.user, password : req.body.password }).save(function(err,doc) { if(err) res.json(err); res.redirect('/'); }); }); ``` Hope that helps, Cheers
I too also got stuck in the same error for quite a long. The above answers are perfect to solve the error but I would also suggest you to check the sequence of the parameters(object & callback function) you have sent to the MongoDB connect function. MongoClient.connect(function(parameters)) From controllers to the models when we send Thanks
51,710,761
I'm new to mongodb , and i try to insert data in database through my html page using post method. and i use mongoose in server side. here is my code look like. ``` var LoginInfoSchema = new mongoose.Schema ({ _id : String, user: String, password: String }); var user = mongoose.model('user',LoginInfoSchema); app.post('/login', function(req, res) { new user({ _id : req.body.email, user : req.body.user, password : req.body.password }).save(function(err,doc){ if(err) res.json(err); else res.redirect('/'); }); mongoose.connect('mongodb://localhost:27017/UserInfo',function(err,db){ if(err) console.log(err); db.collection("users").insertOne(user, function(error, result) { if(error) console.log(error); console.log("1 document inserted"); db.close(); }); }); }); ``` whenever i insert data from localhost html page it will inserted successfully , i see that from mongo.exe terminal but i got error that is name: 'MongoError', message: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', ok: 0, errmsg: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', code: 16, codeName: 'InvalidLength', [Symbol(mongoErrorContextSymbol)]: {} } i search everywhere i cannot solve it . what its exactly mean please answer.
2018/08/06
[ "https://Stackoverflow.com/questions/51710761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7611778/" ]
First I would use mongoose.connect() on top of your file and outside from the route handler. Then when you use user.save(), you have already saved data into your DB and thanks to the callback function you can handle potential errors or display some success message. So db.collection.("users").insertOne() is kind of redundant. Try this code maybe ? : ``` mongoose.connect('mongodb://localhost:27017/UserInfo'); var LoginInfoSchema = new mongoose.Schema({ _id : String, user: String, password: String }); var user = mongoose.model('user',LoginInfoSchema); app.post('/login', function(req, res) { new user({ _id : req.body.email, user : req.body.user, password : req.body.password }).save(function(err,doc) { if(err) res.json(err); res.redirect('/'); }); }); ``` Hope that helps, Cheers
The MongoDB error "Write batch sizes must be between 1 and 100000. Got 0 operations." results from trying to apply a write operation to no arguments, e.g. update an array of zero documents: ``` db.runCommand( { update: 'some-collection', updates: [], // Uh-oh, no documents! comment: 'this is gonna fail', } ) ``` The OP's code results in this error because the call to `insertOne` is passed the Mongoose constructor `user` rather than a document created with `new user(...)`.
51,710,761
I'm new to mongodb , and i try to insert data in database through my html page using post method. and i use mongoose in server side. here is my code look like. ``` var LoginInfoSchema = new mongoose.Schema ({ _id : String, user: String, password: String }); var user = mongoose.model('user',LoginInfoSchema); app.post('/login', function(req, res) { new user({ _id : req.body.email, user : req.body.user, password : req.body.password }).save(function(err,doc){ if(err) res.json(err); else res.redirect('/'); }); mongoose.connect('mongodb://localhost:27017/UserInfo',function(err,db){ if(err) console.log(err); db.collection("users").insertOne(user, function(error, result) { if(error) console.log(error); console.log("1 document inserted"); db.close(); }); }); }); ``` whenever i insert data from localhost html page it will inserted successfully , i see that from mongo.exe terminal but i got error that is name: 'MongoError', message: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', ok: 0, errmsg: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', code: 16, codeName: 'InvalidLength', [Symbol(mongoErrorContextSymbol)]: {} } i search everywhere i cannot solve it . what its exactly mean please answer.
2018/08/06
[ "https://Stackoverflow.com/questions/51710761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7611778/" ]
I spent the last two weeks with this error and just got it resolved. I am using kotlin on jetty and the official MongoDB drive. This link in stackoverflow was the closest result I got. In the end, I was missing the to call `documentCodec?.encode(writer, document, encoderContext)` at the end of the "encode" funcion. *The code bellow got rid of the error:* ``` override fun encode(writer: BsonWriter?, value: User?, encoderContext: EncoderContext?) { document["_id"] = value?._id document["name"] = value?.name documentCodec?.encode(writer, document, encoderContext) }` ```
I too also got stuck in the same error for quite a long. The above answers are perfect to solve the error but I would also suggest you to check the sequence of the parameters(object & callback function) you have sent to the MongoDB connect function. MongoClient.connect(function(parameters)) From controllers to the models when we send Thanks
51,710,761
I'm new to mongodb , and i try to insert data in database through my html page using post method. and i use mongoose in server side. here is my code look like. ``` var LoginInfoSchema = new mongoose.Schema ({ _id : String, user: String, password: String }); var user = mongoose.model('user',LoginInfoSchema); app.post('/login', function(req, res) { new user({ _id : req.body.email, user : req.body.user, password : req.body.password }).save(function(err,doc){ if(err) res.json(err); else res.redirect('/'); }); mongoose.connect('mongodb://localhost:27017/UserInfo',function(err,db){ if(err) console.log(err); db.collection("users").insertOne(user, function(error, result) { if(error) console.log(error); console.log("1 document inserted"); db.close(); }); }); }); ``` whenever i insert data from localhost html page it will inserted successfully , i see that from mongo.exe terminal but i got error that is name: 'MongoError', message: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', ok: 0, errmsg: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', code: 16, codeName: 'InvalidLength', [Symbol(mongoErrorContextSymbol)]: {} } i search everywhere i cannot solve it . what its exactly mean please answer.
2018/08/06
[ "https://Stackoverflow.com/questions/51710761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7611778/" ]
I spent the last two weeks with this error and just got it resolved. I am using kotlin on jetty and the official MongoDB drive. This link in stackoverflow was the closest result I got. In the end, I was missing the to call `documentCodec?.encode(writer, document, encoderContext)` at the end of the "encode" funcion. *The code bellow got rid of the error:* ``` override fun encode(writer: BsonWriter?, value: User?, encoderContext: EncoderContext?) { document["_id"] = value?._id document["name"] = value?.name documentCodec?.encode(writer, document, encoderContext) }` ```
The MongoDB error "Write batch sizes must be between 1 and 100000. Got 0 operations." results from trying to apply a write operation to no arguments, e.g. update an array of zero documents: ``` db.runCommand( { update: 'some-collection', updates: [], // Uh-oh, no documents! comment: 'this is gonna fail', } ) ``` The OP's code results in this error because the call to `insertOne` is passed the Mongoose constructor `user` rather than a document created with `new user(...)`.
51,710,761
I'm new to mongodb , and i try to insert data in database through my html page using post method. and i use mongoose in server side. here is my code look like. ``` var LoginInfoSchema = new mongoose.Schema ({ _id : String, user: String, password: String }); var user = mongoose.model('user',LoginInfoSchema); app.post('/login', function(req, res) { new user({ _id : req.body.email, user : req.body.user, password : req.body.password }).save(function(err,doc){ if(err) res.json(err); else res.redirect('/'); }); mongoose.connect('mongodb://localhost:27017/UserInfo',function(err,db){ if(err) console.log(err); db.collection("users").insertOne(user, function(error, result) { if(error) console.log(error); console.log("1 document inserted"); db.close(); }); }); }); ``` whenever i insert data from localhost html page it will inserted successfully , i see that from mongo.exe terminal but i got error that is name: 'MongoError', message: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', ok: 0, errmsg: 'Write batch sizes must be between 1 and 100000. Got 0 operations.', code: 16, codeName: 'InvalidLength', [Symbol(mongoErrorContextSymbol)]: {} } i search everywhere i cannot solve it . what its exactly mean please answer.
2018/08/06
[ "https://Stackoverflow.com/questions/51710761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7611778/" ]
The MongoDB error "Write batch sizes must be between 1 and 100000. Got 0 operations." results from trying to apply a write operation to no arguments, e.g. update an array of zero documents: ``` db.runCommand( { update: 'some-collection', updates: [], // Uh-oh, no documents! comment: 'this is gonna fail', } ) ``` The OP's code results in this error because the call to `insertOne` is passed the Mongoose constructor `user` rather than a document created with `new user(...)`.
I too also got stuck in the same error for quite a long. The above answers are perfect to solve the error but I would also suggest you to check the sequence of the parameters(object & callback function) you have sent to the MongoDB connect function. MongoClient.connect(function(parameters)) From controllers to the models when we send Thanks
61,925
I am having troubles understanding utilitarianism a little bit, and have posed this question to a number of people and been met mostly with bafflement about how I cannot see the error in my proposed claim. But, when they explain against it, I cannot see the soundness of their argument. So, I am willing to accept that there is an essential error I am making in my reasoning, and am making this post in the hopes that someone will be able to point it out. People like to say against utilitarianism the idea of inalienable rights. We believe people should have them, not because they will increase pleasure/decrease pain in the aggregate, but for some other given reason. Despite the fact that 30 people being run over by a bus is a much more unpleasurable result than one person being run over, we still (some of us) do not think it right to push that person in front of the bus to save the 30. Not advocating for this, just as a proposed counter-argument. My question is: if we say that inalienable rights are valuable, are we not just simply choosing a different kind of pleasure that we place value on? People should have inalienable rights, and the value of a society which upholds these rights (with that value being determined by the consummate pleasure that comes with having inalienable rights, as compared to not having them) we consider to be a greater point value (+100 points of pleasure) versus the 30 people surviving the bus crash (+50 points of pleasure). Or, if I refuse to torture one person to save two people from being tortured. Some might call me a Kantian, or some other thing, but not a utilitarian. But am I not just saying that the point value of the displeasure that comes from taking it upon myself to torture the one person (perhaps I believe that humans do not have that right, only God does) is -1 trillion versus the (granted) still very large point value of saving the other 2 (-1 billion)? I had someone say, ok, well that is no longer about the aggregate. That is about the one person saving their self the -1 trillion points value. But for the person making this decision, isn't the idea that a society in which these decisions are made by people (and not God, say) substantially worse than even half of that society getting killed off? Like, if I think there are personal moral laws that absolutely cannot be transgressed, I only think that because I believe acting in a contrary way will be extremely unpleasurable (be it spiritually, emotionally, or for the greater society). And perhaps I believe that a society of people that have license to kill off the one for the many is damaged in a way that is way worse for the aggregate than half of its population dying. I almost wonder if this can't be distilled to: for any value claim, is there not a normative claim attached necessarily? I believe this is the is/ought debate, right? If I refrain from doing something that I think is bad, is it not always because I also believe that everyone doing that thing would also be bad, which means utilitarianism can't be escaped? Any normative belief I have is also a belief that the aggregate is better off (i.e. experiences more pleasure or less displeasure) for having this.
2019/04/17
[ "https://philosophy.stackexchange.com/questions/61925", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/30741/" ]
The difference is that a utilitarian who endorses inalienable rights can conceive of a world in which that endorsement ends up morally wrong, even if our actual world endorses inalienable rights. By contrast, deontologists about rights say such a world is quite literally inconceivable. Indeed, on a basic utilitarian analysis, we can imagine a case in which inalienable rights are *unjustified*, even if such a case never obtains. In a world in which the enforcement of a right led to negative utility in the aggregate, it would have to be admitted that the prescription of utilitarianism in this case would be not only that violation of the right was permissible but *obligatory*. The deontologist about rights says such a situation is quite literally inconceivable: there is no possible world in which it is morally permissible to violate the right of another. Hence, talk of inalienable rights in utilitarianism reduces to shorthand for talk about utility. The deontologist would argue that this is unacceptable: rights are valuable not for their utility but because they, say, preserve human dignity. Now you might want to then pose the question: why do we want to preserve human dignity in the first place? And you might want to argue: we want to preserve human dignity because societies that preserve human dignity tend to lead to greater aggregate utility. This would be a particular theory, but you can't simply assert that this is what's going on, you'd have to argue for that claim. My sense is that you are confusing *ethical* and *psychological* hedonism. A psychologist, for example, might be able to collect data to support the claim that---as a matter of empirical fact---most people reason in a hedonist-utilitarian fashion about moral matters, even if they don't explicitly hold utilitarianism as a moral theory or even if they explicitly hold some competing moral theory (such as deontology or virtue ethics). In other words, it may be that what in fact motivates us psychologically is pleasure and pain. Hence, it may be that, statistically speaking, the reason most people end up behaving in such a way that endorses inalienable rights is based on utilitarian considerations. But that is a separate matter from whether utilitarianism can actually give us a theory that *grounds* the value of inalienable rights. Hence, this quote: > > Like, if I think there are personal moral laws that absolutely cannot be transgressed, I only think that because I believe acting in a contrary way will be extremely unpleasurable (be it spiritually, emotionally, or for the greater society). > > > ...is the kind of hanging chad in your case. You claim that the only reason you believe in a moral law is because you in turn believe that acting in a way contrary to that law will lead to negative utility. But have you really separated out psychological from ethical hedonism here? Do you just take it that your behaviors *are* motivated by pleasure and pain? if so, that means you're a psychological hedonist. But *ought* your actions be motivated by pleasure and pain? Well that's a different question, and to jump from psychological to ethical hedonism is simply begging the question in favor of utilitarianism. First you need to clearly separate in your mind the question of how people psychologically deliberate about things, from the question of moral value. You would need to make the case that moral laws are *grounded* in utility, rather than just argue that people in fact reason in utilitarian ways. Indeed, Mill tries to do this himself when he claims that all Kant's derivations of moral duties from the categorical imperative implicitly rely on reasoning about the aggregate consequences of an action on the resulting world in which such moral laws were implemented globally and without exception.
Your objection of inalienable rights against utilitarianism is perfectly sound. I would be very interested in reading about the opposite arguments that did not convince you. One very common trait of utilitarian thought experiment is that they put their subject in the acting role: the one who chooses who gets under the bus, but almost never the one acted upon, the one being pushed. I personally find very telling the case study of the *involuntary organ donor*: > > A person is being drugged on the operation table for a very benign > surgery and sleeps. just before the operation begins ambulances > arrive, with on board several people who got caught in an accident. > Those people will die until they are being transplanted with new > kidneys, heart, lungs, livers. The only timely available source of > fresh organs is the person sleeping on the table. No time to wake him > up and ask for his opinion: either the doctor takes his organs, > killing him and saving the injured, or he lives and the injured are > declared DOA. What should be done ? > > > This experiment has many variations: the injured people are Nobel prizes whose research will undoubtedly save thousands of lives, the drugged patient is a Nobel prize, the drugged patient is your daughter... But 99% of the time I heard it, it puts the subject in the role of the doctor making the decision. It is a shame, as the real moral and politic dilemmas arise when the subject is in fact the drugged patient: *"you are the drugged patient, do you accept to live in a society where people who go to the hospital for a benign operation face the possibility of being sliced open without consent and never wake up in order to save several others ?"* I sure would not. This configuration raises the same questions you do by opposing the value of inalienable rights against the direct utility gained by, say, torturing a person: it is clear, or at least it can't be simply hand waved, that a society where people can be acted upon without consent, including the sacrifice of their life, to maximize general utility is not desirable. Therefore limits exists to what can productively be done in order to maximize utility. And the idea of giving to any subject the possibility to oppose beeing acted upon to preserve their personal utility is equivalent to what you could call inalienable rights. It must be acknowledged here that this argument's soundness depends on one's metaphysical world view. For example, if one believes that such a sacrifice can grant them better karma or a place in paradise, their utility is maximized as well and the ethical problem solved. But people who do not believe in afterlife can rightfully oppose that making the world a better place by sacrificing their life is meaningless if they can't enjoy it anyway. It is a sound logical position to prefer living in a somewhat crappy world and still enjoy what is left to enjoy rather than making it the best possible at the cost of not enjoying it. Yet this only highlights one of the dead angle of many utilitarians, which is that the measure of utility ultimately depends on metaphysical considerations that can't be universally agreed upon (at least it was never agreed upon so far). Now, please note that the concept of inalienable rights defined above is in no way Kantian. There is no absolute imperative at play here, but pure subjectivity: "I don't care if the utility for the society is maximal if it makes my life too short or too crappy to enjoy it myself" says the subject. Yet this subjectivity can be shared by anyone, and as a least common denominator it is somewhat universal. Being universal, it is the closest thing utilitarians can get to base their value system upon, and therefore no utilitarian view is complete without taking into account the liberties of each individual. I think objections like yours demonstrate that utilitarianism, albeit a useful rule of thumb, is not the "one size fits all" objective moral standard it is often advertised to be, and that a "utilitarian tyranny", even if ruled by the most objective of leaders, say an AI, would certainly be more of a dystopia.
21,824,701
I want to traverse through .gz file and read the contents of file. My folder structure: 1) ABC.gz 1.1) ABC 1.1.1) Sample1.txt 1.1.2) Sample2.txt 1.1.3) Test1.txt I wanted to traverse through .gz , then read and print the contents of Sample\*.txt file. Test\*.txt should be ignored. Importantly i do not want to copy / extract the gz to a different location. Perl script i have to read the file: ``` use strict; use warnings; my $filename = 'Sample1.txt'; open(my $fh, '<:encoding(UTF-8)', $filename) or die "Could not open file '$filename' $!"; while (my $row = <$fh>) { chomp $row; print "$row\n"; } ```
2014/02/17
[ "https://Stackoverflow.com/questions/21824701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3318108/" ]
First of all a gzip file is a compressed version of a single file. From your description you most likely have a tar archive which was then compressed. The second point is that you will have to decompress it, either in memory or a temporary file. You will definitely not be able to read it row by row. Take a look at [Tie::Gzip](http://search.cpan.org/~softdia/Tie-Gzip-0.06/lib/Tie/Gzip.pm) for the handling of compressed files and at [Archive::Tar](http://search.cpan.org/~bingos/Archive-Tar-1.96/lib/Archive/Tar.pm) for tar archives.
Maybe something like this: ``` #!/usr/bin/perl -w use IPC::System::Simple "capture"; use File::Path qw[ make_path remove_tree ]; use warnings; use strict; my $tar = "/path/to/archive.tar.gz"; my @list = capture("tar tzf $tar | awk '{print \$NF}'"); my $tmp_path = "/your/tmp/path"; make_path($tmp_path) if not -e $tmp_path; foreach my $file (@list) { if ($file =~ /(Sample*\.txt)$/) { my $out = capture("tar xzf $tmp_path/$1 -O"); print "$out\n"; #unlink $tmp_path/$1; } } remove_tree($tmp_path); ```
8,754,159
I am using VS2005 C# I have a GridView and I have enabled row editing. However, I have some columns which will have a larger input, such as *Comments* column, which will contain more words. Is there a way to adjust the textbox sizes?
2012/01/06
[ "https://Stackoverflow.com/questions/8754159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/872370/" ]
If you want control over width *and* height, as well as other properties, you can reference the TextBox in your GridView's RowDataBound event and set its height and width as well as setting the TextMode to MultiLine: ``` protected void RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit) { // Comments TextBox comments = (TextBox)e.Row.Cells[column_index].Controls[control_index]; comments.TextMode = TextBoxMode.MultiLine; comments.Height = 100; comments.Width = 400; } } ``` Ensure you're referencing the edit row by checking the RowState or EditIndex, and set your column\_index and control\_index appropriately. For BoundFields, the control index will typically be 0.
Set the `ItemStyle-Width` and `ControlStyle-Width`, and if you want wrap the text use `ItemStyle-Wrap`. Hope this helps.
8,754,159
I am using VS2005 C# I have a GridView and I have enabled row editing. However, I have some columns which will have a larger input, such as *Comments* column, which will contain more words. Is there a way to adjust the textbox sizes?
2012/01/06
[ "https://Stackoverflow.com/questions/8754159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/872370/" ]
Set the `ItemStyle-Width` and `ControlStyle-Width`, and if you want wrap the text use `ItemStyle-Wrap`. Hope this helps.
Brissles answer is correct but DataControlRowState can have multiple states ORed together so you may need to check for edit state like this: ``` (e.Row.RowState & DataControlRowState.Edit) != 0 ```
8,754,159
I am using VS2005 C# I have a GridView and I have enabled row editing. However, I have some columns which will have a larger input, such as *Comments* column, which will contain more words. Is there a way to adjust the textbox sizes?
2012/01/06
[ "https://Stackoverflow.com/questions/8754159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/872370/" ]
If you want control over width *and* height, as well as other properties, you can reference the TextBox in your GridView's RowDataBound event and set its height and width as well as setting the TextMode to MultiLine: ``` protected void RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit) { // Comments TextBox comments = (TextBox)e.Row.Cells[column_index].Controls[control_index]; comments.TextMode = TextBoxMode.MultiLine; comments.Height = 100; comments.Width = 400; } } ``` Ensure you're referencing the edit row by checking the RowState or EditIndex, and set your column\_index and control\_index appropriately. For BoundFields, the control index will typically be 0.
Brissles answer is correct but DataControlRowState can have multiple states ORed together so you may need to check for edit state like this: ``` (e.Row.RowState & DataControlRowState.Edit) != 0 ```
20,652,297
I have 100 machines to be automatically controlled using passwordless ssh. However, since passwordless ssh requires id\_rsa handshaking, it takes some time for controlling a machine as we can see in the following. ``` $ time ssh remote hostname remote real 0m0.294s user 0m0.020s sys 0m0.000s ``` It takes approximately 0.3 seconds, and doing this all over 100 machines takes around 30 seconds. What I'm looking for is to make the account on the remote machine no password at all. Is there a way to do it?
2013/12/18
[ "https://Stackoverflow.com/questions/20652297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023045/" ]
There is a way: use [telnet](http://en.wikipedia.org/wiki/Telnet). It provides the same as ssh without authentication and encryption.
The delay may be caused by the host doing a reverse DNS lookup when the client connects, to verify that the client's hostname reverses to the same IP that the client is connecting from. If you disable this option on your server's sshd, you may see less delay when connecting. See the links below for more info: <http://linux-tips.org/article/92/disabling-reverse-dns-lookups-in-ssh> <https://unix.stackexchange.com/questions/56941/what-is-the-point-of-sshd-usedns-option>
20,652,297
I have 100 machines to be automatically controlled using passwordless ssh. However, since passwordless ssh requires id\_rsa handshaking, it takes some time for controlling a machine as we can see in the following. ``` $ time ssh remote hostname remote real 0m0.294s user 0m0.020s sys 0m0.000s ``` It takes approximately 0.3 seconds, and doing this all over 100 machines takes around 30 seconds. What I'm looking for is to make the account on the remote machine no password at all. Is there a way to do it?
2013/12/18
[ "https://Stackoverflow.com/questions/20652297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1023045/" ]
There is a way: use [telnet](http://en.wikipedia.org/wiki/Telnet). It provides the same as ssh without authentication and encryption.
`You can try using sshpass` For example, when password is in password.txt file: `sshpass -fpassword.txt ssh username@hostname`
9,497
So, a teacher explained to me that 究竟 is a more formal way of saying 到底. However, I'm still curious if there are there any other usage differences between the two? Is 究竟 only used in examples that are relatively “夸张” > > E.g. 你究竟为什么要离开我。 > > >
2014/09/10
[ "https://chinese.stackexchange.com/questions/9497", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/6003/" ]
1) "究竟" is more formal than "到底". In everyday spoken Chinese, "究竟" is rarely used. It is used almost only in drama and written Chinese. 2) Well, I would say that the magnitude of "究竟" is equal to that of "到底". They are all equivalent to "on the earth".
When used as an intensive, they are synomymous. Both translated as "on earth," "exactly." --- 究竟, 穷尽. literally means "investigate to the end." It can also be used as a noun which means "outcome," "final truth." 究 谋划;研究;探求. Study, investigate. Originally means "exhaust," "limit." See <http://xh.5156edu.com/html3/15922.html> 竟,终了,完毕. End, finish. See <http://www.zdic.net/z/20/js/7ADF.htm> Source: <http://baike.baidu.com/view/812975.htm?fr=aladdin> --- 到底, 直到尽头. Literally means to "the bottom," "to the end." Source: <http://baike.baidu.com/view/893285.htm>
9,497
So, a teacher explained to me that 究竟 is a more formal way of saying 到底. However, I'm still curious if there are there any other usage differences between the two? Is 究竟 only used in examples that are relatively “夸张” > > E.g. 你究竟为什么要离开我。 > > >
2014/09/10
[ "https://chinese.stackexchange.com/questions/9497", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/6003/" ]
1) "究竟" is more formal than "到底". In everyday spoken Chinese, "究竟" is rarely used. It is used almost only in drama and written Chinese. 2) Well, I would say that the magnitude of "究竟" is equal to that of "到底". They are all equivalent to "on the earth".
There's another meaning for [到底](https://youdao.com/w/%E5%88%B0%E5%BA%95), i.e., "to the end", while [究竟](https://youdao.com/w/%E7%A9%B6%E7%AB%9F) does not have this meaning. E.g.: > > We must fight on until the end. > > 我们必须继续斗争**到底**。 > > > This is described in more detail in the textbook *标准教程HSK4下* on pages 132-133, which says: > > Similarity: Both can be used as adverbs in interrogative sentences of sentences with an interrogative word to indicate inquiry and strengthen the interrogative mood. Both can only be put before the subject if the subject is an interrogative pronoun. > > > > > > > 无论做什么事情,只有试过才知道**究竟/到底**能不能成功。 > > > > 人的一生中,**究竟**什么是最重要的? > > > > > > > > > Differences: "到底" can be used as a verb, meaning "till the end", while "究竟" has no such usage. > > > > > > > 你耐心点儿!这个电影得看到**到底**,才能知道那件事情的原因。 > > > > 我们已经做了这么多努力了,一定要把这个计划坚持**到底**,现在放弃太可惜了。 > > > > > > > > > It also describes 究竟 as follows: > > ... It is often used in written Chinese. If the subject of the sentence is an interrogative pronoun, "究竟" can only be put before it. > > > The *Chinese Grammar Wiki* further highlights how 究竟 is more formal than 到底: > > When someone asks you "what on earth are you doing?," "究竟 (jiūjìng)" is used by the speaker to intensify the question. In this case, 究竟 is similar to 到底. ... Note that 究竟 is more formal than 到底. > > [Expressing "in the end" with "jiujing"](https://resources.allsetlearning.com/chinese/grammar/Expressing_%22in_the_end%22_with_%22jiujing%22) > > >
9,497
So, a teacher explained to me that 究竟 is a more formal way of saying 到底. However, I'm still curious if there are there any other usage differences between the two? Is 究竟 only used in examples that are relatively “夸张” > > E.g. 你究竟为什么要离开我。 > > >
2014/09/10
[ "https://chinese.stackexchange.com/questions/9497", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/6003/" ]
1) "究竟" is more formal than "到底". In everyday spoken Chinese, "究竟" is rarely used. It is used almost only in drama and written Chinese. 2) Well, I would say that the magnitude of "究竟" is equal to that of "到底". They are all equivalent to "on the earth".
1 When used as adverbs Both 到底 and 究竟 can be used as adverbs, and they are nearly the same when they are used to emphasize or to express strong emotion(normally negative ones). In this situation, the only difference is 究竟 is more formal than 到底. Here are a few examples. 你究竟去不去? 他们究竟是谁? 你们到底想干什么? 他们到底是怎么考虑的? When used as an adverb, 到底 can express the meaning of till the end, finally. 究竟 does not have this usage. But we use 最后 or 终于 more often. Some people use 到底 more often, so you can see this usage as a personal style.Here are a few example. 他们到底去了欧洲。They went to Europe finally. 你们到底还是不相信我。They did not trust me till the end. 我们公司到底把你们请来了。Our finally successfully invited you in the end. 2 other differences. 究竟 can be used as a noun, it means result, reason, things that happened. A few examples. 我们都想了解一下究竟。 All of us want to know what happened. 无论什么问题,他都会问个究竟。 Whatever the question is, he asks everything.
9,497
So, a teacher explained to me that 究竟 is a more formal way of saying 到底. However, I'm still curious if there are there any other usage differences between the two? Is 究竟 only used in examples that are relatively “夸张” > > E.g. 你究竟为什么要离开我。 > > >
2014/09/10
[ "https://chinese.stackexchange.com/questions/9497", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/6003/" ]
When used as an intensive, they are synomymous. Both translated as "on earth," "exactly." --- 究竟, 穷尽. literally means "investigate to the end." It can also be used as a noun which means "outcome," "final truth." 究 谋划;研究;探求. Study, investigate. Originally means "exhaust," "limit." See <http://xh.5156edu.com/html3/15922.html> 竟,终了,完毕. End, finish. See <http://www.zdic.net/z/20/js/7ADF.htm> Source: <http://baike.baidu.com/view/812975.htm?fr=aladdin> --- 到底, 直到尽头. Literally means to "the bottom," "to the end." Source: <http://baike.baidu.com/view/893285.htm>
There's another meaning for [到底](https://youdao.com/w/%E5%88%B0%E5%BA%95), i.e., "to the end", while [究竟](https://youdao.com/w/%E7%A9%B6%E7%AB%9F) does not have this meaning. E.g.: > > We must fight on until the end. > > 我们必须继续斗争**到底**。 > > > This is described in more detail in the textbook *标准教程HSK4下* on pages 132-133, which says: > > Similarity: Both can be used as adverbs in interrogative sentences of sentences with an interrogative word to indicate inquiry and strengthen the interrogative mood. Both can only be put before the subject if the subject is an interrogative pronoun. > > > > > > > 无论做什么事情,只有试过才知道**究竟/到底**能不能成功。 > > > > 人的一生中,**究竟**什么是最重要的? > > > > > > > > > Differences: "到底" can be used as a verb, meaning "till the end", while "究竟" has no such usage. > > > > > > > 你耐心点儿!这个电影得看到**到底**,才能知道那件事情的原因。 > > > > 我们已经做了这么多努力了,一定要把这个计划坚持**到底**,现在放弃太可惜了。 > > > > > > > > > It also describes 究竟 as follows: > > ... It is often used in written Chinese. If the subject of the sentence is an interrogative pronoun, "究竟" can only be put before it. > > > The *Chinese Grammar Wiki* further highlights how 究竟 is more formal than 到底: > > When someone asks you "what on earth are you doing?," "究竟 (jiūjìng)" is used by the speaker to intensify the question. In this case, 究竟 is similar to 到底. ... Note that 究竟 is more formal than 到底. > > [Expressing "in the end" with "jiujing"](https://resources.allsetlearning.com/chinese/grammar/Expressing_%22in_the_end%22_with_%22jiujing%22) > > >
9,497
So, a teacher explained to me that 究竟 is a more formal way of saying 到底. However, I'm still curious if there are there any other usage differences between the two? Is 究竟 only used in examples that are relatively “夸张” > > E.g. 你究竟为什么要离开我。 > > >
2014/09/10
[ "https://chinese.stackexchange.com/questions/9497", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/6003/" ]
When used as an intensive, they are synomymous. Both translated as "on earth," "exactly." --- 究竟, 穷尽. literally means "investigate to the end." It can also be used as a noun which means "outcome," "final truth." 究 谋划;研究;探求. Study, investigate. Originally means "exhaust," "limit." See <http://xh.5156edu.com/html3/15922.html> 竟,终了,完毕. End, finish. See <http://www.zdic.net/z/20/js/7ADF.htm> Source: <http://baike.baidu.com/view/812975.htm?fr=aladdin> --- 到底, 直到尽头. Literally means to "the bottom," "to the end." Source: <http://baike.baidu.com/view/893285.htm>
1 When used as adverbs Both 到底 and 究竟 can be used as adverbs, and they are nearly the same when they are used to emphasize or to express strong emotion(normally negative ones). In this situation, the only difference is 究竟 is more formal than 到底. Here are a few examples. 你究竟去不去? 他们究竟是谁? 你们到底想干什么? 他们到底是怎么考虑的? When used as an adverb, 到底 can express the meaning of till the end, finally. 究竟 does not have this usage. But we use 最后 or 终于 more often. Some people use 到底 more often, so you can see this usage as a personal style.Here are a few example. 他们到底去了欧洲。They went to Europe finally. 你们到底还是不相信我。They did not trust me till the end. 我们公司到底把你们请来了。Our finally successfully invited you in the end. 2 other differences. 究竟 can be used as a noun, it means result, reason, things that happened. A few examples. 我们都想了解一下究竟。 All of us want to know what happened. 无论什么问题,他都会问个究竟。 Whatever the question is, he asks everything.
95,010
I'm trying to understand different methods of calculating interest on installment loans. I keep coming across the terms "simple interest" and "actuarial method". They seem to be related but I haven't found a clear explanation. Here's an example of something I read on another website that has me confused: > > **Simple interest** is computed on the actual balance outstanding on the payment due date. **Precomputed interest** is calculated on the original principal balance. The interest is added to the original principal balance and divided by the number of payments to determine the payment amount. ... the Rule of 78s is no longer an acceptable method of accounting for loan income. The acceptable method for accounting for loan income is the **actuarial method**. > > >
2018/05/01
[ "https://money.stackexchange.com/questions/95010", "https://money.stackexchange.com", "https://money.stackexchange.com/users/42805/" ]
Definitions of simple interest differ, e.g. the naïve version here: [What is 'Simple Interest'](https://www.investopedia.com/terms/s/simple_interest.asp). ``` Simple Interest = P x I x N where P is the principal I is the periodic interest rate N is the number of periods ``` (*an example is included below*) However, by contrast, insofar as "*Simple interest is computed on the actual balance outstanding on the payment due date.*", this is what is used by standard (actuarial) methods. The simple interest (actuarial) method also differs from the Rule of 78s. As described here: [Rule of 78s - Precomputed Loan](https://en.wikipedia.org/wiki/Rule_of_78s#Precomputed_Loan) > > Finance charge, carrying charges, interest costs, or whatever the cost > of the loan may be called, can be calculated with simple interest > equations, add-on interest, an agreed upon fee, or any disclosed > method. Once the finance charge has been identified, the Rule of 78s > is used to calculate the amount of the finance charge to be rebated > (forgiven) in the event that the loan is repaid early, prior to the > agreed upon number of payments. > > > So taking a simple example: a 12 month loan repaid early, after 9 months. ``` principal s = 995.40 no. months n = 12 int. rate r = 0.03 per month ``` By simple interest (actuarial) methods, using formula 1 (derived below). ``` repayments d = r (1 + 1/((1 + r)^n - 1)) s = 100 total int. t = d n - s = 204.60 ``` However if the loan is repaid early, after 9 months, using formula 2. ``` x = 9 total int. t = ((1 + r)^x - 1) s + (d (1 - (1 + r)^x + r x))/r = 187.46 ``` So the interest saved by repaying early is ``` 204.60 - 187.46 = 17.14 ``` If this was calculated by the Rule of 78s, with the finance charge taken as the total interest due for the 12 month loan. ``` precomputed interest f = 204.60 precomuputed loan = s + f = 955.40 + 204.60 = 1160 interest forgiven = f (3/78 + 2/78 + 1/78) = 15.74 ``` So in this case it disadvantages the borrower to use the Rule of 78s. Note the finance charge calculated by the naïve simple interest method in the aforementioned link: [What is 'Simple Interest'](https://www.investopedia.com/terms/s/simple_interest.asp) ``` Simple Interest = P x I x N = 955.40 x 0.03 x 12 = 343.94 ``` This is a long way from 204.60, but then the demo interest rate is quite high, accentuating the disparity. The naïve simple interest method is otherwise disregarded in this answer. Demonstrating the interest calculations graphically, it can be observed that the interest payments calculated for months 10, 11 & 12 by the Rule of 78s are less than the simple interest/actuarial calculations. [![enter image description here](https://i.stack.imgur.com/BIIdM.png)](https://i.stack.imgur.com/BIIdM.png) Formulae derivations [![enter image description here](https://i.stack.imgur.com/hlcAX.png)](https://i.stack.imgur.com/hlcAX.png)
The actuarial method, in relation to a loan (as you mentioned) and its repayment is generally associated with repayment of loan at reducing balance (the method though can be used for many other purpose, on some cases on appreciating balance). For example, let's say you have borrowed $1000 at an interest rate of 10% to be re-payed in 20 years with one yearly constant payment (which works out to about about $116 per year, [put the above values in the calculator, this also gives detailed breakdown)](https://emicalculator.net/). The idea is at the end of 1st year, when you pay $116, $100 goes towards settling the simple interest of 10% on $1000 for 1 year, the balance $16 is reduced from $1000. So your next years principal is $1000-$16=$984. In the 2nd year end, you will again pay $116, where now your simple interest on capital outstanding would be 10% of $984, which is $98.4, your principal repayment would be $116-$98.4=$17.6, your principal outstanding at the end of 2nd year would be $984-$17.6=$966.4 Observe the reducing balance, if you keep paying the same amount every year it would finally result in full amortization of the loan in 20 years. The concept of simple interest is used to calculate the interest on remainder balance.
39,515,915
I want to make sure if there are better way of my below code , a way to send data to server the below is working , but can be better? ``` class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String json = ""; String s_calc=String.valueOf(calc);; try { RequestBody formBody = new FormEncodingBuilder() // .add("tag","login") .add("likes", "9") .add("id", id) .build(); Request request = new Request.Builder() .url("http://justedhak.com/old-files/singleactivity.php") .post(formBody) .build(); Response responses = null; try { responses = client.newCall(request).execute(); } catch (IOException e) { e.printStackTrace(); } String jsonData = responses.body().string(); JSONObject Jobject = new JSONObject(jsonData); int success = Jobject.getInt("success"); if (success == 1) { // this means that the credentials are correct, so create a login session. JSONArray JAStuff = Jobject.getJSONArray("stuff"); int intStuff = JAStuff.length(); if (intStuff != 0) { for (int i = 0; i < JAStuff.length(); i++) { JSONObject JOStuff = JAStuff.getJSONObject(i); //create a login session. // session.createLoginSession(name, pass); } } } else { // return an empty string, onPostExecute will validate the returned value. return ""; } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { Log.e("MYAPP", "unexpected JSON exception", e); } //this return will be reached if the user logs in successfully. So, onPostExecute will validate this value. return "RegisterActivity success"; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // if not empty, this means that the provided credentials were correct. . if (!result.equals("")) { finish(); return; } //otherwise, show a popup. AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SingleObjectActivity.this); alertDialogBuilder.setMessage("Wrong username or password, Try again please."); // alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface arg0, int arg1) { // alertDialog.dismiss(); // } // }); // alertDialog = alertDialogBuilder.create(); // alertDialog.show(); } } ```
2016/09/15
[ "https://Stackoverflow.com/questions/39515915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2291869/" ]
You can use [AutoMapper](http://automapper.org/): ``` public Dog UsingAMR(Person prs) { var config = new MapperConfiguration(cfg => { cfg.CreateMap<Person, Dog>(); }); IMapper mapper = config.CreateMapper(); return mapper.Map<Person, Dog>(prs); } ``` Then you can easily: ``` Person ps = new Person {Name = "John", Number = 25}; Dog dog = UsingAMR(ps); ``` Just don't forget to **install `AutoMapper` first** from the package manager console as mentioned in the reference: 1. From *Tools* menu click on *NuGet Package Manager* ==> *Package Manager Console* 2. Then type the following command: ``` PM> Install-Package AutoMapper ```
Install `AutoMapper` package in your project. As a best practice (for web applications) you can create new class (should derives from `Profile`) in your `App_Start` folder, that will contain all your mappings for your project. ``` namespace MyApp.App_Start { public class MyAppMapping : Profile { public MyAppMapping() { CreateMap<Person, Dog>(); //You can also create a reverse mapping CreateMap<Dog, Person>(); /*You can also map claculated value for your destination. Example: you want to append "d-" before the value that will be mapped to Name property of the dog*/ CreateMap<Person, Dog>() .ForMember(d => d.Days, conf => conf.ResolveUsing(AppendDogName)); } private static object AppendDogName(Person person) { return "d-" + person.Name; } } } ``` Then Initialize your mapping inside the `Application_Start` method in `Global.asax` ``` protected void Application_Start() { Mapper.Initialize(m => m.AddProfile<MyAppMapping>()); } ``` You can now use the mappings that you have created ``` var dog = AutoMapper.Mapper.Map<Person, Dog>(person); ```
39,515,915
I want to make sure if there are better way of my below code , a way to send data to server the below is working , but can be better? ``` class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String json = ""; String s_calc=String.valueOf(calc);; try { RequestBody formBody = new FormEncodingBuilder() // .add("tag","login") .add("likes", "9") .add("id", id) .build(); Request request = new Request.Builder() .url("http://justedhak.com/old-files/singleactivity.php") .post(formBody) .build(); Response responses = null; try { responses = client.newCall(request).execute(); } catch (IOException e) { e.printStackTrace(); } String jsonData = responses.body().string(); JSONObject Jobject = new JSONObject(jsonData); int success = Jobject.getInt("success"); if (success == 1) { // this means that the credentials are correct, so create a login session. JSONArray JAStuff = Jobject.getJSONArray("stuff"); int intStuff = JAStuff.length(); if (intStuff != 0) { for (int i = 0; i < JAStuff.length(); i++) { JSONObject JOStuff = JAStuff.getJSONObject(i); //create a login session. // session.createLoginSession(name, pass); } } } else { // return an empty string, onPostExecute will validate the returned value. return ""; } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { Log.e("MYAPP", "unexpected JSON exception", e); } //this return will be reached if the user logs in successfully. So, onPostExecute will validate this value. return "RegisterActivity success"; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // if not empty, this means that the provided credentials were correct. . if (!result.equals("")) { finish(); return; } //otherwise, show a popup. AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SingleObjectActivity.this); alertDialogBuilder.setMessage("Wrong username or password, Try again please."); // alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface arg0, int arg1) { // alertDialog.dismiss(); // } // }); // alertDialog = alertDialogBuilder.create(); // alertDialog.show(); } } ```
2016/09/15
[ "https://Stackoverflow.com/questions/39515915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2291869/" ]
You can use [AutoMapper](http://automapper.org/): ``` public Dog UsingAMR(Person prs) { var config = new MapperConfiguration(cfg => { cfg.CreateMap<Person, Dog>(); }); IMapper mapper = config.CreateMapper(); return mapper.Map<Person, Dog>(prs); } ``` Then you can easily: ``` Person ps = new Person {Name = "John", Number = 25}; Dog dog = UsingAMR(ps); ``` Just don't forget to **install `AutoMapper` first** from the package manager console as mentioned in the reference: 1. From *Tools* menu click on *NuGet Package Manager* ==> *Package Manager Console* 2. Then type the following command: ``` PM> Install-Package AutoMapper ```
An object oriented approach. ``` public class Mammal { public Mammal(Mammal toCopy) { Name = toCopy.Name; Number = toCopy.Number; } public string Name {get; set;} public int Number {get; set;} } public class Person: Mammal { public Person(Mammal toCopy) {} /* will default to base constructor */ } public class Dog: Mammal { public Dog(Mammal toCopy) {} /* will default to base constructor */ } ``` This will allow the following: ``` Person person = new Person(); person.Name = "George"; person.Number = 1; Dog dog = new Dog(person); ```
39,515,915
I want to make sure if there are better way of my below code , a way to send data to server the below is working , but can be better? ``` class SendPostReqAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String json = ""; String s_calc=String.valueOf(calc);; try { RequestBody formBody = new FormEncodingBuilder() // .add("tag","login") .add("likes", "9") .add("id", id) .build(); Request request = new Request.Builder() .url("http://justedhak.com/old-files/singleactivity.php") .post(formBody) .build(); Response responses = null; try { responses = client.newCall(request).execute(); } catch (IOException e) { e.printStackTrace(); } String jsonData = responses.body().string(); JSONObject Jobject = new JSONObject(jsonData); int success = Jobject.getInt("success"); if (success == 1) { // this means that the credentials are correct, so create a login session. JSONArray JAStuff = Jobject.getJSONArray("stuff"); int intStuff = JAStuff.length(); if (intStuff != 0) { for (int i = 0; i < JAStuff.length(); i++) { JSONObject JOStuff = JAStuff.getJSONObject(i); //create a login session. // session.createLoginSession(name, pass); } } } else { // return an empty string, onPostExecute will validate the returned value. return ""; } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { Log.e("MYAPP", "unexpected JSON exception", e); } //this return will be reached if the user logs in successfully. So, onPostExecute will validate this value. return "RegisterActivity success"; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // if not empty, this means that the provided credentials were correct. . if (!result.equals("")) { finish(); return; } //otherwise, show a popup. AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SingleObjectActivity.this); alertDialogBuilder.setMessage("Wrong username or password, Try again please."); // alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface arg0, int arg1) { // alertDialog.dismiss(); // } // }); // alertDialog = alertDialogBuilder.create(); // alertDialog.show(); } } ```
2016/09/15
[ "https://Stackoverflow.com/questions/39515915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2291869/" ]
You can use [AutoMapper](http://automapper.org/): ``` public Dog UsingAMR(Person prs) { var config = new MapperConfiguration(cfg => { cfg.CreateMap<Person, Dog>(); }); IMapper mapper = config.CreateMapper(); return mapper.Map<Person, Dog>(prs); } ``` Then you can easily: ``` Person ps = new Person {Name = "John", Number = 25}; Dog dog = UsingAMR(ps); ``` Just don't forget to **install `AutoMapper` first** from the package manager console as mentioned in the reference: 1. From *Tools* menu click on *NuGet Package Manager* ==> *Package Manager Console* 2. Then type the following command: ``` PM> Install-Package AutoMapper ```
If you don't work with big generic list, you can do it using LinQ. ``` var persons = new List<Person>(); // populate data [...] var dogs = persons.Select(p=>new Dog{Name=p.Name,Number=p.Number}).ToList(); ``` It's easy to remember, and you can filter data previously.
21,814,672
I am using spring framework for writing a web service application. There are not html or jsp pages in the application. It is purely web service. **This is my Controller class** ``` @RequestMapping("/*") public class Opinion { private FeedbackService fs; public Opinion(FeedbackService fs){ this.fs=fs; } @RequestMapping(value="/givefeedback",method=RequestMethod.POST) public void Login(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException { ObjectInputStream in=new ObjectInputStream(request.getInputStream()); serialize.Feedback feedback=(serialize.Feedback)in.readObject(); fs.writeFeedback(feedback); response.setStatus(200); } ``` **My mvc-config.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="poll_Web" class="sef.controller.Opinion"> <constructor-arg ref="feedbackService" /> </bean> <context:component-scan base-package="sef.controller" /> </beans> ``` **My web.xml** ``` <servlet> <servlet-name>opinionDispacher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>opinionDispacher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </context-param> ``` I am using the URL `localhost:8080/feedback/givefeedback`. The app is deployed as **feedback.war**. But the request is not at all forwarded to the controller. I am not sure why is this is happening. I am also not sure till which point the request goes in the chain.
2014/02/16
[ "https://Stackoverflow.com/questions/21814672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139023/" ]
Downloading java dependencies is possible, if you actually really need to download them into a folder. Example: ``` apply plugin: 'java' dependencies { runtime group: 'com.netflix.exhibitor', name: 'exhibitor-standalone', version: '1.5.2' runtime group: 'org.apache.zookeeper', name: 'zookeeper', version: '3.4.6' } repositories { mavenCentral() } task getDeps(type: Copy) { from sourceSets.main.runtimeClasspath into 'runtime/' } ``` Download the dependencies (and their dependencies) into the folder `runtime` when you execute `gradle getDeps`.
I have found this answer <https://stackoverflow.com/a/47107135/3067148> also very helpful: > > `gradle dependencies` will list the dependencies and download them as a > side-effect. > > >
21,814,672
I am using spring framework for writing a web service application. There are not html or jsp pages in the application. It is purely web service. **This is my Controller class** ``` @RequestMapping("/*") public class Opinion { private FeedbackService fs; public Opinion(FeedbackService fs){ this.fs=fs; } @RequestMapping(value="/givefeedback",method=RequestMethod.POST) public void Login(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException { ObjectInputStream in=new ObjectInputStream(request.getInputStream()); serialize.Feedback feedback=(serialize.Feedback)in.readObject(); fs.writeFeedback(feedback); response.setStatus(200); } ``` **My mvc-config.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="poll_Web" class="sef.controller.Opinion"> <constructor-arg ref="feedbackService" /> </bean> <context:component-scan base-package="sef.controller" /> </beans> ``` **My web.xml** ``` <servlet> <servlet-name>opinionDispacher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>opinionDispacher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </context-param> ``` I am using the URL `localhost:8080/feedback/givefeedback`. The app is deployed as **feedback.war**. But the request is not at all forwarded to the controller. I am not sure why is this is happening. I am also not sure till which point the request goes in the chain.
2014/02/16
[ "https://Stackoverflow.com/questions/21814672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139023/" ]
A slightly lighter task that doesn't unnecessarily copy files to a dir: ``` task downloadDependencies(type: Exec) { configurations.testRuntime.files commandLine 'echo', 'Downloaded all dependencies' } ``` Updated for kotlin & gradle 6.2.0, with buildscript dependency resolution added: ```kotlin fun Configuration.isDeprecated() = this is DeprecatableConfiguration && resolutionAlternatives != null fun ConfigurationContainer.resolveAll() = this .filter { it.isCanBeResolved && !it.isDeprecated() } .forEach { it.resolve() } tasks.register("downloadDependencies") { doLast { configurations.resolveAll() buildscript.configurations.resolveAll() } } ```
You should try this one : ``` task getDeps(type: Copy) { from configurations.runtime into 'runtime/' } ``` I was was looking for it some time ago when working on a project in which we had to download all dependencies into current working directory at some point in our provisioning script. I guess you're trying to achieve something similar.
21,814,672
I am using spring framework for writing a web service application. There are not html or jsp pages in the application. It is purely web service. **This is my Controller class** ``` @RequestMapping("/*") public class Opinion { private FeedbackService fs; public Opinion(FeedbackService fs){ this.fs=fs; } @RequestMapping(value="/givefeedback",method=RequestMethod.POST) public void Login(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException { ObjectInputStream in=new ObjectInputStream(request.getInputStream()); serialize.Feedback feedback=(serialize.Feedback)in.readObject(); fs.writeFeedback(feedback); response.setStatus(200); } ``` **My mvc-config.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="poll_Web" class="sef.controller.Opinion"> <constructor-arg ref="feedbackService" /> </bean> <context:component-scan base-package="sef.controller" /> </beans> ``` **My web.xml** ``` <servlet> <servlet-name>opinionDispacher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>opinionDispacher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </context-param> ``` I am using the URL `localhost:8080/feedback/givefeedback`. The app is deployed as **feedback.war**. But the request is not at all forwarded to the controller. I am not sure why is this is happening. I am also not sure till which point the request goes in the chain.
2014/02/16
[ "https://Stackoverflow.com/questions/21814672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139023/" ]
For Intellij go to View > Tool Windows > Gradle > Refresh All Projects (the blue circular arrows at the top of the Gradle window. [![enter image description here](https://i.stack.imgur.com/DEOqt.jpg)](https://i.stack.imgur.com/DEOqt.jpg)
This version builds on Robert Elliot's, but I'm not 100% sure of its efficacy. ``` // There are a few dependencies added by one of the Scala plugins that this cannot reach. task downloadDependencies { description "Pre-downloads *most* dependencies" doLast { configurations.getAsMap().each { name, config -> println "Retrieving dependencies for $name" try { config.files } catch (e) { project.logger.info e.message // some cannot be resolved, silentlyish skip them } } } } ``` I tried putting it into configuration instead of action (by removing doLast) and it broke zinc. I worked around it, but the end result was the same with or without. So, I left it as an explicit state. It seems to work enough to *reduce* the dependencies that have to be downloaded later, but not eliminate them in my case. I think one of the Scala plugins adds dependencies later.
21,814,672
I am using spring framework for writing a web service application. There are not html or jsp pages in the application. It is purely web service. **This is my Controller class** ``` @RequestMapping("/*") public class Opinion { private FeedbackService fs; public Opinion(FeedbackService fs){ this.fs=fs; } @RequestMapping(value="/givefeedback",method=RequestMethod.POST) public void Login(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException { ObjectInputStream in=new ObjectInputStream(request.getInputStream()); serialize.Feedback feedback=(serialize.Feedback)in.readObject(); fs.writeFeedback(feedback); response.setStatus(200); } ``` **My mvc-config.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="poll_Web" class="sef.controller.Opinion"> <constructor-arg ref="feedbackService" /> </bean> <context:component-scan base-package="sef.controller" /> </beans> ``` **My web.xml** ``` <servlet> <servlet-name>opinionDispacher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>opinionDispacher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </context-param> ``` I am using the URL `localhost:8080/feedback/givefeedback`. The app is deployed as **feedback.war**. But the request is not at all forwarded to the controller. I am not sure why is this is happening. I am also not sure till which point the request goes in the chain.
2014/02/16
[ "https://Stackoverflow.com/questions/21814672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139023/" ]
You should try this one : ``` task getDeps(type: Copy) { from configurations.runtime into 'runtime/' } ``` I was was looking for it some time ago when working on a project in which we had to download all dependencies into current working directory at some point in our provisioning script. I guess you're trying to achieve something similar.
There is no task to download dependencies; they are downloaded on demand. To learn how to manage dependencies with Gradle, see "Chapter 8. Dependency Management Basics" in the [Gradle User Guide](http://gradle.org/docs/current/userguide/userguide_single.html).
21,814,672
I am using spring framework for writing a web service application. There are not html or jsp pages in the application. It is purely web service. **This is my Controller class** ``` @RequestMapping("/*") public class Opinion { private FeedbackService fs; public Opinion(FeedbackService fs){ this.fs=fs; } @RequestMapping(value="/givefeedback",method=RequestMethod.POST) public void Login(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException { ObjectInputStream in=new ObjectInputStream(request.getInputStream()); serialize.Feedback feedback=(serialize.Feedback)in.readObject(); fs.writeFeedback(feedback); response.setStatus(200); } ``` **My mvc-config.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="poll_Web" class="sef.controller.Opinion"> <constructor-arg ref="feedbackService" /> </bean> <context:component-scan base-package="sef.controller" /> </beans> ``` **My web.xml** ``` <servlet> <servlet-name>opinionDispacher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>opinionDispacher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </context-param> ``` I am using the URL `localhost:8080/feedback/givefeedback`. The app is deployed as **feedback.war**. But the request is not at all forwarded to the controller. I am not sure why is this is happening. I am also not sure till which point the request goes in the chain.
2014/02/16
[ "https://Stackoverflow.com/questions/21814672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139023/" ]
Downloading java dependencies is possible, if you actually really need to download them into a folder. Example: ``` apply plugin: 'java' dependencies { runtime group: 'com.netflix.exhibitor', name: 'exhibitor-standalone', version: '1.5.2' runtime group: 'org.apache.zookeeper', name: 'zookeeper', version: '3.4.6' } repositories { mavenCentral() } task getDeps(type: Copy) { from sourceSets.main.runtimeClasspath into 'runtime/' } ``` Download the dependencies (and their dependencies) into the folder `runtime` when you execute `gradle getDeps`.
You should try this one : ``` task getDeps(type: Copy) { from configurations.runtime into 'runtime/' } ``` I was was looking for it some time ago when working on a project in which we had to download all dependencies into current working directory at some point in our provisioning script. I guess you're trying to achieve something similar.
21,814,672
I am using spring framework for writing a web service application. There are not html or jsp pages in the application. It is purely web service. **This is my Controller class** ``` @RequestMapping("/*") public class Opinion { private FeedbackService fs; public Opinion(FeedbackService fs){ this.fs=fs; } @RequestMapping(value="/givefeedback",method=RequestMethod.POST) public void Login(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException { ObjectInputStream in=new ObjectInputStream(request.getInputStream()); serialize.Feedback feedback=(serialize.Feedback)in.readObject(); fs.writeFeedback(feedback); response.setStatus(200); } ``` **My mvc-config.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="poll_Web" class="sef.controller.Opinion"> <constructor-arg ref="feedbackService" /> </bean> <context:component-scan base-package="sef.controller" /> </beans> ``` **My web.xml** ``` <servlet> <servlet-name>opinionDispacher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>opinionDispacher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </context-param> ``` I am using the URL `localhost:8080/feedback/givefeedback`. The app is deployed as **feedback.war**. But the request is not at all forwarded to the controller. I am not sure why is this is happening. I am also not sure till which point the request goes in the chain.
2014/02/16
[ "https://Stackoverflow.com/questions/21814672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139023/" ]
Downloading java dependencies is possible, if you actually really need to download them into a folder. Example: ``` apply plugin: 'java' dependencies { runtime group: 'com.netflix.exhibitor', name: 'exhibitor-standalone', version: '1.5.2' runtime group: 'org.apache.zookeeper', name: 'zookeeper', version: '3.4.6' } repositories { mavenCentral() } task getDeps(type: Copy) { from sourceSets.main.runtimeClasspath into 'runtime/' } ``` Download the dependencies (and their dependencies) into the folder `runtime` when you execute `gradle getDeps`.
A slightly lighter task that doesn't unnecessarily copy files to a dir: ``` task downloadDependencies(type: Exec) { configurations.testRuntime.files commandLine 'echo', 'Downloaded all dependencies' } ``` Updated for kotlin & gradle 6.2.0, with buildscript dependency resolution added: ```kotlin fun Configuration.isDeprecated() = this is DeprecatableConfiguration && resolutionAlternatives != null fun ConfigurationContainer.resolveAll() = this .filter { it.isCanBeResolved && !it.isDeprecated() } .forEach { it.resolve() } tasks.register("downloadDependencies") { doLast { configurations.resolveAll() buildscript.configurations.resolveAll() } } ```
21,814,672
I am using spring framework for writing a web service application. There are not html or jsp pages in the application. It is purely web service. **This is my Controller class** ``` @RequestMapping("/*") public class Opinion { private FeedbackService fs; public Opinion(FeedbackService fs){ this.fs=fs; } @RequestMapping(value="/givefeedback",method=RequestMethod.POST) public void Login(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException { ObjectInputStream in=new ObjectInputStream(request.getInputStream()); serialize.Feedback feedback=(serialize.Feedback)in.readObject(); fs.writeFeedback(feedback); response.setStatus(200); } ``` **My mvc-config.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="poll_Web" class="sef.controller.Opinion"> <constructor-arg ref="feedbackService" /> </bean> <context:component-scan base-package="sef.controller" /> </beans> ``` **My web.xml** ``` <servlet> <servlet-name>opinionDispacher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>opinionDispacher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </context-param> ``` I am using the URL `localhost:8080/feedback/givefeedback`. The app is deployed as **feedback.war**. But the request is not at all forwarded to the controller. I am not sure why is this is happening. I am also not sure till which point the request goes in the chain.
2014/02/16
[ "https://Stackoverflow.com/questions/21814672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139023/" ]
I have found this answer <https://stackoverflow.com/a/47107135/3067148> also very helpful: > > `gradle dependencies` will list the dependencies and download them as a > side-effect. > > >
It is hard to figure out exactly what you are trying to do from the question. I'll take a guess and say that you want to add an extra compile task in addition to those provided out of the box by the java plugin. The easiest way to do this is probably to specify a new `sourceSet` called 'speedTest'. This will generate a `configuration` called 'speedTest' which you can use to specify your dependencies within a `dependencies` block. It will also generate a task called `compileSpeedTestJava` for you. For an example, take a look at [defining new source sets](http://www.gradle.org/docs/current/userguide/java_plugin.html#defining_new_source_sets) in the [Java plugin documentation](http://www.gradle.org/docs/current/userguide/java_plugin.html) In general it seems that you have some incorrect assumptions about how dependency management works with Gradle. I would echo the advice of the others to read the 'Dependency Management' chapters of the user guide again :)
21,814,672
I am using spring framework for writing a web service application. There are not html or jsp pages in the application. It is purely web service. **This is my Controller class** ``` @RequestMapping("/*") public class Opinion { private FeedbackService fs; public Opinion(FeedbackService fs){ this.fs=fs; } @RequestMapping(value="/givefeedback",method=RequestMethod.POST) public void Login(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException { ObjectInputStream in=new ObjectInputStream(request.getInputStream()); serialize.Feedback feedback=(serialize.Feedback)in.readObject(); fs.writeFeedback(feedback); response.setStatus(200); } ``` **My mvc-config.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="poll_Web" class="sef.controller.Opinion"> <constructor-arg ref="feedbackService" /> </bean> <context:component-scan base-package="sef.controller" /> </beans> ``` **My web.xml** ``` <servlet> <servlet-name>opinionDispacher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>opinionDispacher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </context-param> ``` I am using the URL `localhost:8080/feedback/givefeedback`. The app is deployed as **feedback.war**. But the request is not at all forwarded to the controller. I am not sure why is this is happening. I am also not sure till which point the request goes in the chain.
2014/02/16
[ "https://Stackoverflow.com/questions/21814672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139023/" ]
A slightly lighter task that doesn't unnecessarily copy files to a dir: ``` task downloadDependencies(type: Exec) { configurations.testRuntime.files commandLine 'echo', 'Downloaded all dependencies' } ``` Updated for kotlin & gradle 6.2.0, with buildscript dependency resolution added: ```kotlin fun Configuration.isDeprecated() = this is DeprecatableConfiguration && resolutionAlternatives != null fun ConfigurationContainer.resolveAll() = this .filter { it.isCanBeResolved && !it.isDeprecated() } .forEach { it.resolve() } tasks.register("downloadDependencies") { doLast { configurations.resolveAll() buildscript.configurations.resolveAll() } } ```
Building on top of Robert Elliot's answer. For whatever reason, if one is interested in downloading the dependencies to Gradle cache then copying to a local repository like maven's (by default `~/.m2/repository`): ```scala task downloadDependencies(type: Exec) { configurations.implementation.files + configurations.runtimeOnly.files finalizedBy "cacheToMavenLocal" commandLine "echo", "Downloaded all dependencies and copied to mavenLocal" } task cacheToMavenLocal(type: Copy) { from new File(gradle.gradleUserHomeDir, "caches/modules-2/files-2.1") into repositories.mavenLocal().url eachFile { List<String> parts = it.path.split("/") it.path = [parts[0].replace(".","/"), parts[1], parts[2], parts[4]].join("/") } includeEmptyDirs false } ``` The task `cacheToMavenLocal` was copied and adapted from [@Adrodoc55's answer on Gradle forum](https://discuss.gradle.org/t/need-a-gradle-task-to-copy-all-dependencies-to-a-local-maven-repo/13397/15).
21,814,672
I am using spring framework for writing a web service application. There are not html or jsp pages in the application. It is purely web service. **This is my Controller class** ``` @RequestMapping("/*") public class Opinion { private FeedbackService fs; public Opinion(FeedbackService fs){ this.fs=fs; } @RequestMapping(value="/givefeedback",method=RequestMethod.POST) public void Login(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException { ObjectInputStream in=new ObjectInputStream(request.getInputStream()); serialize.Feedback feedback=(serialize.Feedback)in.readObject(); fs.writeFeedback(feedback); response.setStatus(200); } ``` **My mvc-config.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="poll_Web" class="sef.controller.Opinion"> <constructor-arg ref="feedbackService" /> </bean> <context:component-scan base-package="sef.controller" /> </beans> ``` **My web.xml** ``` <servlet> <servlet-name>opinionDispacher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>opinionDispacher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </context-param> ``` I am using the URL `localhost:8080/feedback/givefeedback`. The app is deployed as **feedback.war**. But the request is not at all forwarded to the controller. I am not sure why is this is happening. I am also not sure till which point the request goes in the chain.
2014/02/16
[ "https://Stackoverflow.com/questions/21814672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139023/" ]
Downloading java dependencies is possible, if you actually really need to download them into a folder. Example: ``` apply plugin: 'java' dependencies { runtime group: 'com.netflix.exhibitor', name: 'exhibitor-standalone', version: '1.5.2' runtime group: 'org.apache.zookeeper', name: 'zookeeper', version: '3.4.6' } repositories { mavenCentral() } task getDeps(type: Copy) { from sourceSets.main.runtimeClasspath into 'runtime/' } ``` Download the dependencies (and their dependencies) into the folder `runtime` when you execute `gradle getDeps`.
This version builds on Robert Elliot's, but I'm not 100% sure of its efficacy. ``` // There are a few dependencies added by one of the Scala plugins that this cannot reach. task downloadDependencies { description "Pre-downloads *most* dependencies" doLast { configurations.getAsMap().each { name, config -> println "Retrieving dependencies for $name" try { config.files } catch (e) { project.logger.info e.message // some cannot be resolved, silentlyish skip them } } } } ``` I tried putting it into configuration instead of action (by removing doLast) and it broke zinc. I worked around it, but the end result was the same with or without. So, I left it as an explicit state. It seems to work enough to *reduce* the dependencies that have to be downloaded later, but not eliminate them in my case. I think one of the Scala plugins adds dependencies later.
21,814,672
I am using spring framework for writing a web service application. There are not html or jsp pages in the application. It is purely web service. **This is my Controller class** ``` @RequestMapping("/*") public class Opinion { private FeedbackService fs; public Opinion(FeedbackService fs){ this.fs=fs; } @RequestMapping(value="/givefeedback",method=RequestMethod.POST) public void Login(HttpServletRequest request,HttpServletResponse response) throws IOException, ClassNotFoundException { ObjectInputStream in=new ObjectInputStream(request.getInputStream()); serialize.Feedback feedback=(serialize.Feedback)in.readObject(); fs.writeFeedback(feedback); response.setStatus(200); } ``` **My mvc-config.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="poll_Web" class="sef.controller.Opinion"> <constructor-arg ref="feedbackService" /> </bean> <context:component-scan base-package="sef.controller" /> </beans> ``` **My web.xml** ``` <servlet> <servlet-name>opinionDispacher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>opinionDispacher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:repository-config.xml /WEB-INF/mvc-config.xml </param-value> </context-param> ``` I am using the URL `localhost:8080/feedback/givefeedback`. The app is deployed as **feedback.war**. But the request is not at all forwarded to the controller. I am not sure why is this is happening. I am also not sure till which point the request goes in the chain.
2014/02/16
[ "https://Stackoverflow.com/questions/21814672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139023/" ]
You should try this one : ``` task getDeps(type: Copy) { from configurations.runtime into 'runtime/' } ``` I was was looking for it some time ago when working on a project in which we had to download all dependencies into current working directory at some point in our provisioning script. I guess you're trying to achieve something similar.
It is hard to figure out exactly what you are trying to do from the question. I'll take a guess and say that you want to add an extra compile task in addition to those provided out of the box by the java plugin. The easiest way to do this is probably to specify a new `sourceSet` called 'speedTest'. This will generate a `configuration` called 'speedTest' which you can use to specify your dependencies within a `dependencies` block. It will also generate a task called `compileSpeedTestJava` for you. For an example, take a look at [defining new source sets](http://www.gradle.org/docs/current/userguide/java_plugin.html#defining_new_source_sets) in the [Java plugin documentation](http://www.gradle.org/docs/current/userguide/java_plugin.html) In general it seems that you have some incorrect assumptions about how dependency management works with Gradle. I would echo the advice of the others to read the 'Dependency Management' chapters of the user guide again :)
23,565,370
I have a question regarding something I'm seeing in some VB.NET code on a project that I've had to take over. In a form the developer has declared a very simple 15sec timer. ``` Private WithEvents mtmrManualDecision As New System.Timers.Timer(15000) ``` Now, I know that this timer will trigger the mtmrManualDecision\_Elapsed event each 15 seconds after it has been started via mtmrManualDecision.Start(). I'm also familiar with stopping this timer via mtmrManualDecision.Stop(). However, I'm seeing this line of code in parts of the form (like when a button is clicked or the form is closed). ``` RemoveHandler mtmrEvaluation.Elapsed, AddressOf mtmrEvaluation_Elapsed ``` I believe this is basically stopping the timer. Why do this instead of just stop? It's not being added back or used again after this so I'm wondering why the need to do this. I don't normally use RemoveHandler unless I actually used AddHandler in my own code. I believe that the declaration of the timer using "WithEvents" automatically adds a handler for the Elapsed event and he just wants to remove it. Is this really necessary and wouldn't the garbage collection take care of removing the handler like it does with other events, etc.)? Any clarification or ideas would be appreciated. Thank you very much.
2014/05/09
[ "https://Stackoverflow.com/questions/23565370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218207/" ]
> > I believe this is basically stopping the timer. > > > No, it does not stop the timer. The timer does not stop until your program stops it, or disposes of it. Once you remove the handler, the timer will stop delivering the events to your program, but it would continue "ticking" in the background. For example, if you remove the handler 3 seconds into the 15-second interval, and then add it back 2 seconds later, you will get an event after 10 more seconds (3 + 2 + 10 = 15). One reason to remove a handler is to let its associated object, if any, become eligible for garbage collection. This prevents a "lingerer" memory leak. For example, consider a timer that produces an object, and stores it into a list associated with another object, which is owned by your main program. Let's say that at some point your main program drops the object hosting the list. However, the list may not become eligible for garbage collection if the event handler keeps a strong reference to the object. Unregistering for the event explicitly is one way of addressing this problem; another way is to use a [Weak Event Pattern](http://msdn.microsoft.com/en-us/library/aa970850%28v=vs.110%29.aspx).
> > I believe this is basically stopping the timer > > > No, it's removing a single handler. If there are any *other* handlers, those will keep firing. Or maybe the developer wants to be able to re-add the handler later on, with the timer keeping going with its original schedule (rather than stopping/starting which will change the schedule). You haven't really provided us enough information to get into the head of the original developer, but these are just examples of why removing a handler from a timer *isn't* the same as stopping it.
20,596,588
I would like to be able to insert a row into an SQL table, giving it a specified id. The trouble is that the id is unique and for it to work I'd have to update the rows after the inserted row, increasing the id's by 1. So, say I have a table like the following ![enter image description here](https://i.stack.imgur.com/HE9xb.png) I would like to insert the following row (with the id of an existing row)... ![enter image description here](https://i.stack.imgur.com/CYMr1.png) I want the table to look like this after I have inserted the row... ![enter image description here](https://i.stack.imgur.com/R5HUB.png) The id's of the rows after the inserted row need to change,like in the above example. The reason for me doing this is to allow users to order events by importance (I'm using jQuery to order them, just not sure how to do the stuff behind the scenes) Anything that sets me off in the right direction is appreciated, thanks in advance.
2013/12/15
[ "https://Stackoverflow.com/questions/20596588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1997661/" ]
Firstly, best practice is to **never ever** modify the primary key of a row once it is inserted (I assume `id` is your primary key?). *Just Don't Do It™*. **Instead**, create an additional column (called `importance`/`priority`/something, and modify that field as necessary. --- That said, the query would look something like: ``` START TRANSACTION; # increment every importance value that needs incrementing to make way for the new row: UPDATE mytable SET importance = importance + 1 WHERE importance >= newimportance; # insert the new row: INSERT INTO mytable (title, text, importance) VALUES ('newtitle', 'newtext', newimportance); COMMIT; ```
Something is wrong with your design. An `id` column typically has a unique value that represents each row. The nice thing about `id`s is that the value does *not* change, which means that they can be referenced by other tables or even an application. It sounds like you want some sort of "sort order" or something like that. I would recommend that you have another column for this purpose. Or, at the very least, rename the `id` column so someone who knows databases will not be confused when looking at your schema. Something called `id` (or `tableID` or something similar) should generally be an auto-incremented primary key. In any case, you can do what you want by first doing an update: ``` update t set newcol = newcol + 1 where newcol >= NEWVALUE; insert into t(newcol, . . .) select NEWVALUE, . . .; ```
42,845,942
Good afternoon, I'm learning and using pyttsx for speech, the thing is that I want to use it as a "female" voice but I can not do it using this code: ``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work engine.setProperty('female', voice.Voice.gender) #not even engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[4].id) engine.say("Hello World") engine.runAndWait() class Voice(object): def __init__(self, id, name=None, languages=[], gender=None, age=None): self.id = id self.name = name self.languages = languages self.gender = gender self.age = age ```
2017/03/16
[ "https://Stackoverflow.com/questions/42845942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724033/" ]
Use `sound=getProperty ('voices'); engine.setProperty('voice','sound [1].id')` This will definitely work. 0 for male and 1 for female.
You have to check whether your computer has other narrator options or not for that go to control panel -> Ease of Access center -> Narrator options there will be option how many narrators you have. other option go to windows search for narrator. if you don't have other narrator that you have written in code, default narrator will work only.
42,845,942
Good afternoon, I'm learning and using pyttsx for speech, the thing is that I want to use it as a "female" voice but I can not do it using this code: ``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work engine.setProperty('female', voice.Voice.gender) #not even engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[4].id) engine.say("Hello World") engine.runAndWait() class Voice(object): def __init__(self, id, name=None, languages=[], gender=None, age=None): self.id = id self.name = name self.languages = languages self.gender = gender self.age = age ```
2017/03/16
[ "https://Stackoverflow.com/questions/42845942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724033/" ]
if you use linux/espeak... change the code here `engine.setProperty('voice', 'english+f1')` you can change the voice by adding f1 until f4
Use `sound=getProperty ('voices'); engine.setProperty('voice','sound [1].id')` This will definitely work. 0 for male and 1 for female.
42,845,942
Good afternoon, I'm learning and using pyttsx for speech, the thing is that I want to use it as a "female" voice but I can not do it using this code: ``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work engine.setProperty('female', voice.Voice.gender) #not even engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[4].id) engine.say("Hello World") engine.runAndWait() class Voice(object): def __init__(self, id, name=None, languages=[], gender=None, age=None): self.id = id self.name = name self.languages = languages self.gender = gender self.age = age ```
2017/03/16
[ "https://Stackoverflow.com/questions/42845942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724033/" ]
I use this helper function, that iterates over the voices. If a voice for a specific language and gender exists, it will change to this voice otherwise an exception will be raised. ``` # language : en_US, de_DE, ... # gender : VoiceGenderFemale, VoiceGenderMale def change_voice(engine, language, gender='VoiceGenderFemale'): for voice in engine.getProperty('voices'): if language in voice.languages and gender == voice.gender: engine.setProperty('voice', voice.id) return True raise RuntimeError("Language '{}' for gender '{}' not found".format(language, gender)) ``` And finally it will be used like this: ``` engine = pt.init() change_voice(engine, "en_US", "VoiceGenderFemale") engine.say("Hello World") engine.runAndWait() ```
``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work #engine.setProperty('female', voice.Voice.gender) #not even #engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[1].id) engine.say("Hello World") engine.runAndWait ```
42,845,942
Good afternoon, I'm learning and using pyttsx for speech, the thing is that I want to use it as a "female" voice but I can not do it using this code: ``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work engine.setProperty('female', voice.Voice.gender) #not even engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[4].id) engine.say("Hello World") engine.runAndWait() class Voice(object): def __init__(self, id, name=None, languages=[], gender=None, age=None): self.id = id self.name = name self.languages = languages self.gender = gender self.age = age ```
2017/03/16
[ "https://Stackoverflow.com/questions/42845942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724033/" ]
I used the following code to iterate through the voices to find the female voice ``` import pyttsx engine = pyttsx.init() voices = engine.getProperty('voices') for voice in voices: engine.setProperty('voice', voice.id) print voice.id engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait() ``` On my Windows 10 machine the female voice was HKEY\_LOCAL\_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS\_MS\_EN-US\_ZIRA\_11.0 So I changed my code to look like this ``` import pyttsx engine = pyttsx.init() engine.setProperty('voice', 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0') engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait() ```
Use `sound=getProperty ('voices'); engine.setProperty('voice','sound [1].id')` This will definitely work. 0 for male and 1 for female.
42,845,942
Good afternoon, I'm learning and using pyttsx for speech, the thing is that I want to use it as a "female" voice but I can not do it using this code: ``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work engine.setProperty('female', voice.Voice.gender) #not even engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[4].id) engine.say("Hello World") engine.runAndWait() class Voice(object): def __init__(self, id, name=None, languages=[], gender=None, age=None): self.id = id self.name = name self.languages = languages self.gender = gender self.age = age ```
2017/03/16
[ "https://Stackoverflow.com/questions/42845942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724033/" ]
This is a simpler solution: ``` engine = pyttsx.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) ```
``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work #engine.setProperty('female', voice.Voice.gender) #not even #engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[1].id) engine.say("Hello World") engine.runAndWait ```
42,845,942
Good afternoon, I'm learning and using pyttsx for speech, the thing is that I want to use it as a "female" voice but I can not do it using this code: ``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work engine.setProperty('female', voice.Voice.gender) #not even engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[4].id) engine.say("Hello World") engine.runAndWait() class Voice(object): def __init__(self, id, name=None, languages=[], gender=None, age=None): self.id = id self.name = name self.languages = languages self.gender = gender self.age = age ```
2017/03/16
[ "https://Stackoverflow.com/questions/42845942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724033/" ]
Use `sound=getProperty ('voices'); engine.setProperty('voice','sound [1].id')` This will definitely work. 0 for male and 1 for female.
``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work #engine.setProperty('female', voice.Voice.gender) #not even #engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[1].id) engine.say("Hello World") engine.runAndWait ```
42,845,942
Good afternoon, I'm learning and using pyttsx for speech, the thing is that I want to use it as a "female" voice but I can not do it using this code: ``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work engine.setProperty('female', voice.Voice.gender) #not even engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[4].id) engine.say("Hello World") engine.runAndWait() class Voice(object): def __init__(self, id, name=None, languages=[], gender=None, age=None): self.id = id self.name = name self.languages = languages self.gender = gender self.age = age ```
2017/03/16
[ "https://Stackoverflow.com/questions/42845942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724033/" ]
I used the following code to iterate through the voices to find the female voice ``` import pyttsx engine = pyttsx.init() voices = engine.getProperty('voices') for voice in voices: engine.setProperty('voice', voice.id) print voice.id engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait() ``` On my Windows 10 machine the female voice was HKEY\_LOCAL\_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS\_MS\_EN-US\_ZIRA\_11.0 So I changed my code to look like this ``` import pyttsx engine = pyttsx.init() engine.setProperty('voice', 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0') engine.say('The quick brown fox jumped over the lazy dog.') engine.runAndWait() ```
``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work #engine.setProperty('female', voice.Voice.gender) #not even #engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[1].id) engine.say("Hello World") engine.runAndWait ```
42,845,942
Good afternoon, I'm learning and using pyttsx for speech, the thing is that I want to use it as a "female" voice but I can not do it using this code: ``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work engine.setProperty('female', voice.Voice.gender) #not even engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[4].id) engine.say("Hello World") engine.runAndWait() class Voice(object): def __init__(self, id, name=None, languages=[], gender=None, age=None): self.id = id self.name = name self.languages = languages self.gender = gender self.age = age ```
2017/03/16
[ "https://Stackoverflow.com/questions/42845942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724033/" ]
This is a simpler solution: ``` engine = pyttsx.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) ```
Use `sound=getProperty ('voices'); engine.setProperty('voice','sound [1].id')` This will definitely work. 0 for male and 1 for female.
42,845,942
Good afternoon, I'm learning and using pyttsx for speech, the thing is that I want to use it as a "female" voice but I can not do it using this code: ``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work engine.setProperty('female', voice.Voice.gender) #not even engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[4].id) engine.say("Hello World") engine.runAndWait() class Voice(object): def __init__(self, id, name=None, languages=[], gender=None, age=None): self.id = id self.name = name self.languages = languages self.gender = gender self.age = age ```
2017/03/16
[ "https://Stackoverflow.com/questions/42845942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724033/" ]
Use `sound=getProperty ('voices'); engine.setProperty('voice','sound [1].id')` This will definitely work. 0 for male and 1 for female.
I use this helper function, that iterates over the voices. If a voice for a specific language and gender exists, it will change to this voice otherwise an exception will be raised. ``` # language : en_US, de_DE, ... # gender : VoiceGenderFemale, VoiceGenderMale def change_voice(engine, language, gender='VoiceGenderFemale'): for voice in engine.getProperty('voices'): if language in voice.languages and gender == voice.gender: engine.setProperty('voice', voice.id) return True raise RuntimeError("Language '{}' for gender '{}' not found".format(language, gender)) ``` And finally it will be used like this: ``` engine = pt.init() change_voice(engine, "en_US", "VoiceGenderFemale") engine.say("Hello World") engine.runAndWait() ```
42,845,942
Good afternoon, I'm learning and using pyttsx for speech, the thing is that I want to use it as a "female" voice but I can not do it using this code: ``` import pyttsx as pt from pyttsx import voice engine = pt.init() voices = engine.getProperty('voices') #engine.setProperty('gender', 'female') # also does not work engine.setProperty('female', voice.Voice.gender) #not even engine.setProperty('female', voice.gender) #does not work engine.setProperty('voice', voices[4].id) engine.say("Hello World") engine.runAndWait() class Voice(object): def __init__(self, id, name=None, languages=[], gender=None, age=None): self.id = id self.name = name self.languages = languages self.gender = gender self.age = age ```
2017/03/16
[ "https://Stackoverflow.com/questions/42845942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7724033/" ]
if you use linux/espeak... change the code here `engine.setProperty('voice', 'english+f1')` you can change the voice by adding f1 until f4
You have to check whether your computer has other narrator options or not for that go to control panel -> Ease of Access center -> Narrator options there will be option how many narrators you have. other option go to windows search for narrator. if you don't have other narrator that you have written in code, default narrator will work only.
206,614
After re-installing Lubuntu 12.04 system on my laptop an older problem re-emerged after a few days and installation of different programs: without apparent reason the external mouse and sometimes other usb connected devices (including hdd) stop working. The hdd shows it has tension as it has a light there, and the external mouse flashes for a second when plugged. [I have posted a different version of this problem before](https://askubuntu.com/q/178054/47206). I keep it for now as example of the two answers there. None of them works here. **Logging out-in does nothing, restart does.** The event seems entirely random, after reboot it will reappear after many days or weeks or, rarely, after a few hours. * <http://pastebin.com/0qR8bhhX> in `var/log/syslog` after new occurrence (**with only external wired mouse and keyboard**) What counts is at the end I guess: ``` Nov 24 14:06:55 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29953.822962] usb 3-1: USB disconnect, device number 3 Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069427] uhci_hcd 0000:00:1d.0: host controller process error, something bad happened! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069439] uhci_hcd 0000:00:1d.0: host controller halted, very bad! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069461] uhci_hcd 0000:00:1d.0: HC died; cleaning up Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069492] usb 2-2: USB disconnect, device number 2 ``` * I have noticed that **on most occasions only the external mouse and keyboard are affected, but not the external HDD. Or if it is, replugging it solves the problem**. * I have a dual boot with WinXP: **in Windows this never happens, so it is not a hardware issue** * **I have used Lubuntu Quantal 12.10 and the same problem happened there as well**. Upgrading to that would not be a solution * On certain occasion **only restarting 2 or even 3 times** solved it. --- **Using the same PC/hardware with Linux Mint 14 (Quantal) Xfce, the problem almost disappeared**(it happened *once* since then). I am not sure whether this 'solution' comes from using Xfce or Mint (I guess Mint 14 Nadia uses the same kernel as Lubuntu Quantal).
2012/10/26
[ "https://askubuntu.com/questions/206614", "https://askubuntu.com", "https://askubuntu.com/users/-1/" ]
kernel vs hardware issues ------------------------- If you have ruled out possible hardware issues such as voltage/current problems, failing USB ports/hubs then this is probably a kernel problem. If you feel comfortable with possible non-booting issues/black screen issues on boot, you could try installing the quantal kernel available in the 12.04 repositories. * [My computer boots to a black screen, what options do I have to fix it?](https://askubuntu.com/questions/162075/my-computer-boots-to-a-black-screen-what-options-do-i-have-to-fix-it) Remember - most blackscreen issues are due to installation of proprietary graphics drivers. You will have most luck removing these first before upgrading your kernel. To install the quantal kernel: ``` sudo apt-get install linux-generic-lts-quantal ``` Remember to do a full system backup to allow you to recover if the new kernel breaks more than it fixes. * [Comparison of backup tools](https://askubuntu.com/questions/2596/comparison-of-backup-tools)
A **fast solution** that works at least in my case (Linux Mint KDE, on a Lenovo Yoga 3 Pro laptop): With the laptop on, just **press the power button for about 30 seconds**, that is shutting down and still pressing for a while after this. I did it with the charger unplugged. After turning on the laptop, the USB ports work again.
206,614
After re-installing Lubuntu 12.04 system on my laptop an older problem re-emerged after a few days and installation of different programs: without apparent reason the external mouse and sometimes other usb connected devices (including hdd) stop working. The hdd shows it has tension as it has a light there, and the external mouse flashes for a second when plugged. [I have posted a different version of this problem before](https://askubuntu.com/q/178054/47206). I keep it for now as example of the two answers there. None of them works here. **Logging out-in does nothing, restart does.** The event seems entirely random, after reboot it will reappear after many days or weeks or, rarely, after a few hours. * <http://pastebin.com/0qR8bhhX> in `var/log/syslog` after new occurrence (**with only external wired mouse and keyboard**) What counts is at the end I guess: ``` Nov 24 14:06:55 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29953.822962] usb 3-1: USB disconnect, device number 3 Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069427] uhci_hcd 0000:00:1d.0: host controller process error, something bad happened! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069439] uhci_hcd 0000:00:1d.0: host controller halted, very bad! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069461] uhci_hcd 0000:00:1d.0: HC died; cleaning up Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069492] usb 2-2: USB disconnect, device number 2 ``` * I have noticed that **on most occasions only the external mouse and keyboard are affected, but not the external HDD. Or if it is, replugging it solves the problem**. * I have a dual boot with WinXP: **in Windows this never happens, so it is not a hardware issue** * **I have used Lubuntu Quantal 12.10 and the same problem happened there as well**. Upgrading to that would not be a solution * On certain occasion **only restarting 2 or even 3 times** solved it. --- **Using the same PC/hardware with Linux Mint 14 (Quantal) Xfce, the problem almost disappeared**(it happened *once* since then). I am not sure whether this 'solution' comes from using Xfce or Mint (I guess Mint 14 Nadia uses the same kernel as Lubuntu Quantal).
2012/10/26
[ "https://askubuntu.com/questions/206614", "https://askubuntu.com", "https://askubuntu.com/users/-1/" ]
Old post, and replies are not relevant to USB 3.0. So here's how to reset a 3.0 Bus that stopped serving data: ``` su - ``` and as root: ``` echo -n "0000:06:00.0" | tee /sys/bus/pci/drivers/xhci_hcd/unbind echo -n "0000:06:00.0" | tee /sys/bus/pci/drivers/xhci_hcd/bind ``` After this, USB should start to work correctly again, just like after a restart. --- Explanation ----------- In case you're using a different driver, this is how I found what to do, use it as a reference: A `lsusb -t` will output this - take a note of the `xhci_hcd` driver for the fast bus, it's the 3.0 driver name: ``` $ lsusb -t /: Bus 04.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 5000M /: Bus 03.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 480M |__ Port 1: Dev 3, If 0, Class=Vendor Specific Class, Driver=dvb_usb_it913x, 480M /: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/6p, 480M ...etc ``` The directory to look for is `/sys/bus/pci/drivers/xhci_hcd` ``` drwxr-xr-x 2 root root 0 5 21:48 ./ drwxr-xr-x 28 root root 0 1 00:21 ../ lrwxrwxrwx 1 root root 0 6 00:29 0000:06:00.0 -> ../../../../devices/pci0000:00/0000:00:1c.3/0000:06:00.0/ --w------- 1 root root 4096 5 22:33 bind lrwxrwxrwx 1 root root 0 5 22:32 module -> ../../../../module/xhci_hcd/ --w------- 1 root root 4096 5 22:32 new_id --w------- 1 root root 4096 5 22:32 remove_id --w------- 1 root root 4096 5 22:32 uevent --w------- 1 root root 4096 5 22:33 unbind ``` In my case I needed to unbind `"0000:06:00.0"`. ps. If you need to rebind the USB 2.0 driver, follow the above instructions but with `ehci-pci`, or look [here](http://davidjb.com/blog/2012/06/restartreset-usb-in-ubuntu-12-04-without-rebooting/) (deserves a credit).
A **fast solution** that works at least in my case (Linux Mint KDE, on a Lenovo Yoga 3 Pro laptop): With the laptop on, just **press the power button for about 30 seconds**, that is shutting down and still pressing for a while after this. I did it with the charger unplugged. After turning on the laptop, the USB ports work again.
206,614
After re-installing Lubuntu 12.04 system on my laptop an older problem re-emerged after a few days and installation of different programs: without apparent reason the external mouse and sometimes other usb connected devices (including hdd) stop working. The hdd shows it has tension as it has a light there, and the external mouse flashes for a second when plugged. [I have posted a different version of this problem before](https://askubuntu.com/q/178054/47206). I keep it for now as example of the two answers there. None of them works here. **Logging out-in does nothing, restart does.** The event seems entirely random, after reboot it will reappear after many days or weeks or, rarely, after a few hours. * <http://pastebin.com/0qR8bhhX> in `var/log/syslog` after new occurrence (**with only external wired mouse and keyboard**) What counts is at the end I guess: ``` Nov 24 14:06:55 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29953.822962] usb 3-1: USB disconnect, device number 3 Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069427] uhci_hcd 0000:00:1d.0: host controller process error, something bad happened! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069439] uhci_hcd 0000:00:1d.0: host controller halted, very bad! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069461] uhci_hcd 0000:00:1d.0: HC died; cleaning up Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069492] usb 2-2: USB disconnect, device number 2 ``` * I have noticed that **on most occasions only the external mouse and keyboard are affected, but not the external HDD. Or if it is, replugging it solves the problem**. * I have a dual boot with WinXP: **in Windows this never happens, so it is not a hardware issue** * **I have used Lubuntu Quantal 12.10 and the same problem happened there as well**. Upgrading to that would not be a solution * On certain occasion **only restarting 2 or even 3 times** solved it. --- **Using the same PC/hardware with Linux Mint 14 (Quantal) Xfce, the problem almost disappeared**(it happened *once* since then). I am not sure whether this 'solution' comes from using Xfce or Mint (I guess Mint 14 Nadia uses the same kernel as Lubuntu Quantal).
2012/10/26
[ "https://askubuntu.com/questions/206614", "https://askubuntu.com", "https://askubuntu.com/users/-1/" ]
Power issues for USB 2.0 ------------------------ USB 2.0 has a maximum current draw available of 500mA, however it should be noted that the +5V on several ports may actually be on the same bus. For example on a desktop case the USB ports on the front of the machine may all be on the same bus, while the ports on the back of the machine will normally be a a different bus, or have completely separate +5V supplies for each group of USB 2.0 sockets. A low current device as defined by the USB 2.0 [standards](http://www.usb.org/developers/docs/) can draw up to 100mA (1 unit) while high current devices can draw up to 5 units (500mA). Hard drives with no external source of supply are typically high current devices. Devices should stop working if the +5V line drops below 4.75V and this is why many high power devices can cause problems on some computers. In addition to this the circuit that supplies +5V to each bus may refuse to re-negotiate high power capability if the device is drawing enough current to pull the +5V line too low. This is why high power devices will need to be removed and re-attached before they will work if they have failed due to a power problem, and also why a reboot does not allow them to re-attach while a full power down/up cycle may do so. Note that if one or more low power devices are already plugged into a USB bus, there may not be enough capacity available to also run a high power device such as an external hard drive. Using high power devices therefore needs to be planned for, and if problems exist the device needs to be used on it's own on any one bus or given a separate +5V supply. While the USB 2.0 standards document might be a little difficult to read, there is some very good information and explanations in the [wikipedia page on the subject of USB 2.0](http://en.wikipedia.org/wiki/Universal_Serial_Bus#Power) Also note that plugging in many low power devices such as through an external USB hub device can also cause a voltage drop on the bus supply line, causing some or all of the devices to be disabled. The types of cables used may also affect the reliability of high power devices. For example an external hard drive plugged in via a regular long USB cable may see enough of a voltage drop at 500mA to disable itself to prevent damage to its circuitry or drive motors. These devices are typically supplied with a special short cable, or a 'Y' cable that plugs into two USB ports to help with the power problem. Note that this only a partial solution to the problem relating specifically to the cabling issue, it's doesn't actually allow more than 500mA to be supplied since adjacent USB ports are likely to be on the same 5V 500mA supply internally in the computer. Even where a separate bus is used for the second plug on the 'Y' cable it won't be able to get a high current supply since it has no data connection to request it from the USB bus. Only one of the ports will be enabled as a high current supply. Since the very common use of USB keyboards and mice, problems can sometimes occur when these are both plugged into the same bus. Peak load currents at power-on can exceed the design specification of the USB bus and cause one or both of the devices to be disabled or to malfunction. Solutions to these problems usually involve using only a minimum of low power devices, using only well designed and made low power devices, making sure they are plugged into different buses with separate +5V lines, and where high power devices are involved using a powered hub to help with the supply problems seen on many USB 2.0 bus supplies. If it's not possible to use a powered hub, then the high power device should only be plugged in after the computer is powered up and the current drain from low power devices has stabilised. It should also be noted here that computers such as laptops and netbooks may have low power USB devices incorporated internally. Hardware such as internal card readers, wireless 3G adapters, and webcams are often connected internally to a USB bus. This may be a dedicated bus with it's own +5V power, or it may be shared with one or more external USB ports.
Base on `lsusb` ``` #lsusb Bus 002 Device 002: ID 04f3:0230 Elan Microelectronics Corp. 3D Optical Mouse Bus 003 Device 002: ID 04f3:0103 Elan Microelectronics Corp. Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub ``` Do `lsusb -t`, output will be in following format ``` $ lsusb -t /: Bus 04.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/4p, 5000M /: Bus 03.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/4p, 480M /: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci_hcd/2p, 480M |__ Port 1: Dev 2, If 0, Class=hub, Driver=hub/8p, 480M /: Bus 01.Port 1: Dev 1, Class=root_hub, Driver=ehci_hcd/2p, 480M |__ Port 1: Dev 2, If 0, Class=hub, Driver=hub/6p, 480M |__ Port 6: Dev 3, If 0, Class=HID, Driver=usbhid, 1.5M ``` Pay attention to the `Bus 00X` number and the `1.1`/`2.0` USB version in both output. If mouse and keyboard is on `1.1` now, try moving them to the `2.0` port, or the other way round. This does not fix the driver issue, but a work around (if it works).
206,614
After re-installing Lubuntu 12.04 system on my laptop an older problem re-emerged after a few days and installation of different programs: without apparent reason the external mouse and sometimes other usb connected devices (including hdd) stop working. The hdd shows it has tension as it has a light there, and the external mouse flashes for a second when plugged. [I have posted a different version of this problem before](https://askubuntu.com/q/178054/47206). I keep it for now as example of the two answers there. None of them works here. **Logging out-in does nothing, restart does.** The event seems entirely random, after reboot it will reappear after many days or weeks or, rarely, after a few hours. * <http://pastebin.com/0qR8bhhX> in `var/log/syslog` after new occurrence (**with only external wired mouse and keyboard**) What counts is at the end I guess: ``` Nov 24 14:06:55 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29953.822962] usb 3-1: USB disconnect, device number 3 Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069427] uhci_hcd 0000:00:1d.0: host controller process error, something bad happened! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069439] uhci_hcd 0000:00:1d.0: host controller halted, very bad! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069461] uhci_hcd 0000:00:1d.0: HC died; cleaning up Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069492] usb 2-2: USB disconnect, device number 2 ``` * I have noticed that **on most occasions only the external mouse and keyboard are affected, but not the external HDD. Or if it is, replugging it solves the problem**. * I have a dual boot with WinXP: **in Windows this never happens, so it is not a hardware issue** * **I have used Lubuntu Quantal 12.10 and the same problem happened there as well**. Upgrading to that would not be a solution * On certain occasion **only restarting 2 or even 3 times** solved it. --- **Using the same PC/hardware with Linux Mint 14 (Quantal) Xfce, the problem almost disappeared**(it happened *once* since then). I am not sure whether this 'solution' comes from using Xfce or Mint (I guess Mint 14 Nadia uses the same kernel as Lubuntu Quantal).
2012/10/26
[ "https://askubuntu.com/questions/206614", "https://askubuntu.com", "https://askubuntu.com/users/-1/" ]
Base on `lsusb` ``` #lsusb Bus 002 Device 002: ID 04f3:0230 Elan Microelectronics Corp. 3D Optical Mouse Bus 003 Device 002: ID 04f3:0103 Elan Microelectronics Corp. Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 002 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub ``` Do `lsusb -t`, output will be in following format ``` $ lsusb -t /: Bus 04.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/4p, 5000M /: Bus 03.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/4p, 480M /: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci_hcd/2p, 480M |__ Port 1: Dev 2, If 0, Class=hub, Driver=hub/8p, 480M /: Bus 01.Port 1: Dev 1, Class=root_hub, Driver=ehci_hcd/2p, 480M |__ Port 1: Dev 2, If 0, Class=hub, Driver=hub/6p, 480M |__ Port 6: Dev 3, If 0, Class=HID, Driver=usbhid, 1.5M ``` Pay attention to the `Bus 00X` number and the `1.1`/`2.0` USB version in both output. If mouse and keyboard is on `1.1` now, try moving them to the `2.0` port, or the other way round. This does not fix the driver issue, but a work around (if it works).
A **fast solution** that works at least in my case (Linux Mint KDE, on a Lenovo Yoga 3 Pro laptop): With the laptop on, just **press the power button for about 30 seconds**, that is shutting down and still pressing for a while after this. I did it with the charger unplugged. After turning on the laptop, the USB ports work again.
206,614
After re-installing Lubuntu 12.04 system on my laptop an older problem re-emerged after a few days and installation of different programs: without apparent reason the external mouse and sometimes other usb connected devices (including hdd) stop working. The hdd shows it has tension as it has a light there, and the external mouse flashes for a second when plugged. [I have posted a different version of this problem before](https://askubuntu.com/q/178054/47206). I keep it for now as example of the two answers there. None of them works here. **Logging out-in does nothing, restart does.** The event seems entirely random, after reboot it will reappear after many days or weeks or, rarely, after a few hours. * <http://pastebin.com/0qR8bhhX> in `var/log/syslog` after new occurrence (**with only external wired mouse and keyboard**) What counts is at the end I guess: ``` Nov 24 14:06:55 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29953.822962] usb 3-1: USB disconnect, device number 3 Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069427] uhci_hcd 0000:00:1d.0: host controller process error, something bad happened! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069439] uhci_hcd 0000:00:1d.0: host controller halted, very bad! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069461] uhci_hcd 0000:00:1d.0: HC died; cleaning up Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069492] usb 2-2: USB disconnect, device number 2 ``` * I have noticed that **on most occasions only the external mouse and keyboard are affected, but not the external HDD. Or if it is, replugging it solves the problem**. * I have a dual boot with WinXP: **in Windows this never happens, so it is not a hardware issue** * **I have used Lubuntu Quantal 12.10 and the same problem happened there as well**. Upgrading to that would not be a solution * On certain occasion **only restarting 2 or even 3 times** solved it. --- **Using the same PC/hardware with Linux Mint 14 (Quantal) Xfce, the problem almost disappeared**(it happened *once* since then). I am not sure whether this 'solution' comes from using Xfce or Mint (I guess Mint 14 Nadia uses the same kernel as Lubuntu Quantal).
2012/10/26
[ "https://askubuntu.com/questions/206614", "https://askubuntu.com", "https://askubuntu.com/users/-1/" ]
Something similar to this was happening to me. [This blog post](http://billauer.co.il/blog/2013/02/usb-reset-ehci-uhci-linux/) provided a partial solution. This is what worked for me: ``` sudo -s cd /sys/bus/pci/drivers/xhci_hcd/ for file in ????:??:??.? ; do echo -n "$file" > unbind echo -n "$file" > bind done ``` As noted at that block post, different systems get hung up in different places, so if the above doesn't work, you might want to try replacing `/sys/bus/pci/drivers/xhci_hcd/` with `/sys/bus/pci/drivers/ehci_hcd/`, or `/sys/bus/pci/drivers/uhci_hcd/`, if one of those exists.
Old post, and replies are not relevant to USB 3.0. So here's how to reset a 3.0 Bus that stopped serving data: ``` su - ``` and as root: ``` echo -n "0000:06:00.0" | tee /sys/bus/pci/drivers/xhci_hcd/unbind echo -n "0000:06:00.0" | tee /sys/bus/pci/drivers/xhci_hcd/bind ``` After this, USB should start to work correctly again, just like after a restart. --- Explanation ----------- In case you're using a different driver, this is how I found what to do, use it as a reference: A `lsusb -t` will output this - take a note of the `xhci_hcd` driver for the fast bus, it's the 3.0 driver name: ``` $ lsusb -t /: Bus 04.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 5000M /: Bus 03.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 480M |__ Port 1: Dev 3, If 0, Class=Vendor Specific Class, Driver=dvb_usb_it913x, 480M /: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/6p, 480M ...etc ``` The directory to look for is `/sys/bus/pci/drivers/xhci_hcd` ``` drwxr-xr-x 2 root root 0 5 21:48 ./ drwxr-xr-x 28 root root 0 1 00:21 ../ lrwxrwxrwx 1 root root 0 6 00:29 0000:06:00.0 -> ../../../../devices/pci0000:00/0000:00:1c.3/0000:06:00.0/ --w------- 1 root root 4096 5 22:33 bind lrwxrwxrwx 1 root root 0 5 22:32 module -> ../../../../module/xhci_hcd/ --w------- 1 root root 4096 5 22:32 new_id --w------- 1 root root 4096 5 22:32 remove_id --w------- 1 root root 4096 5 22:32 uevent --w------- 1 root root 4096 5 22:33 unbind ``` In my case I needed to unbind `"0000:06:00.0"`. ps. If you need to rebind the USB 2.0 driver, follow the above instructions but with `ehci-pci`, or look [here](http://davidjb.com/blog/2012/06/restartreset-usb-in-ubuntu-12-04-without-rebooting/) (deserves a credit).
206,614
After re-installing Lubuntu 12.04 system on my laptop an older problem re-emerged after a few days and installation of different programs: without apparent reason the external mouse and sometimes other usb connected devices (including hdd) stop working. The hdd shows it has tension as it has a light there, and the external mouse flashes for a second when plugged. [I have posted a different version of this problem before](https://askubuntu.com/q/178054/47206). I keep it for now as example of the two answers there. None of them works here. **Logging out-in does nothing, restart does.** The event seems entirely random, after reboot it will reappear after many days or weeks or, rarely, after a few hours. * <http://pastebin.com/0qR8bhhX> in `var/log/syslog` after new occurrence (**with only external wired mouse and keyboard**) What counts is at the end I guess: ``` Nov 24 14:06:55 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29953.822962] usb 3-1: USB disconnect, device number 3 Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069427] uhci_hcd 0000:00:1d.0: host controller process error, something bad happened! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069439] uhci_hcd 0000:00:1d.0: host controller halted, very bad! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069461] uhci_hcd 0000:00:1d.0: HC died; cleaning up Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069492] usb 2-2: USB disconnect, device number 2 ``` * I have noticed that **on most occasions only the external mouse and keyboard are affected, but not the external HDD. Or if it is, replugging it solves the problem**. * I have a dual boot with WinXP: **in Windows this never happens, so it is not a hardware issue** * **I have used Lubuntu Quantal 12.10 and the same problem happened there as well**. Upgrading to that would not be a solution * On certain occasion **only restarting 2 or even 3 times** solved it. --- **Using the same PC/hardware with Linux Mint 14 (Quantal) Xfce, the problem almost disappeared**(it happened *once* since then). I am not sure whether this 'solution' comes from using Xfce or Mint (I guess Mint 14 Nadia uses the same kernel as Lubuntu Quantal).
2012/10/26
[ "https://askubuntu.com/questions/206614", "https://askubuntu.com", "https://askubuntu.com/users/-1/" ]
Something similar to this was happening to me. [This blog post](http://billauer.co.il/blog/2013/02/usb-reset-ehci-uhci-linux/) provided a partial solution. This is what worked for me: ``` sudo -s cd /sys/bus/pci/drivers/xhci_hcd/ for file in ????:??:??.? ; do echo -n "$file" > unbind echo -n "$file" > bind done ``` As noted at that block post, different systems get hung up in different places, so if the above doesn't work, you might want to try replacing `/sys/bus/pci/drivers/xhci_hcd/` with `/sys/bus/pci/drivers/ehci_hcd/`, or `/sys/bus/pci/drivers/uhci_hcd/`, if one of those exists.
FWIW - If you're having USB problems on ubuntu due to conflicts or power issues, save yourself some trouble and get a powered USB expander - these are cheap devices that plug into your USB port and turn it into 5 or 10 or whatever you need to buy and have a separate power supply and go for about 30$ USD on amazon. I had tons of issues with my keyboard and/or mouse when I added a USB device and this made all of my problems go away. Cheers
206,614
After re-installing Lubuntu 12.04 system on my laptop an older problem re-emerged after a few days and installation of different programs: without apparent reason the external mouse and sometimes other usb connected devices (including hdd) stop working. The hdd shows it has tension as it has a light there, and the external mouse flashes for a second when plugged. [I have posted a different version of this problem before](https://askubuntu.com/q/178054/47206). I keep it for now as example of the two answers there. None of them works here. **Logging out-in does nothing, restart does.** The event seems entirely random, after reboot it will reappear after many days or weeks or, rarely, after a few hours. * <http://pastebin.com/0qR8bhhX> in `var/log/syslog` after new occurrence (**with only external wired mouse and keyboard**) What counts is at the end I guess: ``` Nov 24 14:06:55 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29953.822962] usb 3-1: USB disconnect, device number 3 Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069427] uhci_hcd 0000:00:1d.0: host controller process error, something bad happened! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069439] uhci_hcd 0000:00:1d.0: host controller halted, very bad! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069461] uhci_hcd 0000:00:1d.0: HC died; cleaning up Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069492] usb 2-2: USB disconnect, device number 2 ``` * I have noticed that **on most occasions only the external mouse and keyboard are affected, but not the external HDD. Or if it is, replugging it solves the problem**. * I have a dual boot with WinXP: **in Windows this never happens, so it is not a hardware issue** * **I have used Lubuntu Quantal 12.10 and the same problem happened there as well**. Upgrading to that would not be a solution * On certain occasion **only restarting 2 or even 3 times** solved it. --- **Using the same PC/hardware with Linux Mint 14 (Quantal) Xfce, the problem almost disappeared**(it happened *once* since then). I am not sure whether this 'solution' comes from using Xfce or Mint (I guess Mint 14 Nadia uses the same kernel as Lubuntu Quantal).
2012/10/26
[ "https://askubuntu.com/questions/206614", "https://askubuntu.com", "https://askubuntu.com/users/-1/" ]
kernel vs hardware issues ------------------------- If you have ruled out possible hardware issues such as voltage/current problems, failing USB ports/hubs then this is probably a kernel problem. If you feel comfortable with possible non-booting issues/black screen issues on boot, you could try installing the quantal kernel available in the 12.04 repositories. * [My computer boots to a black screen, what options do I have to fix it?](https://askubuntu.com/questions/162075/my-computer-boots-to-a-black-screen-what-options-do-i-have-to-fix-it) Remember - most blackscreen issues are due to installation of proprietary graphics drivers. You will have most luck removing these first before upgrading your kernel. To install the quantal kernel: ``` sudo apt-get install linux-generic-lts-quantal ``` Remember to do a full system backup to allow you to recover if the new kernel breaks more than it fixes. * [Comparison of backup tools](https://askubuntu.com/questions/2596/comparison-of-backup-tools)
Old post, and replies are not relevant to USB 3.0. So here's how to reset a 3.0 Bus that stopped serving data: ``` su - ``` and as root: ``` echo -n "0000:06:00.0" | tee /sys/bus/pci/drivers/xhci_hcd/unbind echo -n "0000:06:00.0" | tee /sys/bus/pci/drivers/xhci_hcd/bind ``` After this, USB should start to work correctly again, just like after a restart. --- Explanation ----------- In case you're using a different driver, this is how I found what to do, use it as a reference: A `lsusb -t` will output this - take a note of the `xhci_hcd` driver for the fast bus, it's the 3.0 driver name: ``` $ lsusb -t /: Bus 04.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 5000M /: Bus 03.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 480M |__ Port 1: Dev 3, If 0, Class=Vendor Specific Class, Driver=dvb_usb_it913x, 480M /: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/6p, 480M ...etc ``` The directory to look for is `/sys/bus/pci/drivers/xhci_hcd` ``` drwxr-xr-x 2 root root 0 5 21:48 ./ drwxr-xr-x 28 root root 0 1 00:21 ../ lrwxrwxrwx 1 root root 0 6 00:29 0000:06:00.0 -> ../../../../devices/pci0000:00/0000:00:1c.3/0000:06:00.0/ --w------- 1 root root 4096 5 22:33 bind lrwxrwxrwx 1 root root 0 5 22:32 module -> ../../../../module/xhci_hcd/ --w------- 1 root root 4096 5 22:32 new_id --w------- 1 root root 4096 5 22:32 remove_id --w------- 1 root root 4096 5 22:32 uevent --w------- 1 root root 4096 5 22:33 unbind ``` In my case I needed to unbind `"0000:06:00.0"`. ps. If you need to rebind the USB 2.0 driver, follow the above instructions but with `ehci-pci`, or look [here](http://davidjb.com/blog/2012/06/restartreset-usb-in-ubuntu-12-04-without-rebooting/) (deserves a credit).
206,614
After re-installing Lubuntu 12.04 system on my laptop an older problem re-emerged after a few days and installation of different programs: without apparent reason the external mouse and sometimes other usb connected devices (including hdd) stop working. The hdd shows it has tension as it has a light there, and the external mouse flashes for a second when plugged. [I have posted a different version of this problem before](https://askubuntu.com/q/178054/47206). I keep it for now as example of the two answers there. None of them works here. **Logging out-in does nothing, restart does.** The event seems entirely random, after reboot it will reappear after many days or weeks or, rarely, after a few hours. * <http://pastebin.com/0qR8bhhX> in `var/log/syslog` after new occurrence (**with only external wired mouse and keyboard**) What counts is at the end I guess: ``` Nov 24 14:06:55 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29953.822962] usb 3-1: USB disconnect, device number 3 Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069427] uhci_hcd 0000:00:1d.0: host controller process error, something bad happened! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069439] uhci_hcd 0000:00:1d.0: host controller halted, very bad! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069461] uhci_hcd 0000:00:1d.0: HC died; cleaning up Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069492] usb 2-2: USB disconnect, device number 2 ``` * I have noticed that **on most occasions only the external mouse and keyboard are affected, but not the external HDD. Or if it is, replugging it solves the problem**. * I have a dual boot with WinXP: **in Windows this never happens, so it is not a hardware issue** * **I have used Lubuntu Quantal 12.10 and the same problem happened there as well**. Upgrading to that would not be a solution * On certain occasion **only restarting 2 or even 3 times** solved it. --- **Using the same PC/hardware with Linux Mint 14 (Quantal) Xfce, the problem almost disappeared**(it happened *once* since then). I am not sure whether this 'solution' comes from using Xfce or Mint (I guess Mint 14 Nadia uses the same kernel as Lubuntu Quantal).
2012/10/26
[ "https://askubuntu.com/questions/206614", "https://askubuntu.com", "https://askubuntu.com/users/-1/" ]
kernel vs hardware issues ------------------------- If you have ruled out possible hardware issues such as voltage/current problems, failing USB ports/hubs then this is probably a kernel problem. If you feel comfortable with possible non-booting issues/black screen issues on boot, you could try installing the quantal kernel available in the 12.04 repositories. * [My computer boots to a black screen, what options do I have to fix it?](https://askubuntu.com/questions/162075/my-computer-boots-to-a-black-screen-what-options-do-i-have-to-fix-it) Remember - most blackscreen issues are due to installation of proprietary graphics drivers. You will have most luck removing these first before upgrading your kernel. To install the quantal kernel: ``` sudo apt-get install linux-generic-lts-quantal ``` Remember to do a full system backup to allow you to recover if the new kernel breaks more than it fixes. * [Comparison of backup tools](https://askubuntu.com/questions/2596/comparison-of-backup-tools)
FWIW - If you're having USB problems on ubuntu due to conflicts or power issues, save yourself some trouble and get a powered USB expander - these are cheap devices that plug into your USB port and turn it into 5 or 10 or whatever you need to buy and have a separate power supply and go for about 30$ USD on amazon. I had tons of issues with my keyboard and/or mouse when I added a USB device and this made all of my problems go away. Cheers
206,614
After re-installing Lubuntu 12.04 system on my laptop an older problem re-emerged after a few days and installation of different programs: without apparent reason the external mouse and sometimes other usb connected devices (including hdd) stop working. The hdd shows it has tension as it has a light there, and the external mouse flashes for a second when plugged. [I have posted a different version of this problem before](https://askubuntu.com/q/178054/47206). I keep it for now as example of the two answers there. None of them works here. **Logging out-in does nothing, restart does.** The event seems entirely random, after reboot it will reappear after many days or weeks or, rarely, after a few hours. * <http://pastebin.com/0qR8bhhX> in `var/log/syslog` after new occurrence (**with only external wired mouse and keyboard**) What counts is at the end I guess: ``` Nov 24 14:06:55 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29953.822962] usb 3-1: USB disconnect, device number 3 Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069427] uhci_hcd 0000:00:1d.0: host controller process error, something bad happened! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069439] uhci_hcd 0000:00:1d.0: host controller halted, very bad! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069461] uhci_hcd 0000:00:1d.0: HC died; cleaning up Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069492] usb 2-2: USB disconnect, device number 2 ``` * I have noticed that **on most occasions only the external mouse and keyboard are affected, but not the external HDD. Or if it is, replugging it solves the problem**. * I have a dual boot with WinXP: **in Windows this never happens, so it is not a hardware issue** * **I have used Lubuntu Quantal 12.10 and the same problem happened there as well**. Upgrading to that would not be a solution * On certain occasion **only restarting 2 or even 3 times** solved it. --- **Using the same PC/hardware with Linux Mint 14 (Quantal) Xfce, the problem almost disappeared**(it happened *once* since then). I am not sure whether this 'solution' comes from using Xfce or Mint (I guess Mint 14 Nadia uses the same kernel as Lubuntu Quantal).
2012/10/26
[ "https://askubuntu.com/questions/206614", "https://askubuntu.com", "https://askubuntu.com/users/-1/" ]
Something similar to this was happening to me. [This blog post](http://billauer.co.il/blog/2013/02/usb-reset-ehci-uhci-linux/) provided a partial solution. This is what worked for me: ``` sudo -s cd /sys/bus/pci/drivers/xhci_hcd/ for file in ????:??:??.? ; do echo -n "$file" > unbind echo -n "$file" > bind done ``` As noted at that block post, different systems get hung up in different places, so if the above doesn't work, you might want to try replacing `/sys/bus/pci/drivers/xhci_hcd/` with `/sys/bus/pci/drivers/ehci_hcd/`, or `/sys/bus/pci/drivers/uhci_hcd/`, if one of those exists.
A **fast solution** that works at least in my case (Linux Mint KDE, on a Lenovo Yoga 3 Pro laptop): With the laptop on, just **press the power button for about 30 seconds**, that is shutting down and still pressing for a while after this. I did it with the charger unplugged. After turning on the laptop, the USB ports work again.
206,614
After re-installing Lubuntu 12.04 system on my laptop an older problem re-emerged after a few days and installation of different programs: without apparent reason the external mouse and sometimes other usb connected devices (including hdd) stop working. The hdd shows it has tension as it has a light there, and the external mouse flashes for a second when plugged. [I have posted a different version of this problem before](https://askubuntu.com/q/178054/47206). I keep it for now as example of the two answers there. None of them works here. **Logging out-in does nothing, restart does.** The event seems entirely random, after reboot it will reappear after many days or weeks or, rarely, after a few hours. * <http://pastebin.com/0qR8bhhX> in `var/log/syslog` after new occurrence (**with only external wired mouse and keyboard**) What counts is at the end I guess: ``` Nov 24 14:06:55 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29953.822962] usb 3-1: USB disconnect, device number 3 Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069427] uhci_hcd 0000:00:1d.0: host controller process error, something bad happened! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069439] uhci_hcd 0000:00:1d.0: host controller halted, very bad! Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069461] uhci_hcd 0000:00:1d.0: HC died; cleaning up Nov 24 14:06:57 cprq-HP-Compaq-nx8220-PY518EA-ABB kernel: [29955.069492] usb 2-2: USB disconnect, device number 2 ``` * I have noticed that **on most occasions only the external mouse and keyboard are affected, but not the external HDD. Or if it is, replugging it solves the problem**. * I have a dual boot with WinXP: **in Windows this never happens, so it is not a hardware issue** * **I have used Lubuntu Quantal 12.10 and the same problem happened there as well**. Upgrading to that would not be a solution * On certain occasion **only restarting 2 or even 3 times** solved it. --- **Using the same PC/hardware with Linux Mint 14 (Quantal) Xfce, the problem almost disappeared**(it happened *once* since then). I am not sure whether this 'solution' comes from using Xfce or Mint (I guess Mint 14 Nadia uses the same kernel as Lubuntu Quantal).
2012/10/26
[ "https://askubuntu.com/questions/206614", "https://askubuntu.com", "https://askubuntu.com/users/-1/" ]
Old post, and replies are not relevant to USB 3.0. So here's how to reset a 3.0 Bus that stopped serving data: ``` su - ``` and as root: ``` echo -n "0000:06:00.0" | tee /sys/bus/pci/drivers/xhci_hcd/unbind echo -n "0000:06:00.0" | tee /sys/bus/pci/drivers/xhci_hcd/bind ``` After this, USB should start to work correctly again, just like after a restart. --- Explanation ----------- In case you're using a different driver, this is how I found what to do, use it as a reference: A `lsusb -t` will output this - take a note of the `xhci_hcd` driver for the fast bus, it's the 3.0 driver name: ``` $ lsusb -t /: Bus 04.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 5000M /: Bus 03.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/2p, 480M |__ Port 1: Dev 3, If 0, Class=Vendor Specific Class, Driver=dvb_usb_it913x, 480M /: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Class=Hub, Driver=hub/6p, 480M ...etc ``` The directory to look for is `/sys/bus/pci/drivers/xhci_hcd` ``` drwxr-xr-x 2 root root 0 5 21:48 ./ drwxr-xr-x 28 root root 0 1 00:21 ../ lrwxrwxrwx 1 root root 0 6 00:29 0000:06:00.0 -> ../../../../devices/pci0000:00/0000:00:1c.3/0000:06:00.0/ --w------- 1 root root 4096 5 22:33 bind lrwxrwxrwx 1 root root 0 5 22:32 module -> ../../../../module/xhci_hcd/ --w------- 1 root root 4096 5 22:32 new_id --w------- 1 root root 4096 5 22:32 remove_id --w------- 1 root root 4096 5 22:32 uevent --w------- 1 root root 4096 5 22:33 unbind ``` In my case I needed to unbind `"0000:06:00.0"`. ps. If you need to rebind the USB 2.0 driver, follow the above instructions but with `ehci-pci`, or look [here](http://davidjb.com/blog/2012/06/restartreset-usb-in-ubuntu-12-04-without-rebooting/) (deserves a credit).
FWIW - If you're having USB problems on ubuntu due to conflicts or power issues, save yourself some trouble and get a powered USB expander - these are cheap devices that plug into your USB port and turn it into 5 or 10 or whatever you need to buy and have a separate power supply and go for about 30$ USD on amazon. I had tons of issues with my keyboard and/or mouse when I added a USB device and this made all of my problems go away. Cheers
23,759,319
I found this tabbed content and so far set it up but for the life of me cannot figure out how to change the colour of the tab to a difference colour when you hover over it. I thought it would be the tabs label:hover but it doesn't seem to be. My code is here: ``` body, html { height: 100%; margin: 0; -webkit-font-smoothing: antialiased; font-weight: 100; background: #ffffff; text-align: center; font-family: helvetica; } .tabs input[type=radio] { position: absolute; top: -9999px; left: -9999px; } .tabs { width: 670px; float: none; list-style: none; position: relative; padding: 0; margin: 75px auto; } .tabs li{ float: left; } .tabs label { display: block; padding: 10px 20px; border-radius: 0px 0px 0 0; color: #ffffff; font-size: 18px; font-weight: normal; font-family: helvetica; background: #f3f3f3; cursor: pointer; position: relative; top: 3px; -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .tabs label:hover { background: #9eab05); top: 1px; } /* LABEL COLOURS */ [id^=tab]:checked + label { background: #e3ba12; color: white; top: 0; } [id^=tabfindme]:checked + label { background: #e3ba12; color: white; top: 0; } [id^=tabtwitter]:checked + label { background: #0085a1; color: white; top: 0; } [id^=tabtv]:checked + label { background: #6a2150; color: white; top: 0; } [id^=tabteach]:checked + label { background: #d10373; color: white; top: 0; } [id^=tab]:checked ~ [id^=tab-content] { display: block; } /* CONTENT COLOURS */ .findmecontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #e3ba12; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } .twittercontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #0085a1; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } .tvcontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #6a2150; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } .teachcontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #d10373; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } <ul class="tabs"> <li> <input type="radio" checked name="tabs" id="tabfindme"> <label for="tabfindme">FIND ME</label> <div id="tab-content1" class="findmecontent animated fadeIn"> You can find me at the following venues: <ul> <li>BBC Television Centre</li> <li>OutBurst Festival</li> </ul> </div> </li> <li> <input type="radio" name="tabs" id="tabtwitter"> <label for="tabtwitter">TWITTER</label> <div id="tab-content2" class="twittercontent animated fadeIn"> Twitterfeed </div> </li> <li> <input type="radio" name="tabs" id="tabtv"> <label for="tabtv">TELEVISION</label> <div id="tab-content3" class="tvcontent animated fadeIn"> Click the links to see me on TV <ul> <li>BBC Television Centre</li> <li>ITV</li> </ul> </div> </li> <li> <input type="radio" name="tabs" id="tabteach"> <label for="tabteach">HOW I TEACH</label> <div id="tab-content4" class="teachcontent animated fadeIn"> How I teach </div> </li> </li> ```
2014/05/20
[ "https://Stackoverflow.com/questions/23759319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3319013/" ]
``` .tabs label:hover { background: #9eab05; top: 1px; } ``` there is a ")" <-- remove it fiddle <http://jsfiddle.net/n5ura/> ``` body, html { height: 100%; margin: 0; -webkit-font-smoothing: antialiased; font-weight: 100; background: #ffffff; text-align: center; font-family: helvetica; } .tabs input[type=radio] { position: absolute; top: -9999px; left: -9999px; } .tabs { width: 670px; float: none; list-style: none; position: relative; padding: 0; margin: 75px auto; } .tabs li{ float: left; } .tabs label { display: block; padding: 10px 20px; border-radius: 0px 0px 0 0; color: #ffffff; font-size: 18px; font-weight: normal; font-family: helvetica; background: #f3f3f3; cursor: pointer; position: relative; top: 3px; -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .tabs label:hover { background: #9eab05; top: 1px; } /* LABEL COLOURS */ [id^=tab]:checked + label { background: #e3ba12; color: white; top: 0; } [id^=tabfindme]:checked + label { background: #e3ba12; color: white; top: 0; } [id^=tabtwitter]:checked + label { background: #0085a1; color: white; top: 0; } [id^=tabtv]:checked + label { background: #6a2150; color: white; top: 0; } [id^=tabteach]:checked + label { background: #d10373; color: white; top: 0; } [id^=tab]:checked ~ [id^=tab-content] { display: block; } /* CONTENT COLOURS */ .findmecontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #e3ba12; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } .twittercontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #0085a1; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } .tvcontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #6a2150; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } .teachcontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #d10373; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } ```
maybe change this ? ``` .tabs label:hover { background: #9eab05; top: 1px; } ``` into : ``` .tabs label:hover { background: #9eab05; color:#000; top: 1px; } ``` if you want to change the color of the text. Or else change background into something else.
23,759,319
I found this tabbed content and so far set it up but for the life of me cannot figure out how to change the colour of the tab to a difference colour when you hover over it. I thought it would be the tabs label:hover but it doesn't seem to be. My code is here: ``` body, html { height: 100%; margin: 0; -webkit-font-smoothing: antialiased; font-weight: 100; background: #ffffff; text-align: center; font-family: helvetica; } .tabs input[type=radio] { position: absolute; top: -9999px; left: -9999px; } .tabs { width: 670px; float: none; list-style: none; position: relative; padding: 0; margin: 75px auto; } .tabs li{ float: left; } .tabs label { display: block; padding: 10px 20px; border-radius: 0px 0px 0 0; color: #ffffff; font-size: 18px; font-weight: normal; font-family: helvetica; background: #f3f3f3; cursor: pointer; position: relative; top: 3px; -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .tabs label:hover { background: #9eab05); top: 1px; } /* LABEL COLOURS */ [id^=tab]:checked + label { background: #e3ba12; color: white; top: 0; } [id^=tabfindme]:checked + label { background: #e3ba12; color: white; top: 0; } [id^=tabtwitter]:checked + label { background: #0085a1; color: white; top: 0; } [id^=tabtv]:checked + label { background: #6a2150; color: white; top: 0; } [id^=tabteach]:checked + label { background: #d10373; color: white; top: 0; } [id^=tab]:checked ~ [id^=tab-content] { display: block; } /* CONTENT COLOURS */ .findmecontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #e3ba12; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } .twittercontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #0085a1; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } .tvcontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #6a2150; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } .teachcontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #d10373; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } <ul class="tabs"> <li> <input type="radio" checked name="tabs" id="tabfindme"> <label for="tabfindme">FIND ME</label> <div id="tab-content1" class="findmecontent animated fadeIn"> You can find me at the following venues: <ul> <li>BBC Television Centre</li> <li>OutBurst Festival</li> </ul> </div> </li> <li> <input type="radio" name="tabs" id="tabtwitter"> <label for="tabtwitter">TWITTER</label> <div id="tab-content2" class="twittercontent animated fadeIn"> Twitterfeed </div> </li> <li> <input type="radio" name="tabs" id="tabtv"> <label for="tabtv">TELEVISION</label> <div id="tab-content3" class="tvcontent animated fadeIn"> Click the links to see me on TV <ul> <li>BBC Television Centre</li> <li>ITV</li> </ul> </div> </li> <li> <input type="radio" name="tabs" id="tabteach"> <label for="tabteach">HOW I TEACH</label> <div id="tab-content4" class="teachcontent animated fadeIn"> How I teach </div> </li> </li> ```
2014/05/20
[ "https://Stackoverflow.com/questions/23759319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3319013/" ]
``` .tabs label:hover { background: #9eab05; top: 1px; } ``` there is a ")" <-- remove it fiddle <http://jsfiddle.net/n5ura/> ``` body, html { height: 100%; margin: 0; -webkit-font-smoothing: antialiased; font-weight: 100; background: #ffffff; text-align: center; font-family: helvetica; } .tabs input[type=radio] { position: absolute; top: -9999px; left: -9999px; } .tabs { width: 670px; float: none; list-style: none; position: relative; padding: 0; margin: 75px auto; } .tabs li{ float: left; } .tabs label { display: block; padding: 10px 20px; border-radius: 0px 0px 0 0; color: #ffffff; font-size: 18px; font-weight: normal; font-family: helvetica; background: #f3f3f3; cursor: pointer; position: relative; top: 3px; -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .tabs label:hover { background: #9eab05; top: 1px; } /* LABEL COLOURS */ [id^=tab]:checked + label { background: #e3ba12; color: white; top: 0; } [id^=tabfindme]:checked + label { background: #e3ba12; color: white; top: 0; } [id^=tabtwitter]:checked + label { background: #0085a1; color: white; top: 0; } [id^=tabtv]:checked + label { background: #6a2150; color: white; top: 0; } [id^=tabteach]:checked + label { background: #d10373; color: white; top: 0; } [id^=tab]:checked ~ [id^=tab-content] { display: block; } /* CONTENT COLOURS */ .findmecontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #e3ba12; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } .twittercontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #0085a1; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } .tvcontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #6a2150; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } .teachcontent{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 12px; line-height: 140%; padding-top: 0px; background: #d10373; padding: 15px; color: white; position: absolute; top: 40px; left: 0; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } ```
Use hover instead checked, example on the find me button ``` [id^=tabfindme]:hover + label { background: red color: white; top: 0; } ```
44,236,756
How do I scroll through a modal window that is created using Bootstrap's modal class? Generally we use the JavascriptExecutor and use the window.scroll/scrollBy method. But when I tried the same when a modal is popped up with long content, the scroll is happening in the actual webpage which is not focused. How do I scroll through content in a modal popup that has long content? Example - Modal popup here: <https://v4-alpha.getbootstrap.com/components/modal/#scrolling-long-content>
2017/05/29
[ "https://Stackoverflow.com/questions/44236756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2110723/" ]
This script captures the `-i` command, while still allowing `unittest.main` to do its own commandline parsing: ``` import unittest class Testclass(unittest.TestCase): @classmethod def setUpClass(cls): print "Hello Class" def test_addnum(self): print "Execute the test case" #parser = parse_args(['-i']) print 'simple_value =', args.inputfile import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-i', help='input file', dest='inputfile') ns, args = parser.parse_known_args(namespace=unittest) #args = parser.parse_args() return ns, sys.argv[:1] + args if __name__ == '__main__': import sys args, argv = parse_args() # run this first print(args, argv) sys.argv[:] = argv # create cleans argv for main() unittest.main() ``` produces: ``` 1113:~/mypy$ python stack44236745.py -i testname -v (<module 'unittest' from '/usr/lib/python2.7/unittest/__init__.pyc'>, ['stack44236745.py', '-v']) Hello Class test_addnum (__main__.Testclass) ... Execute the test case simple_value = testname ok ---------------------------------------------------------------------- Ran 1 test in 0.000s OK ``` It looks rather kludgy, but does seem to work. The idea is to run your own parser first, capturing the `-i` input, and putting the rest back into `sys.argv`. Your definition of `parse_args` suggests that you are already trying to do that.
Your code is setting up your argument parser using ``` argparse.ArgumentParser() parser.add_argument('-i', help='input file', dest='inputfile') ``` in a method of your test class. But I see no indication that the code is actually calling the method. So at the time you start the program, the parser does not yet exist, because the method `TestClass.parse_args()` hasn't been called yet. Move the creation of the parser and specification of its parameters out of the class so that the code calls it when the program starts.
44,236,756
How do I scroll through a modal window that is created using Bootstrap's modal class? Generally we use the JavascriptExecutor and use the window.scroll/scrollBy method. But when I tried the same when a modal is popped up with long content, the scroll is happening in the actual webpage which is not focused. How do I scroll through content in a modal popup that has long content? Example - Modal popup here: <https://v4-alpha.getbootstrap.com/components/modal/#scrolling-long-content>
2017/05/29
[ "https://Stackoverflow.com/questions/44236756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2110723/" ]
Thanks hpaulj, your solution really helped me and I found one more solution for this problem. Hope it helps someone else facing the same issue. ``` import unittest import argparse import sys class Testclass(unittest.TestCase): @classmethod def setUpClass(cls): print "Hello Class" def test_addnum(self): print "Execute the test case" #parser = parse_args(['-i']) print 'simple_value =', args.inputfile if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-i', help='input file', dest='inputfile') parser.add_argument('unittest_args', nargs='*') args = parser.parse_args() sys.argv[1:] = args.unittest_args unittest.main() ``` Now executing the script with option `-i` as `python testing.py -i somefile.txt` gives result as ``` Hello Class Execute the test case simple_value = somefile.txt . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK ```
Your code is setting up your argument parser using ``` argparse.ArgumentParser() parser.add_argument('-i', help='input file', dest='inputfile') ``` in a method of your test class. But I see no indication that the code is actually calling the method. So at the time you start the program, the parser does not yet exist, because the method `TestClass.parse_args()` hasn't been called yet. Move the creation of the parser and specification of its parameters out of the class so that the code calls it when the program starts.
44,236,756
How do I scroll through a modal window that is created using Bootstrap's modal class? Generally we use the JavascriptExecutor and use the window.scroll/scrollBy method. But when I tried the same when a modal is popped up with long content, the scroll is happening in the actual webpage which is not focused. How do I scroll through content in a modal popup that has long content? Example - Modal popup here: <https://v4-alpha.getbootstrap.com/components/modal/#scrolling-long-content>
2017/05/29
[ "https://Stackoverflow.com/questions/44236756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2110723/" ]
This script captures the `-i` command, while still allowing `unittest.main` to do its own commandline parsing: ``` import unittest class Testclass(unittest.TestCase): @classmethod def setUpClass(cls): print "Hello Class" def test_addnum(self): print "Execute the test case" #parser = parse_args(['-i']) print 'simple_value =', args.inputfile import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-i', help='input file', dest='inputfile') ns, args = parser.parse_known_args(namespace=unittest) #args = parser.parse_args() return ns, sys.argv[:1] + args if __name__ == '__main__': import sys args, argv = parse_args() # run this first print(args, argv) sys.argv[:] = argv # create cleans argv for main() unittest.main() ``` produces: ``` 1113:~/mypy$ python stack44236745.py -i testname -v (<module 'unittest' from '/usr/lib/python2.7/unittest/__init__.pyc'>, ['stack44236745.py', '-v']) Hello Class test_addnum (__main__.Testclass) ... Execute the test case simple_value = testname ok ---------------------------------------------------------------------- Ran 1 test in 0.000s OK ``` It looks rather kludgy, but does seem to work. The idea is to run your own parser first, capturing the `-i` input, and putting the rest back into `sys.argv`. Your definition of `parse_args` suggests that you are already trying to do that.
You are running `unittest.main()` as the main program. So it's complaining rightfully that it does not know about the option you wrote: ``` "option -i not recognized" ``` If you want to create your own test suite launcher you should look into [TextTestRunner](https://docs.python.org/dev/library/unittest.html#unittest.TextTestRunner)
44,236,756
How do I scroll through a modal window that is created using Bootstrap's modal class? Generally we use the JavascriptExecutor and use the window.scroll/scrollBy method. But when I tried the same when a modal is popped up with long content, the scroll is happening in the actual webpage which is not focused. How do I scroll through content in a modal popup that has long content? Example - Modal popup here: <https://v4-alpha.getbootstrap.com/components/modal/#scrolling-long-content>
2017/05/29
[ "https://Stackoverflow.com/questions/44236756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2110723/" ]
Thanks hpaulj, your solution really helped me and I found one more solution for this problem. Hope it helps someone else facing the same issue. ``` import unittest import argparse import sys class Testclass(unittest.TestCase): @classmethod def setUpClass(cls): print "Hello Class" def test_addnum(self): print "Execute the test case" #parser = parse_args(['-i']) print 'simple_value =', args.inputfile if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-i', help='input file', dest='inputfile') parser.add_argument('unittest_args', nargs='*') args = parser.parse_args() sys.argv[1:] = args.unittest_args unittest.main() ``` Now executing the script with option `-i` as `python testing.py -i somefile.txt` gives result as ``` Hello Class Execute the test case simple_value = somefile.txt . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK ```
You are running `unittest.main()` as the main program. So it's complaining rightfully that it does not know about the option you wrote: ``` "option -i not recognized" ``` If you want to create your own test suite launcher you should look into [TextTestRunner](https://docs.python.org/dev/library/unittest.html#unittest.TextTestRunner)
44,236,756
How do I scroll through a modal window that is created using Bootstrap's modal class? Generally we use the JavascriptExecutor and use the window.scroll/scrollBy method. But when I tried the same when a modal is popped up with long content, the scroll is happening in the actual webpage which is not focused. How do I scroll through content in a modal popup that has long content? Example - Modal popup here: <https://v4-alpha.getbootstrap.com/components/modal/#scrolling-long-content>
2017/05/29
[ "https://Stackoverflow.com/questions/44236756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2110723/" ]
This script captures the `-i` command, while still allowing `unittest.main` to do its own commandline parsing: ``` import unittest class Testclass(unittest.TestCase): @classmethod def setUpClass(cls): print "Hello Class" def test_addnum(self): print "Execute the test case" #parser = parse_args(['-i']) print 'simple_value =', args.inputfile import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-i', help='input file', dest='inputfile') ns, args = parser.parse_known_args(namespace=unittest) #args = parser.parse_args() return ns, sys.argv[:1] + args if __name__ == '__main__': import sys args, argv = parse_args() # run this first print(args, argv) sys.argv[:] = argv # create cleans argv for main() unittest.main() ``` produces: ``` 1113:~/mypy$ python stack44236745.py -i testname -v (<module 'unittest' from '/usr/lib/python2.7/unittest/__init__.pyc'>, ['stack44236745.py', '-v']) Hello Class test_addnum (__main__.Testclass) ... Execute the test case simple_value = testname ok ---------------------------------------------------------------------- Ran 1 test in 0.000s OK ``` It looks rather kludgy, but does seem to work. The idea is to run your own parser first, capturing the `-i` input, and putting the rest back into `sys.argv`. Your definition of `parse_args` suggests that you are already trying to do that.
Thanks hpaulj, your solution really helped me and I found one more solution for this problem. Hope it helps someone else facing the same issue. ``` import unittest import argparse import sys class Testclass(unittest.TestCase): @classmethod def setUpClass(cls): print "Hello Class" def test_addnum(self): print "Execute the test case" #parser = parse_args(['-i']) print 'simple_value =', args.inputfile if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-i', help='input file', dest='inputfile') parser.add_argument('unittest_args', nargs='*') args = parser.parse_args() sys.argv[1:] = args.unittest_args unittest.main() ``` Now executing the script with option `-i` as `python testing.py -i somefile.txt` gives result as ``` Hello Class Execute the test case simple_value = somefile.txt . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK ```
17,069,514
We have two tables. ``` 1. information title body name title1 body1 author1 title2 body2 author1 title1 body1 author2 title1 body1 author3 2. interactions name favorited user_favorited_by author1 yes user1 author2 yes user1 author1 yes user2 author1 no user3 ``` The question is: who is for each user the favourite author or authors? The query should give us the following answer based on the example: ``` user1 author1 user1 author2 user2 author1 ``` Any help appreciated.
2013/06/12
[ "https://Stackoverflow.com/questions/17069514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/235532/" ]
Here is a JOIN that works: ``` SELECT DISTINCT user_favorited_by, a.name FROM information a JOIN interactions b ON a.name = b.name WHERE favorited = 'yes' ``` Since you only have 'name' to join on, you need DISTINCT, or you could GROUP BY selected fields to remove duplicate lines from your output. And here is a demo: [SQL Fiddle](http://sqlfiddle.com/#!2/ca2be/3/0)
May I suggest: ``` select user_favorited_by, author from information a inner join interaction b on a.name = b.name where b.favorited = 'yes' ```
17,069,514
We have two tables. ``` 1. information title body name title1 body1 author1 title2 body2 author1 title1 body1 author2 title1 body1 author3 2. interactions name favorited user_favorited_by author1 yes user1 author2 yes user1 author1 yes user2 author1 no user3 ``` The question is: who is for each user the favourite author or authors? The query should give us the following answer based on the example: ``` user1 author1 user1 author2 user2 author1 ``` Any help appreciated.
2013/06/12
[ "https://Stackoverflow.com/questions/17069514", "https://Stackoverflow.com", "https://Stackoverflow.com/users/235532/" ]
Here is a JOIN that works: ``` SELECT DISTINCT user_favorited_by, a.name FROM information a JOIN interactions b ON a.name = b.name WHERE favorited = 'yes' ``` Since you only have 'name' to join on, you need DISTINCT, or you could GROUP BY selected fields to remove duplicate lines from your output. And here is a demo: [SQL Fiddle](http://sqlfiddle.com/#!2/ca2be/3/0)
I think the following should work ``` SELECT DISTINCT user_favorited_by, a.name FROM information a, interactions b WHERE a.name = b.name AND favorited = 'yes' ```
64,195,427
The following code compiles: ``` val collection = listOf("a", "b") val filter = { x: String -> x.isEmpty() } collection.filter(filter) ``` Is it possible to define the filter using a function interface? For example the following code doesn't compile: ``` fun interface MyFilter { fun execute(string: String): Boolean } ``` and ``` val filter = MyFilter { x -> x.isEmpty() } ``` gives a compilation error ``` Type mismatch. Required: (TypeVariable(T)) → Boolean Found: MyFilter ```
2020/10/04
[ "https://Stackoverflow.com/questions/64195427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4680812/" ]
You can inherit `MyFilter` from `(String) -> Boolean` ``` fun interface MyFilter : (String) -> Boolean fun main() { val collection = listOf("a", "b") val filter = MyFilter { x -> x.isEmpty() } val newCollection = collection.filter(filter) } ``` With your custom method: ``` fun interface MyFilter : (String) -> Boolean { override operator fun invoke(p1: String): Boolean = execute(p1) fun execute(param: String): Boolean } ``` But it works only with `jvmTarget = 1.8 (or higher)` and `-Xjvm-default=all`
You can use **member reference** operator `::` to pass the function of interface by reference: ``` val collection = listOf("a", "b") val filter = MyFilter { x -> x.isEmpty() } collection.filter(filter::execute) fun interface MyFilter { fun execute(string: String): Boolean } ```
32,116,842
I have subroutine in my module which checks (regular) user password age using regex search on `shadow` file: **Module.pm** ``` my $pwdsetts_dump = "tmp/shadow_dump.txt"; system("cat /etc/shadow > $pwdsetts_dump"); open (my $fh1, "<", $pwdsetts_dump) or die "Could not open file '$pwdsetts_dump': $!"; sub CollectPWDSettings { my @pwdsettings; while (my $array = <$fh1>) { if ($array =~ /^(\S+)[:][$]\S+[:](1[0-9]{4})/) { my $pwdchange = "$2"; if ("$2" eq "0") { $pwdchange = "Next login"; } my %hash = ( "Username" => $1, "Last change" => $pwdchange ); push (@pwdsettings, \%hash); } } my $current_date = int(time()/86400); # epoch my $ndate = shift @_; # n-days my $search_date = int($current_date - $ndate); my @sorted = grep{$_->{'Last change'} > $search_date} @pwdsettings; return \@sorted; } ``` Script is divided in 2 steps: 1. load all password settings 2. search for password which is older than n-days In my main script I use following script: ``` my ($user_changed_pwd); if (grep{$_->{'Username'} eq $users_to_check} @{Module::CollectPWDSettings("100")}) { $user_changed_pwd = "no"; } else { $user_changed_pwd = "yes"; } ``` Problem occurs in first step, AoH never gets populated. I'm also pretty sure that this subroutine always worked for me and `strict` and `warnings` never complained about it, nut now, for some reason it refuses to work.
2015/08/20
[ "https://Stackoverflow.com/questions/32116842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've just run your regex against my `/etc/shadow` and got no matches. If I drop the leading `1` I get a few hits. E.g.: ``` $array =~ /^(\S+)[:][$]\S+[:]([0-9]{4})/ ``` But personally - I would suggest not trying to regex, and instead rely on the fact that [`/etc/shadow`](http://linux.die.net/man/5/shadow) is defined as delimited by `:`. ``` my @fields = split ( /:/, $array ); ``` $1 contains a bunch of stuff, and I suspect what you *actually* want is the username - but because `\S+` is greedy, you might be accidentally ending up with encrypted passwords. Which will be `$fields[0]`. And then the 'last change' field - from [`man shadow`](http://linux.die.net/man/5/shadow) is `$fields[2]`.
I think your regex pattern is the main problem. Don't forget that `\S` matches any non-space character including colons `:`, and `\S+` will try to match as much as possible so it will happily skip over multiple fields of the file I think using [`split`](http://perldoc.perl.org/functions/split.html) to separate each record into colon-delimited fields is a better approach. I also think that, instead of the array of two-element hashes `@pwdsettings` it would be better to store the data as a hash relating usernames to their password history Here's how I would write this. It prints a list of all usernames whose password history is greater than 90 days ``` use strict; use warnings; use Time::Seconds 'ONE_DAY'; my @shadow = do { open my $fh, '<', '/etc/shadow' or die qq{Unable to open "/etc/shadow" for input: $!}; <$fh>; }; print "$_\n" for @{ collect_pwd_settings(90) }; sub collect_pwd_settings { my ($ndate) = @_; my %pwdsettings; for ( @shadow ) { my ($user, $pwdchange) = (split /:/)[0,2]; $pwdsettings{$user} = $pwdchange; } my $current_date = time / ONE_DAY; my @filtered = grep { $current_date - $pwdsettings{$_} > $ndate } keys %pwdsettings; return \@filtered; } ```
67,366,685
I am running an Angular Application I am getting these popup in vs code whenever I am opening it. However, the ng serve command is working fine and it's serving(running) the app successfully. But I am getting this error in console. [![console error](https://i.stack.imgur.com/mX73o.png)](https://i.stack.imgur.com/mX73o.png) [![this popup coming in vs code](https://i.stack.imgur.com/uJkvM.png)](https://i.stack.imgur.com/uJkvM.png) [![ng serve is serving the app](https://i.stack.imgur.com/I1exq.png)](https://i.stack.imgur.com/I1exq.png)
2021/05/03
[ "https://Stackoverflow.com/questions/67366685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13975105/" ]
Angular Language Service Extension has one bug which is reported to their git repository. My solution will work for Angular Projects which is running < Version 9.0 To resolve this issue you have two ways. Solution 1: Downgrade extension version 1. Downgrade [https://marketplace.visualstudio.com/items?itemName=Angular.ng-template](https://i.stack.imgur.com/wyMlG.png) to 11.2.14 2. Remove Node Module 3. Run npm install 4. Run npm start or ng serve Solution 2: (For Version 12) 1. Open Vs Code 2. Go To Files ==> Preference ==> Setting 3. Under Extension Select Use Legacy View Engine Checkbox. 4. Run npm start (If you're facing any issue then kindly close VS Code and Remove node\_modules folder and Run npm install [![enter image description here](https://i.stack.imgur.com/wyMlG.png)](https://i.stack.imgur.com/wyMlG.png)
it might be some version inconsistency problem. It was in my case. Had same symptoms: I opened a folder in Visual Studio Code and after few secons I got the same message, but also VSC did not recognize any of angular tags. On the other hand, it did run without problems on my other computer... I reinstalled VS, angular, nodejs, nothing helped, then the last thing I did is upate all packages in package.json to latest, fixed some code (because of changes in new packages) and now it works! br, Marjan
67,366,685
I am running an Angular Application I am getting these popup in vs code whenever I am opening it. However, the ng serve command is working fine and it's serving(running) the app successfully. But I am getting this error in console. [![console error](https://i.stack.imgur.com/mX73o.png)](https://i.stack.imgur.com/mX73o.png) [![this popup coming in vs code](https://i.stack.imgur.com/uJkvM.png)](https://i.stack.imgur.com/uJkvM.png) [![ng serve is serving the app](https://i.stack.imgur.com/I1exq.png)](https://i.stack.imgur.com/I1exq.png)
2021/05/03
[ "https://Stackoverflow.com/questions/67366685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13975105/" ]
Angular Language Service Extension has one bug which is reported to their git repository. My solution will work for Angular Projects which is running < Version 9.0 To resolve this issue you have two ways. Solution 1: Downgrade extension version 1. Downgrade [https://marketplace.visualstudio.com/items?itemName=Angular.ng-template](https://i.stack.imgur.com/wyMlG.png) to 11.2.14 2. Remove Node Module 3. Run npm install 4. Run npm start or ng serve Solution 2: (For Version 12) 1. Open Vs Code 2. Go To Files ==> Preference ==> Setting 3. Under Extension Select Use Legacy View Engine Checkbox. 4. Run npm start (If you're facing any issue then kindly close VS Code and Remove node\_modules folder and Run npm install [![enter image description here](https://i.stack.imgur.com/wyMlG.png)](https://i.stack.imgur.com/wyMlG.png)
reinstall vscode extension Angular Language [email protected] resolve my problem.