qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
51,286 | I put a bounty on a question ([here](https://stackoverflow.com/questions/2625524/crash-when-linking-swc-with-alchemy)) which has gotten no answers. The bounty has since expired. I sort of expected to get my reputation back since nobody 'won' it. Is this really how the system works? | 2010/05/26 | [
"https://meta.stackexchange.com/questions/51286",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/137929/"
] | Jon Skeet.
See [this SE Data Explorer query](https://data.stackexchange.com/stackoverflow/query/946/rising-stars-top-50-users-ordered-on-rep-per-day) (not by me). | I imagine that user would be Jon Skeet, the answer to life, the universe, and everything.
(hope I got the quote right) |
51,286 | I put a bounty on a question ([here](https://stackoverflow.com/questions/2625524/crash-when-linking-swc-with-alchemy)) which has gotten no answers. The bounty has since expired. I sort of expected to get my reputation back since nobody 'won' it. Is this really how the system works? | 2010/05/26 | [
"https://meta.stackexchange.com/questions/51286",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/137929/"
] | Jon Skeet.
See [this SE Data Explorer query](https://data.stackexchange.com/stackoverflow/query/946/rising-stars-top-50-users-ordered-on-rep-per-day) (not by me). | I would say Jon Skeet because a while ago he made a Twitter update saying "Wow today is the first day in months I didn't hit the reputation cap on Stack Overflow". |
9,276,261 | I want to append an html element to a div and have jquery return me the wrapped set that contains the element I just appended and not the wrapped set containing the div
So my html:-
```
...
<div id="somediv">Some other elements...</div>
...
```
javascript:-
```
var jqueryObj = $('#somediv').append('<p>Hello, World!</p>');
alert(jqueryObj.html());
```
I'd like this to alert me with `'Hello, world'` not `'Some other elements...<p>Hello, World!</p>'` | 2012/02/14 | [
"https://Stackoverflow.com/questions/9276261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196970/"
] | Use [`.appendTo()`](http://api.jquery.com/appendTo/) instead of [`.append()`](http://api.jquery.com/append/).
```
var jqueryObj = $('<p>Hello, World!</p>').appendTo('#somediv');
alert(jqueryObj.html()); // '<p>Hello, World!</p>'
``` | ```
var jqueryObj = $('#somediv').append('<p>Hello, World!</p>');
alert(jqueryObj.find("p").html());
``` |
9,276,261 | I want to append an html element to a div and have jquery return me the wrapped set that contains the element I just appended and not the wrapped set containing the div
So my html:-
```
...
<div id="somediv">Some other elements...</div>
...
```
javascript:-
```
var jqueryObj = $('#somediv').append('<p>Hello, World!</p>');
alert(jqueryObj.html());
```
I'd like this to alert me with `'Hello, world'` not `'Some other elements...<p>Hello, World!</p>'` | 2012/02/14 | [
"https://Stackoverflow.com/questions/9276261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196970/"
] | Use [`.appendTo()`](http://api.jquery.com/appendTo/) instead of [`.append()`](http://api.jquery.com/append/).
```
var jqueryObj = $('<p>Hello, World!</p>').appendTo('#somediv');
alert(jqueryObj.html()); // '<p>Hello, World!</p>'
``` | Switch them around, and use the [`.appendTo()`](http://api.jquery.com/appendTo/) function. Like so:
```
var jqueryObj = $('<p>Hello, World!</p>').appendTo('#somediv');
```
[**Working DEMO**](http://jsfiddle.net/9wse7/) |
9,276,261 | I want to append an html element to a div and have jquery return me the wrapped set that contains the element I just appended and not the wrapped set containing the div
So my html:-
```
...
<div id="somediv">Some other elements...</div>
...
```
javascript:-
```
var jqueryObj = $('#somediv').append('<p>Hello, World!</p>');
alert(jqueryObj.html());
```
I'd like this to alert me with `'Hello, world'` not `'Some other elements...<p>Hello, World!</p>'` | 2012/02/14 | [
"https://Stackoverflow.com/questions/9276261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196970/"
] | Use [`.appendTo()`](http://api.jquery.com/appendTo/) instead of [`.append()`](http://api.jquery.com/append/).
```
var jqueryObj = $('<p>Hello, World!</p>').appendTo('#somediv');
alert(jqueryObj.html()); // '<p>Hello, World!</p>'
``` | Try this:
```
var jqueryObj= $('<p>Hello, world!</p>');
$('#somediv').append(jqueryObj);
alert(jqueryObj.html());
```
What you want is the variable to actually hold the newly created object, not the div into which you added it. |
9,276,261 | I want to append an html element to a div and have jquery return me the wrapped set that contains the element I just appended and not the wrapped set containing the div
So my html:-
```
...
<div id="somediv">Some other elements...</div>
...
```
javascript:-
```
var jqueryObj = $('#somediv').append('<p>Hello, World!</p>');
alert(jqueryObj.html());
```
I'd like this to alert me with `'Hello, world'` not `'Some other elements...<p>Hello, World!</p>'` | 2012/02/14 | [
"https://Stackoverflow.com/questions/9276261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196970/"
] | Switch them around, and use the [`.appendTo()`](http://api.jquery.com/appendTo/) function. Like so:
```
var jqueryObj = $('<p>Hello, World!</p>').appendTo('#somediv');
```
[**Working DEMO**](http://jsfiddle.net/9wse7/) | ```
var jqueryObj = $('#somediv').append('<p>Hello, World!</p>');
alert(jqueryObj.find("p").html());
``` |
9,276,261 | I want to append an html element to a div and have jquery return me the wrapped set that contains the element I just appended and not the wrapped set containing the div
So my html:-
```
...
<div id="somediv">Some other elements...</div>
...
```
javascript:-
```
var jqueryObj = $('#somediv').append('<p>Hello, World!</p>');
alert(jqueryObj.html());
```
I'd like this to alert me with `'Hello, world'` not `'Some other elements...<p>Hello, World!</p>'` | 2012/02/14 | [
"https://Stackoverflow.com/questions/9276261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196970/"
] | Switch them around, and use the [`.appendTo()`](http://api.jquery.com/appendTo/) function. Like so:
```
var jqueryObj = $('<p>Hello, World!</p>').appendTo('#somediv');
```
[**Working DEMO**](http://jsfiddle.net/9wse7/) | Try this:
```
var jqueryObj= $('<p>Hello, world!</p>');
$('#somediv').append(jqueryObj);
alert(jqueryObj.html());
```
What you want is the variable to actually hold the newly created object, not the div into which you added it. |
115,930 | Since the update I've attempted to play the new mode but am not doing so well. I have an assassin specialized mainly into the Cunning tree and partially into the Bloodshed side. With my current build I can't even get passed the W4R-DEN with leads me to believe co-op is almost a necessary requirement to beat this mode.
Am I right or do I just need better equipment to do this? Maybe other classes would also be better suited to beating this solo as well? | 2013/05/02 | [
"https://gaming.stackexchange.com/questions/115930",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/37612/"
] | The most standard way of playing melee Zer0 is to go all the way down the `Bloodshed` tree for `Many Must Fall`. Definitely skip `Grim` because it ruins how you will be playing and `Resurgence` is useless with the weapons you will be using. See this [post](http://forums.gearboxsoftware.com/showthread.php?t=254652) for the complete melee formula (in short melee damage is based purely on your level and other modifiers, weapon damage is irrelevant unless it specifically says it does extra melee damage) - you can use this to min/max the skills. `Many Must Fall` is better than `Death Bl0ss0m` typically unless you are doing raid bosses so switch if you are farming raid bosses.
Your standard setup includes:
* [Rubi](http://borderlands.wikia.com/wiki/Rubi) (preferably with `Slag` and `Evisceration`)
+ An alternative is to use [Law](http://borderlands.wikia.com/wiki/Law_%28Borderlands_2%29) with [Order](http://borderlands.wikia.com/wiki/Order) but I believe you will do less damage overall
+ This is how you are going to recover HP - ~12% damage you do with `Rubi` is gained as HP, you will often go from 1% to 100% HP in one hit
+ Any damage done while holding `Rubi`, not just damage done with Rubi is recovered as HP
* [Love Thumper](http://borderlands.wikia.com/wiki/Love_Thumper) (preferably with one of the immunities)
+ This is the better alternative to Order for the damage that it produces which means better HP recovery
+ The reason `Love Thumper` is better than `Order` is because you don't need to manage your shield and the higher Roid damage
+ Another alternative is [Hide of Terramorphous](http://borderlands.wikia.com/wiki/Hide_of_Terramorphous) but again you will need to manage your sheilds
* [Rapier](http://borderlands.wikia.com/wiki/Rapier) (also preferably with Slag)
+ the 200% modifier is huge and if you look around you can find videos of Zer0 doing max damage in one melee swing
+ Swap and use this as necessary - DO NOT underestimate this weapon, this is a huge boost to your melee damage compared to `Rubi`
+ This requires [Captain Scarlett and Her Pirate's Booty](http://borderlands.wikia.com/wiki/Captain_Scarlett_and_Her_Pirate%27s_Booty) DLC which is pretty good overall
* [Proficiency Relic](http://borderlands.wikia.com/wiki/Proficiency_Relic) is the most common relic used
* Class mod is up to your preference
* [Storm Front](http://borderlands.wikia.com/wiki/Storm_Front)
+ Often used because it has consistent damage so paired with Rubi it has good HP recovery and the explosion can break your shield while the Tesla won't damage you
* I usually keep a Rocket Launcher, Sniper Rifle, or [Dahlminator](http://borderlands.wikia.com/wiki/Dahlminator) in the remaining slots for FFYL, long distance, or flying enemies
Remember Roid damage is a big contributor to your overall damage so your shield should usually be depleted - this is why `Grim` is useless and detrimental in this build.
With `Rubi` in hand you can pretty much just trade blows with most things. If you are using something similar to this build, your damage output in UVHM will be "sufficient" as well as your sustainability.
If anyone tells you Zer0 is not viable, they are either not using something like this or do not know what they are talking about. As far as I know Salvador is the only one that comes closest/surpasses Zer0 in damage output. Gaige's Deathtrap and Axton's turret(s) don't come anywhere close to what melee Zer0 can dish out.
Yes, this does mean pretty much every gun you get is near useless and their damage is irrelevant (remember you still have 2 slots you need to fill). The only values that matter in term of damage is your level, melee modifier, and skills that modifies melee damage. As far as I know, nothing of value was added in UVHM for Zer0 players.
More info organized [here](http://forums.gearboxsoftware.com/showthread.php?t=255385).
Some interesting video:
* [Max damage done in a single hit](http://www.youtube.com/watch?v=0iduz8Aj7HI) - I believe it is because [Death Mark](http://borderlands.wikia.com/wiki/Deathmark) from multiple players can stack
+ [UVHM Voracidous The Invincible Melee Solo](http://www.youtube.com/watch?v=v8WDBCg86Aw)
+ [Pyro Pete solo](http://www.youtube.com/watch?v=Rnz0tIfSq2I) - PT2.5 I believe
+ Pretty much most video by [Gothalion](http://www.youtube.com/user/BorderlandsCom/videos?view=0&flow=grid)
+ [Alternative](http://www.youtube.com/watch?v=AC6tvc59gss) to melee Zer0 using B0re on Hyperius | I am currently doing solo UVHM as Hybrid Zero, and it's been a breeze. Slag -> correct elemental weapon—even badasses and super badasses go down in few hits.
(I don't really buy that "getting killed in 1-2 hits.
My Zer0 has 400k health and is perfectly capable of soaking damage.)
Although I do confess that the constant weapon swapping gets really tiring after a while, it's so routine and tedious:
shielded bandit -> slag -> shock -> fire -> reload all weapons -> next enemy-> rinse and repeat ad nauseam...
But I wouldn't say it's hard. Just use those elemental weapons and remember to slag the hell out of everything, and a few well placed shots are all you need to take down the baddies.
For melee builds, use slag singularity grenades before going for Many Must Fall, those executions deal insane amounts of damage on slagged enemies.
Kunai also benefits from any bonus for "melee damage" since it registers as a melee.
B0re can totally devastate groups of enemies. Just drag them together with singularity slag and fire away. If done right, everyone is dead before your magazine is empty. |
115,930 | Since the update I've attempted to play the new mode but am not doing so well. I have an assassin specialized mainly into the Cunning tree and partially into the Bloodshed side. With my current build I can't even get passed the W4R-DEN with leads me to believe co-op is almost a necessary requirement to beat this mode.
Am I right or do I just need better equipment to do this? Maybe other classes would also be better suited to beating this solo as well? | 2013/05/02 | [
"https://gaming.stackexchange.com/questions/115930",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/37612/"
] | This is an Assassin equipment guide (with some skill pointers) for Ultimate Vault Hunter Mode. It's not the only right solution, nor do I claim this to be the *best* possible, but it is something that worked for me, making the UVHM easy to solo.
NOTE: This guide does not include any Legendary or E-tech weapons, mods or relics because getting them is based on very low drop rate and hours of farming on specific bosses. (e.g.: Conference Call requires you to farm The Warrior or Handsome Jack.) This guide also does not include any quest-specific items, since getting them requires you to complete those quests first. Telling you to use some equipment that you won't get until late into the game would be rather pointless - if you're already to the endgame, why would you be needing this?
Quick analysis:
What's Zer0 great at, and where is he not so great?
Zer0 is really good at everything. Depending on your choice of skills and equipment, he can do just about anything fairly well - even tanking. This guide is geared towards a solo game though, so there won't be a lot of coverage on such co-op strategies.
His primary strength is dealing damage, in one of two ways: Either massively painful single blows every 15-20 seconds, or a constant stream of high DPS through damage bonus modifiers. Both styles work out to about the same rate of damage in the end, so which way you play is really up to you.
Weapons:
Forget any non-elemental guns. While you may love Jakobs guns for their ridiculously high raw damage stats, they're really not so useful in UVHM. UVHM puts heavy weight on exploiting your enemy's elemental weaknesses (and, conversely, greatly beefs up the enemies' elemental resistances) and effective use of multiple weapons. Slag damage is also greatly boosted. This is why you should notice that your weapon swap speed is slightly increased in UVHM. If you're playing UVHM, you're sure to find a whole new appreciation for Maliwan!
Always keep at least one each of Slag, Fire, Corrosive, and Shock weaponry on hand.
Make sure your Slag weapon has a *high chance* to slag. The gun damage is trivial - it can even be a level 1 gun, so long as it has a very high Slag percentage. You're not using the gun to deal the bulk of your damage in the fight. You're using it to enhance the damage your other guns deal. You don't want to throw yourself into the fray with a gun that constantly fails to apply Slag.
Pro Tip: Have 2 Slag weapons - one for close range, one for long range.
For your Shock weapon, you can use a Sniper Rifle. Shock damage has no penalty on flesh or armor, but deals *massive* damage on Shields. This means that a high-powered Shock Sniper Rifle can take out enemy Shields even without Slag. Still, you may want to carry a rapid-firing Shock SMG just in case. (Even though most heavy troopers don't carry shields - I guess it's an ego thing.)
For Fire weapons, I really recommend an SMG. After you've applied Slag, you can take down even Badass-level enemies with a rapid-firing Fire SMG. Moxxi's Good touch is great for this. You can get the Good Touch during any part of the game as long as you have access to Sanctuary. Just go to Moxxi's bar and tip her enough money (somewhere between $20k-$75k - anecdotal evidence varies). Good Touch always scales to your level, is extremely powerful, and returns 2% of the damage dealt back to you as a health recharge! You can go back to Moxxi any time to tip her again for a new one, which again will be scaled to your current level, so don't worry about "out-growing" this gun.
For corrosive weapons: SMG, SMG, SMG! Alternately, Shotgun. Most of the armored enemies you'll encounter are fast-moving Psychos (though now we call them Lunatics) or Hyperion loaders. Most of these will have hard-to-hit Critical locations, and will either be in your face with Melee or swarming you with Machine Gun fire and Grenades. This is not a good place to be relying on a Sniper Rifle. Instead, Slag the Lunatics and unload that SMG or Shotgun in their face - like everyone is Face McShooty! Loaders are about the same - they can quickly close the gap. Those pesky Surveyors aren't going to just hang around waiting for you to Snipe their armored core. Instead, blast them to bits with a Shotgun while they try their flyby attacks.
Grenades:
Yes! Lots of Grenades! Your best choice here is for Singularity or MIRV with a huge radius. Activate Decepti0n and drop grenades everywhere (this does not break Decepti0n) while you run for cover! This is extremely useful when getting pestered by those Stalkers, especially since you can see them while in Decepti0n even when they're invisible.
Pro Tip (especially for Solo players only): Throw a Slag Singularity, pause the game, switch to an Explosive MIRV and throw it where you dropped the Singularity. Watch the meat fountain! Instant profit!
Shields:
Anshin adaptive Shields. Not only do they give you a nice damage resistance bonus (matching resistance to the last damage type received), they also increase your health. Zer0 is all about health, especially considering that he is the only class with no passive Shield bonuses but all kinds of ways to regenerate *huge* amounts of health in *seconds*! If you're lucky enough to find a Purple-grade Anshin Shield (which offers up to 60% damage resistance) you can pretty much just stand idle while a Bruiser shotguns you to the face!
If you're more of a slash-and-dash player, you might prefer to use a shield that adds Roid damage. However, these usually have very short recharge delays which make them fairly difficult to use effectively (since the shield has to stay discharged to give you the bonus). The best use for Melee with Zer0 is to deliver the Killing Bl0ws to quickly dispatch enemies with low health. You don't need Roid shields for that, and you can even get a bonus with Resurgence which recovers health on every Melee kill.
Pro Tip: Carry one "elemental immunity" Shield of each element type on your backpack, regardless the level or type of Shields. You never know when you'll bump into a pack of enemies that are using just one elemental type. You'll *really* want that Shock immunity when the Super Badass Shock Skag decides to fry your brains with electric barks, while his Shock-charged Pups gnaw on your legs!
Relics:
Health relics - buff that HP! If you're using Anshin Shields as recommended, your Shield capacity is going to be low. Compensate for that by getting your Health as high as you can!
Class Mods:
Use a Survivor Class Mod. They all give extra HP and HP regeneration, and many come with some nice skill bonuses. Regenerating 600 HP/s may seem a bit slow when you have over 300k HP, but you'll be really glad your HP is constantly recharging when you're ducking for cover under heavy Buzzard fire. It's also real nice to know that, when you're traveling about, you won't have to shell out at the nearest Zed's when you get to town - by the time you get there, your health will already be full again!
The 8k HP bonus might not look like much, when you consider your enemies are blowing away 50k at a time. But when you survive that crazy blaster master rocket bombardment with just a few hundred HP left - giving you a chance to pop Decepti0n and run for cover, *while* regaining health - you'll be really glad you chose a Survivor mod!
Other decent Class Mod choices are Infiltrator and Ninja, if they suit your play style and Skill setups better.
Skills:
A full build layout is too much to cover in this post, but I'll give a few pointers.
B0re, B0re, B0re, B0re, B0re! No matter what your play style, take this one skill! You'll learn to love it, once you get the hang of it's effective use. It may also give you a pleasant suprise in a fight against Bunker. ;)
Execute. Take it, take it, take it, take it, take it! Combined with Killing Bl0w, this one can win you a lot of losing battles.
Innervate. At level 5, this skill lets you recover up to 24% of your max HP (which should be fairly high, if you've followed the above recommendations) whenever you drop into Decepti0n. Who can really say no to a fresh 24% HP refill available every 15 seconds? And if you've followed my recommendations so far, 24% of your max HP should be **a lot** of HP!
Rising Sh0t. Using those elemental SMGs like I told you to? Then meet your new best friend! At level 5, Rising Sh0t makes your 5th consecutive hit (and every consecutive hit afterwards) have a 50% damage bonus. With a really nice Survivor mod, this can be boosted to 110%! You *want* that extra damage! Unload your SMG on those baddies! With a 30-bullet mag, 25 bullets could be doing double damage or better! It's like having a co-op partner, or your own special way of Gunzerking! Multiply the damage with Slag and proper elemental selection, and the bad guys just don't stand a chance!
Unf0rseen - forget it!
Level 5 deals about 300k Shock damage, level 10 via Class Mods can deal almost 1M. But this has a *very* short radius, so usually the enemies you'll use this against are Suicide Psychos (which are going to, well, suicide anyway) or other relatively trivial grunts that just like being up in your face. 300k to 1M damage every 15-20 seconds is a pittance against Bosses and Badasses. With Slag, followed by the right elemental weapon, and Rising Sh0t, you'll be dealing that 300k on every shot instead!
Personal Note: I've played the game through up to level 61 with three different Zer0s. I've soloed Raid Bosses like Terramorphous, Pete, Hyperious, and Master Gee even *without* Legendary equipment! (Though once I did obtain some "Dahlicious" Orange goodness, they became even less of a hassle to defeat! Those Legendaries make a *huge* difference in terms of power - but that's another story.) | The most standard way of playing melee Zer0 is to go all the way down the `Bloodshed` tree for `Many Must Fall`. Definitely skip `Grim` because it ruins how you will be playing and `Resurgence` is useless with the weapons you will be using. See this [post](http://forums.gearboxsoftware.com/showthread.php?t=254652) for the complete melee formula (in short melee damage is based purely on your level and other modifiers, weapon damage is irrelevant unless it specifically says it does extra melee damage) - you can use this to min/max the skills. `Many Must Fall` is better than `Death Bl0ss0m` typically unless you are doing raid bosses so switch if you are farming raid bosses.
Your standard setup includes:
* [Rubi](http://borderlands.wikia.com/wiki/Rubi) (preferably with `Slag` and `Evisceration`)
+ An alternative is to use [Law](http://borderlands.wikia.com/wiki/Law_%28Borderlands_2%29) with [Order](http://borderlands.wikia.com/wiki/Order) but I believe you will do less damage overall
+ This is how you are going to recover HP - ~12% damage you do with `Rubi` is gained as HP, you will often go from 1% to 100% HP in one hit
+ Any damage done while holding `Rubi`, not just damage done with Rubi is recovered as HP
* [Love Thumper](http://borderlands.wikia.com/wiki/Love_Thumper) (preferably with one of the immunities)
+ This is the better alternative to Order for the damage that it produces which means better HP recovery
+ The reason `Love Thumper` is better than `Order` is because you don't need to manage your shield and the higher Roid damage
+ Another alternative is [Hide of Terramorphous](http://borderlands.wikia.com/wiki/Hide_of_Terramorphous) but again you will need to manage your sheilds
* [Rapier](http://borderlands.wikia.com/wiki/Rapier) (also preferably with Slag)
+ the 200% modifier is huge and if you look around you can find videos of Zer0 doing max damage in one melee swing
+ Swap and use this as necessary - DO NOT underestimate this weapon, this is a huge boost to your melee damage compared to `Rubi`
+ This requires [Captain Scarlett and Her Pirate's Booty](http://borderlands.wikia.com/wiki/Captain_Scarlett_and_Her_Pirate%27s_Booty) DLC which is pretty good overall
* [Proficiency Relic](http://borderlands.wikia.com/wiki/Proficiency_Relic) is the most common relic used
* Class mod is up to your preference
* [Storm Front](http://borderlands.wikia.com/wiki/Storm_Front)
+ Often used because it has consistent damage so paired with Rubi it has good HP recovery and the explosion can break your shield while the Tesla won't damage you
* I usually keep a Rocket Launcher, Sniper Rifle, or [Dahlminator](http://borderlands.wikia.com/wiki/Dahlminator) in the remaining slots for FFYL, long distance, or flying enemies
Remember Roid damage is a big contributor to your overall damage so your shield should usually be depleted - this is why `Grim` is useless and detrimental in this build.
With `Rubi` in hand you can pretty much just trade blows with most things. If you are using something similar to this build, your damage output in UVHM will be "sufficient" as well as your sustainability.
If anyone tells you Zer0 is not viable, they are either not using something like this or do not know what they are talking about. As far as I know Salvador is the only one that comes closest/surpasses Zer0 in damage output. Gaige's Deathtrap and Axton's turret(s) don't come anywhere close to what melee Zer0 can dish out.
Yes, this does mean pretty much every gun you get is near useless and their damage is irrelevant (remember you still have 2 slots you need to fill). The only values that matter in term of damage is your level, melee modifier, and skills that modifies melee damage. As far as I know, nothing of value was added in UVHM for Zer0 players.
More info organized [here](http://forums.gearboxsoftware.com/showthread.php?t=255385).
Some interesting video:
* [Max damage done in a single hit](http://www.youtube.com/watch?v=0iduz8Aj7HI) - I believe it is because [Death Mark](http://borderlands.wikia.com/wiki/Deathmark) from multiple players can stack
+ [UVHM Voracidous The Invincible Melee Solo](http://www.youtube.com/watch?v=v8WDBCg86Aw)
+ [Pyro Pete solo](http://www.youtube.com/watch?v=Rnz0tIfSq2I) - PT2.5 I believe
+ Pretty much most video by [Gothalion](http://www.youtube.com/user/BorderlandsCom/videos?view=0&flow=grid)
+ [Alternative](http://www.youtube.com/watch?v=AC6tvc59gss) to melee Zer0 using B0re on Hyperius |
115,930 | Since the update I've attempted to play the new mode but am not doing so well. I have an assassin specialized mainly into the Cunning tree and partially into the Bloodshed side. With my current build I can't even get passed the W4R-DEN with leads me to believe co-op is almost a necessary requirement to beat this mode.
Am I right or do I just need better equipment to do this? Maybe other classes would also be better suited to beating this solo as well? | 2013/05/02 | [
"https://gaming.stackexchange.com/questions/115930",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/37612/"
] | The most standard way of playing melee Zer0 is to go all the way down the `Bloodshed` tree for `Many Must Fall`. Definitely skip `Grim` because it ruins how you will be playing and `Resurgence` is useless with the weapons you will be using. See this [post](http://forums.gearboxsoftware.com/showthread.php?t=254652) for the complete melee formula (in short melee damage is based purely on your level and other modifiers, weapon damage is irrelevant unless it specifically says it does extra melee damage) - you can use this to min/max the skills. `Many Must Fall` is better than `Death Bl0ss0m` typically unless you are doing raid bosses so switch if you are farming raid bosses.
Your standard setup includes:
* [Rubi](http://borderlands.wikia.com/wiki/Rubi) (preferably with `Slag` and `Evisceration`)
+ An alternative is to use [Law](http://borderlands.wikia.com/wiki/Law_%28Borderlands_2%29) with [Order](http://borderlands.wikia.com/wiki/Order) but I believe you will do less damage overall
+ This is how you are going to recover HP - ~12% damage you do with `Rubi` is gained as HP, you will often go from 1% to 100% HP in one hit
+ Any damage done while holding `Rubi`, not just damage done with Rubi is recovered as HP
* [Love Thumper](http://borderlands.wikia.com/wiki/Love_Thumper) (preferably with one of the immunities)
+ This is the better alternative to Order for the damage that it produces which means better HP recovery
+ The reason `Love Thumper` is better than `Order` is because you don't need to manage your shield and the higher Roid damage
+ Another alternative is [Hide of Terramorphous](http://borderlands.wikia.com/wiki/Hide_of_Terramorphous) but again you will need to manage your sheilds
* [Rapier](http://borderlands.wikia.com/wiki/Rapier) (also preferably with Slag)
+ the 200% modifier is huge and if you look around you can find videos of Zer0 doing max damage in one melee swing
+ Swap and use this as necessary - DO NOT underestimate this weapon, this is a huge boost to your melee damage compared to `Rubi`
+ This requires [Captain Scarlett and Her Pirate's Booty](http://borderlands.wikia.com/wiki/Captain_Scarlett_and_Her_Pirate%27s_Booty) DLC which is pretty good overall
* [Proficiency Relic](http://borderlands.wikia.com/wiki/Proficiency_Relic) is the most common relic used
* Class mod is up to your preference
* [Storm Front](http://borderlands.wikia.com/wiki/Storm_Front)
+ Often used because it has consistent damage so paired with Rubi it has good HP recovery and the explosion can break your shield while the Tesla won't damage you
* I usually keep a Rocket Launcher, Sniper Rifle, or [Dahlminator](http://borderlands.wikia.com/wiki/Dahlminator) in the remaining slots for FFYL, long distance, or flying enemies
Remember Roid damage is a big contributor to your overall damage so your shield should usually be depleted - this is why `Grim` is useless and detrimental in this build.
With `Rubi` in hand you can pretty much just trade blows with most things. If you are using something similar to this build, your damage output in UVHM will be "sufficient" as well as your sustainability.
If anyone tells you Zer0 is not viable, they are either not using something like this or do not know what they are talking about. As far as I know Salvador is the only one that comes closest/surpasses Zer0 in damage output. Gaige's Deathtrap and Axton's turret(s) don't come anywhere close to what melee Zer0 can dish out.
Yes, this does mean pretty much every gun you get is near useless and their damage is irrelevant (remember you still have 2 slots you need to fill). The only values that matter in term of damage is your level, melee modifier, and skills that modifies melee damage. As far as I know, nothing of value was added in UVHM for Zer0 players.
More info organized [here](http://forums.gearboxsoftware.com/showthread.php?t=255385).
Some interesting video:
* [Max damage done in a single hit](http://www.youtube.com/watch?v=0iduz8Aj7HI) - I believe it is because [Death Mark](http://borderlands.wikia.com/wiki/Deathmark) from multiple players can stack
+ [UVHM Voracidous The Invincible Melee Solo](http://www.youtube.com/watch?v=v8WDBCg86Aw)
+ [Pyro Pete solo](http://www.youtube.com/watch?v=Rnz0tIfSq2I) - PT2.5 I believe
+ Pretty much most video by [Gothalion](http://www.youtube.com/user/BorderlandsCom/videos?view=0&flow=grid)
+ [Alternative](http://www.youtube.com/watch?v=AC6tvc59gss) to melee Zer0 using B0re on Hyperius | If you have Tiny Tina's Dragon Keep DLC, then go find a Magic Missle grenade mod dropped by a wizard. Regardless of what level you find one at, they all do the same thing.
1) they regenerate your grenade ammo
2) they fire 2 homing nades that home in on opponents
3) the homing nades have an almost 100% chance to slag on explosion
Toss a Magic Missle. Let it slag some folks while you switch to the appropriate elemental sniper (fire for flesh, corrosive for armor (yellow health bar), shock for shields, or explosive for all-around decent damage on everything). Let the homing Magic Missles do their trick.
This ensures you always get slagged enemies, and then you pick them off. If you team it with something like the Pimpernal from Scarlett's Pirate Booty DLC you can do some major damage. Problem with UVHM is that levelling scales even more exponentially, so weapons that are 2-3 levels behind get useless very fast. It's better to just move on to a same-level white gun than to stick with a lower-level green, blue, etc. |
115,930 | Since the update I've attempted to play the new mode but am not doing so well. I have an assassin specialized mainly into the Cunning tree and partially into the Bloodshed side. With my current build I can't even get passed the W4R-DEN with leads me to believe co-op is almost a necessary requirement to beat this mode.
Am I right or do I just need better equipment to do this? Maybe other classes would also be better suited to beating this solo as well? | 2013/05/02 | [
"https://gaming.stackexchange.com/questions/115930",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/37612/"
] | This is an Assassin equipment guide (with some skill pointers) for Ultimate Vault Hunter Mode. It's not the only right solution, nor do I claim this to be the *best* possible, but it is something that worked for me, making the UVHM easy to solo.
NOTE: This guide does not include any Legendary or E-tech weapons, mods or relics because getting them is based on very low drop rate and hours of farming on specific bosses. (e.g.: Conference Call requires you to farm The Warrior or Handsome Jack.) This guide also does not include any quest-specific items, since getting them requires you to complete those quests first. Telling you to use some equipment that you won't get until late into the game would be rather pointless - if you're already to the endgame, why would you be needing this?
Quick analysis:
What's Zer0 great at, and where is he not so great?
Zer0 is really good at everything. Depending on your choice of skills and equipment, he can do just about anything fairly well - even tanking. This guide is geared towards a solo game though, so there won't be a lot of coverage on such co-op strategies.
His primary strength is dealing damage, in one of two ways: Either massively painful single blows every 15-20 seconds, or a constant stream of high DPS through damage bonus modifiers. Both styles work out to about the same rate of damage in the end, so which way you play is really up to you.
Weapons:
Forget any non-elemental guns. While you may love Jakobs guns for their ridiculously high raw damage stats, they're really not so useful in UVHM. UVHM puts heavy weight on exploiting your enemy's elemental weaknesses (and, conversely, greatly beefs up the enemies' elemental resistances) and effective use of multiple weapons. Slag damage is also greatly boosted. This is why you should notice that your weapon swap speed is slightly increased in UVHM. If you're playing UVHM, you're sure to find a whole new appreciation for Maliwan!
Always keep at least one each of Slag, Fire, Corrosive, and Shock weaponry on hand.
Make sure your Slag weapon has a *high chance* to slag. The gun damage is trivial - it can even be a level 1 gun, so long as it has a very high Slag percentage. You're not using the gun to deal the bulk of your damage in the fight. You're using it to enhance the damage your other guns deal. You don't want to throw yourself into the fray with a gun that constantly fails to apply Slag.
Pro Tip: Have 2 Slag weapons - one for close range, one for long range.
For your Shock weapon, you can use a Sniper Rifle. Shock damage has no penalty on flesh or armor, but deals *massive* damage on Shields. This means that a high-powered Shock Sniper Rifle can take out enemy Shields even without Slag. Still, you may want to carry a rapid-firing Shock SMG just in case. (Even though most heavy troopers don't carry shields - I guess it's an ego thing.)
For Fire weapons, I really recommend an SMG. After you've applied Slag, you can take down even Badass-level enemies with a rapid-firing Fire SMG. Moxxi's Good touch is great for this. You can get the Good Touch during any part of the game as long as you have access to Sanctuary. Just go to Moxxi's bar and tip her enough money (somewhere between $20k-$75k - anecdotal evidence varies). Good Touch always scales to your level, is extremely powerful, and returns 2% of the damage dealt back to you as a health recharge! You can go back to Moxxi any time to tip her again for a new one, which again will be scaled to your current level, so don't worry about "out-growing" this gun.
For corrosive weapons: SMG, SMG, SMG! Alternately, Shotgun. Most of the armored enemies you'll encounter are fast-moving Psychos (though now we call them Lunatics) or Hyperion loaders. Most of these will have hard-to-hit Critical locations, and will either be in your face with Melee or swarming you with Machine Gun fire and Grenades. This is not a good place to be relying on a Sniper Rifle. Instead, Slag the Lunatics and unload that SMG or Shotgun in their face - like everyone is Face McShooty! Loaders are about the same - they can quickly close the gap. Those pesky Surveyors aren't going to just hang around waiting for you to Snipe their armored core. Instead, blast them to bits with a Shotgun while they try their flyby attacks.
Grenades:
Yes! Lots of Grenades! Your best choice here is for Singularity or MIRV with a huge radius. Activate Decepti0n and drop grenades everywhere (this does not break Decepti0n) while you run for cover! This is extremely useful when getting pestered by those Stalkers, especially since you can see them while in Decepti0n even when they're invisible.
Pro Tip (especially for Solo players only): Throw a Slag Singularity, pause the game, switch to an Explosive MIRV and throw it where you dropped the Singularity. Watch the meat fountain! Instant profit!
Shields:
Anshin adaptive Shields. Not only do they give you a nice damage resistance bonus (matching resistance to the last damage type received), they also increase your health. Zer0 is all about health, especially considering that he is the only class with no passive Shield bonuses but all kinds of ways to regenerate *huge* amounts of health in *seconds*! If you're lucky enough to find a Purple-grade Anshin Shield (which offers up to 60% damage resistance) you can pretty much just stand idle while a Bruiser shotguns you to the face!
If you're more of a slash-and-dash player, you might prefer to use a shield that adds Roid damage. However, these usually have very short recharge delays which make them fairly difficult to use effectively (since the shield has to stay discharged to give you the bonus). The best use for Melee with Zer0 is to deliver the Killing Bl0ws to quickly dispatch enemies with low health. You don't need Roid shields for that, and you can even get a bonus with Resurgence which recovers health on every Melee kill.
Pro Tip: Carry one "elemental immunity" Shield of each element type on your backpack, regardless the level or type of Shields. You never know when you'll bump into a pack of enemies that are using just one elemental type. You'll *really* want that Shock immunity when the Super Badass Shock Skag decides to fry your brains with electric barks, while his Shock-charged Pups gnaw on your legs!
Relics:
Health relics - buff that HP! If you're using Anshin Shields as recommended, your Shield capacity is going to be low. Compensate for that by getting your Health as high as you can!
Class Mods:
Use a Survivor Class Mod. They all give extra HP and HP regeneration, and many come with some nice skill bonuses. Regenerating 600 HP/s may seem a bit slow when you have over 300k HP, but you'll be really glad your HP is constantly recharging when you're ducking for cover under heavy Buzzard fire. It's also real nice to know that, when you're traveling about, you won't have to shell out at the nearest Zed's when you get to town - by the time you get there, your health will already be full again!
The 8k HP bonus might not look like much, when you consider your enemies are blowing away 50k at a time. But when you survive that crazy blaster master rocket bombardment with just a few hundred HP left - giving you a chance to pop Decepti0n and run for cover, *while* regaining health - you'll be really glad you chose a Survivor mod!
Other decent Class Mod choices are Infiltrator and Ninja, if they suit your play style and Skill setups better.
Skills:
A full build layout is too much to cover in this post, but I'll give a few pointers.
B0re, B0re, B0re, B0re, B0re! No matter what your play style, take this one skill! You'll learn to love it, once you get the hang of it's effective use. It may also give you a pleasant suprise in a fight against Bunker. ;)
Execute. Take it, take it, take it, take it, take it! Combined with Killing Bl0w, this one can win you a lot of losing battles.
Innervate. At level 5, this skill lets you recover up to 24% of your max HP (which should be fairly high, if you've followed the above recommendations) whenever you drop into Decepti0n. Who can really say no to a fresh 24% HP refill available every 15 seconds? And if you've followed my recommendations so far, 24% of your max HP should be **a lot** of HP!
Rising Sh0t. Using those elemental SMGs like I told you to? Then meet your new best friend! At level 5, Rising Sh0t makes your 5th consecutive hit (and every consecutive hit afterwards) have a 50% damage bonus. With a really nice Survivor mod, this can be boosted to 110%! You *want* that extra damage! Unload your SMG on those baddies! With a 30-bullet mag, 25 bullets could be doing double damage or better! It's like having a co-op partner, or your own special way of Gunzerking! Multiply the damage with Slag and proper elemental selection, and the bad guys just don't stand a chance!
Unf0rseen - forget it!
Level 5 deals about 300k Shock damage, level 10 via Class Mods can deal almost 1M. But this has a *very* short radius, so usually the enemies you'll use this against are Suicide Psychos (which are going to, well, suicide anyway) or other relatively trivial grunts that just like being up in your face. 300k to 1M damage every 15-20 seconds is a pittance against Bosses and Badasses. With Slag, followed by the right elemental weapon, and Rising Sh0t, you'll be dealing that 300k on every shot instead!
Personal Note: I've played the game through up to level 61 with three different Zer0s. I've soloed Raid Bosses like Terramorphous, Pete, Hyperious, and Master Gee even *without* Legendary equipment! (Though once I did obtain some "Dahlicious" Orange goodness, they became even less of a hassle to defeat! Those Legendaries make a *huge* difference in terms of power - but that's another story.) | I am currently doing solo UVHM as Hybrid Zero, and it's been a breeze. Slag -> correct elemental weapon—even badasses and super badasses go down in few hits.
(I don't really buy that "getting killed in 1-2 hits.
My Zer0 has 400k health and is perfectly capable of soaking damage.)
Although I do confess that the constant weapon swapping gets really tiring after a while, it's so routine and tedious:
shielded bandit -> slag -> shock -> fire -> reload all weapons -> next enemy-> rinse and repeat ad nauseam...
But I wouldn't say it's hard. Just use those elemental weapons and remember to slag the hell out of everything, and a few well placed shots are all you need to take down the baddies.
For melee builds, use slag singularity grenades before going for Many Must Fall, those executions deal insane amounts of damage on slagged enemies.
Kunai also benefits from any bonus for "melee damage" since it registers as a melee.
B0re can totally devastate groups of enemies. Just drag them together with singularity slag and fire away. If done right, everyone is dead before your magazine is empty. |
115,930 | Since the update I've attempted to play the new mode but am not doing so well. I have an assassin specialized mainly into the Cunning tree and partially into the Bloodshed side. With my current build I can't even get passed the W4R-DEN with leads me to believe co-op is almost a necessary requirement to beat this mode.
Am I right or do I just need better equipment to do this? Maybe other classes would also be better suited to beating this solo as well? | 2013/05/02 | [
"https://gaming.stackexchange.com/questions/115930",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/37612/"
] | This is an Assassin equipment guide (with some skill pointers) for Ultimate Vault Hunter Mode. It's not the only right solution, nor do I claim this to be the *best* possible, but it is something that worked for me, making the UVHM easy to solo.
NOTE: This guide does not include any Legendary or E-tech weapons, mods or relics because getting them is based on very low drop rate and hours of farming on specific bosses. (e.g.: Conference Call requires you to farm The Warrior or Handsome Jack.) This guide also does not include any quest-specific items, since getting them requires you to complete those quests first. Telling you to use some equipment that you won't get until late into the game would be rather pointless - if you're already to the endgame, why would you be needing this?
Quick analysis:
What's Zer0 great at, and where is he not so great?
Zer0 is really good at everything. Depending on your choice of skills and equipment, he can do just about anything fairly well - even tanking. This guide is geared towards a solo game though, so there won't be a lot of coverage on such co-op strategies.
His primary strength is dealing damage, in one of two ways: Either massively painful single blows every 15-20 seconds, or a constant stream of high DPS through damage bonus modifiers. Both styles work out to about the same rate of damage in the end, so which way you play is really up to you.
Weapons:
Forget any non-elemental guns. While you may love Jakobs guns for their ridiculously high raw damage stats, they're really not so useful in UVHM. UVHM puts heavy weight on exploiting your enemy's elemental weaknesses (and, conversely, greatly beefs up the enemies' elemental resistances) and effective use of multiple weapons. Slag damage is also greatly boosted. This is why you should notice that your weapon swap speed is slightly increased in UVHM. If you're playing UVHM, you're sure to find a whole new appreciation for Maliwan!
Always keep at least one each of Slag, Fire, Corrosive, and Shock weaponry on hand.
Make sure your Slag weapon has a *high chance* to slag. The gun damage is trivial - it can even be a level 1 gun, so long as it has a very high Slag percentage. You're not using the gun to deal the bulk of your damage in the fight. You're using it to enhance the damage your other guns deal. You don't want to throw yourself into the fray with a gun that constantly fails to apply Slag.
Pro Tip: Have 2 Slag weapons - one for close range, one for long range.
For your Shock weapon, you can use a Sniper Rifle. Shock damage has no penalty on flesh or armor, but deals *massive* damage on Shields. This means that a high-powered Shock Sniper Rifle can take out enemy Shields even without Slag. Still, you may want to carry a rapid-firing Shock SMG just in case. (Even though most heavy troopers don't carry shields - I guess it's an ego thing.)
For Fire weapons, I really recommend an SMG. After you've applied Slag, you can take down even Badass-level enemies with a rapid-firing Fire SMG. Moxxi's Good touch is great for this. You can get the Good Touch during any part of the game as long as you have access to Sanctuary. Just go to Moxxi's bar and tip her enough money (somewhere between $20k-$75k - anecdotal evidence varies). Good Touch always scales to your level, is extremely powerful, and returns 2% of the damage dealt back to you as a health recharge! You can go back to Moxxi any time to tip her again for a new one, which again will be scaled to your current level, so don't worry about "out-growing" this gun.
For corrosive weapons: SMG, SMG, SMG! Alternately, Shotgun. Most of the armored enemies you'll encounter are fast-moving Psychos (though now we call them Lunatics) or Hyperion loaders. Most of these will have hard-to-hit Critical locations, and will either be in your face with Melee or swarming you with Machine Gun fire and Grenades. This is not a good place to be relying on a Sniper Rifle. Instead, Slag the Lunatics and unload that SMG or Shotgun in their face - like everyone is Face McShooty! Loaders are about the same - they can quickly close the gap. Those pesky Surveyors aren't going to just hang around waiting for you to Snipe their armored core. Instead, blast them to bits with a Shotgun while they try their flyby attacks.
Grenades:
Yes! Lots of Grenades! Your best choice here is for Singularity or MIRV with a huge radius. Activate Decepti0n and drop grenades everywhere (this does not break Decepti0n) while you run for cover! This is extremely useful when getting pestered by those Stalkers, especially since you can see them while in Decepti0n even when they're invisible.
Pro Tip (especially for Solo players only): Throw a Slag Singularity, pause the game, switch to an Explosive MIRV and throw it where you dropped the Singularity. Watch the meat fountain! Instant profit!
Shields:
Anshin adaptive Shields. Not only do they give you a nice damage resistance bonus (matching resistance to the last damage type received), they also increase your health. Zer0 is all about health, especially considering that he is the only class with no passive Shield bonuses but all kinds of ways to regenerate *huge* amounts of health in *seconds*! If you're lucky enough to find a Purple-grade Anshin Shield (which offers up to 60% damage resistance) you can pretty much just stand idle while a Bruiser shotguns you to the face!
If you're more of a slash-and-dash player, you might prefer to use a shield that adds Roid damage. However, these usually have very short recharge delays which make them fairly difficult to use effectively (since the shield has to stay discharged to give you the bonus). The best use for Melee with Zer0 is to deliver the Killing Bl0ws to quickly dispatch enemies with low health. You don't need Roid shields for that, and you can even get a bonus with Resurgence which recovers health on every Melee kill.
Pro Tip: Carry one "elemental immunity" Shield of each element type on your backpack, regardless the level or type of Shields. You never know when you'll bump into a pack of enemies that are using just one elemental type. You'll *really* want that Shock immunity when the Super Badass Shock Skag decides to fry your brains with electric barks, while his Shock-charged Pups gnaw on your legs!
Relics:
Health relics - buff that HP! If you're using Anshin Shields as recommended, your Shield capacity is going to be low. Compensate for that by getting your Health as high as you can!
Class Mods:
Use a Survivor Class Mod. They all give extra HP and HP regeneration, and many come with some nice skill bonuses. Regenerating 600 HP/s may seem a bit slow when you have over 300k HP, but you'll be really glad your HP is constantly recharging when you're ducking for cover under heavy Buzzard fire. It's also real nice to know that, when you're traveling about, you won't have to shell out at the nearest Zed's when you get to town - by the time you get there, your health will already be full again!
The 8k HP bonus might not look like much, when you consider your enemies are blowing away 50k at a time. But when you survive that crazy blaster master rocket bombardment with just a few hundred HP left - giving you a chance to pop Decepti0n and run for cover, *while* regaining health - you'll be really glad you chose a Survivor mod!
Other decent Class Mod choices are Infiltrator and Ninja, if they suit your play style and Skill setups better.
Skills:
A full build layout is too much to cover in this post, but I'll give a few pointers.
B0re, B0re, B0re, B0re, B0re! No matter what your play style, take this one skill! You'll learn to love it, once you get the hang of it's effective use. It may also give you a pleasant suprise in a fight against Bunker. ;)
Execute. Take it, take it, take it, take it, take it! Combined with Killing Bl0w, this one can win you a lot of losing battles.
Innervate. At level 5, this skill lets you recover up to 24% of your max HP (which should be fairly high, if you've followed the above recommendations) whenever you drop into Decepti0n. Who can really say no to a fresh 24% HP refill available every 15 seconds? And if you've followed my recommendations so far, 24% of your max HP should be **a lot** of HP!
Rising Sh0t. Using those elemental SMGs like I told you to? Then meet your new best friend! At level 5, Rising Sh0t makes your 5th consecutive hit (and every consecutive hit afterwards) have a 50% damage bonus. With a really nice Survivor mod, this can be boosted to 110%! You *want* that extra damage! Unload your SMG on those baddies! With a 30-bullet mag, 25 bullets could be doing double damage or better! It's like having a co-op partner, or your own special way of Gunzerking! Multiply the damage with Slag and proper elemental selection, and the bad guys just don't stand a chance!
Unf0rseen - forget it!
Level 5 deals about 300k Shock damage, level 10 via Class Mods can deal almost 1M. But this has a *very* short radius, so usually the enemies you'll use this against are Suicide Psychos (which are going to, well, suicide anyway) or other relatively trivial grunts that just like being up in your face. 300k to 1M damage every 15-20 seconds is a pittance against Bosses and Badasses. With Slag, followed by the right elemental weapon, and Rising Sh0t, you'll be dealing that 300k on every shot instead!
Personal Note: I've played the game through up to level 61 with three different Zer0s. I've soloed Raid Bosses like Terramorphous, Pete, Hyperious, and Master Gee even *without* Legendary equipment! (Though once I did obtain some "Dahlicious" Orange goodness, they became even less of a hassle to defeat! Those Legendaries make a *huge* difference in terms of power - but that's another story.) | If you have Tiny Tina's Dragon Keep DLC, then go find a Magic Missle grenade mod dropped by a wizard. Regardless of what level you find one at, they all do the same thing.
1) they regenerate your grenade ammo
2) they fire 2 homing nades that home in on opponents
3) the homing nades have an almost 100% chance to slag on explosion
Toss a Magic Missle. Let it slag some folks while you switch to the appropriate elemental sniper (fire for flesh, corrosive for armor (yellow health bar), shock for shields, or explosive for all-around decent damage on everything). Let the homing Magic Missles do their trick.
This ensures you always get slagged enemies, and then you pick them off. If you team it with something like the Pimpernal from Scarlett's Pirate Booty DLC you can do some major damage. Problem with UVHM is that levelling scales even more exponentially, so weapons that are 2-3 levels behind get useless very fast. It's better to just move on to a same-level white gun than to stick with a lower-level green, blue, etc. |
112,428 | ```
{<|"date" -> "2016-04-12", "key" -> 1,
"1st" -> 0.9652777777777778`, "2nd" -> 0.8867924528301887`, "3rd" -> 0.49074074074074076`|>,
<|"date" -> "2016-04-12", "key" -> 2,
"2nd" -> 0.14619883040935672`, "3rd" -> 0.15212981744421908`|>,
<|"date" -> "2016-04-13" , "key" -> 1,
"2nd" -> 0.14619883040935672`, "3rd" -> 0.15212981744421908`|>,
<|"date" -> "2016-04-13" , "key" -> 2,
"2nd" -> 0.14619883040935672`, "3rd" -> 0.15212981744421908`|>
} // Dataset
```
Consider we are constructing a feature dataset for an id[product,user]. Feature is time related, like action\_behavior, and we need some feature for a user in a period.
Should I do this in a `Association` structure? since we have `JoinAcross`? not a `Dataset` structure?
The example shows that `"key"` `1` has feature in `04-12` and feature in `04-13`. What I want to do is, when I get data from hive, to construct this kind of tables
select a.key,a.1\_st,a.2\_st,b.1\_st,b.2\_st from
select
a.key
a.1\_st
a.2\_st
from table\_1 where date='date' a
left outer join
b.key
b.1\_st
b.2\_st
where date='date-1' b
on a.key1=b.key2
I mean the result table is one dataset only, and there are many dates rows beside `2016-04-12, 2016-04-13`:
[](https://i.stack.imgur.com/XfaeN.jpg) | 2016/04/12 | [
"https://mathematica.stackexchange.com/questions/112428",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/6648/"
] | `Dataset` excels at representing hierarchical data. If you look at your problem as creating a hierarchy of records with levels `"key"` and `"date"` then a `Dataset` solution quickly presents itself.
To make querying easier I first ensure all records contain all keys with `KeyUnion`. Then create the `Dataset`.
```
dat = Dataset@KeyUnion@associations
```

Now with `GroupBy` a single hierarchical `Dataset` can be created.
```
gdat = dat[GroupBy[#"key" &], GroupBy[#"date" &]]
```

It is kind of difficult to see the structure so we can implicitly use `Dataset` to show it. **Note** *this is only needed to show the structure in a visually friendly way.* You don't need to do this on your larger dataset.
```
gdat[All, Dataset, Dataset]
```

Now you can query the hierarchical dataset for your values.
```
gdat[1, All, All, "1st"]
```

```
gdat[All, "2016-04-12", All, "3rd"]
```

```
gdat[2, "2016-04-12"]
```

And so on.
Hope this helps. | Not sure if this can be done using `JoinAcross`.
```
associations = {
<|"date" -> "2016-04-12", "key" -> 1, "1st" -> 0.9652777777777778`,
"2nd" -> 0.8867924528301887`, "3rd" -> 0.49074074074074076`|>,
<|"date" -> "2016-04-12", "key" -> 2,
"2nd" -> 0.14619883040935672`, "3rd" -> 0.15212981744421908`|>,
<|"date" -> "2016-04-13", "key" -> 1,
"2nd" -> 0.14619883040935672`, "3rd" -> 0.15212981744421908`|>,
<|"date" -> "2016-04-13", "key" -> 2,
"2nd" -> 0.14619883040935672`, "3rd" -> 0.15212981744421908`|>};
Dataset[associations]
```
[](https://i.stack.imgur.com/pfjj1.png)
```
dates = Flatten@Values[Union@KeyTake[associations, "date"]];
Dataset /@ Map[Function[date, Select[#["date"] == date &]@associations], dates]
```
[](https://i.stack.imgur.com/lFp5C.png) |
71,981,738 | Hi I would like to ask for the aes mapping, if I want to have the mean of wages based on age group but I do not want to adjust the data table, is there a function I can call in the ggplot to have the mean wages based on their age group?
```
ab_final <- ab %>%
group_by(agegroup,haveKids,educationLevel) %>%
summarise(Wage = mean(Wage), Expenses = mean(Expenses)) %>%
mutate(Wage = ifelse(haveKids, -Wage, Wage), Expenses = ifelse(haveKids,Expenses,-Expenses))
head (ab_final)
```
| agegroup | haveKids | educationLevel | Wage | Expenses |
| --- | --- | --- | --- | --- |
| 18-25 | FALSE | Bachelors | 73428. | 18582. |
| 18-25 | FALSE | Graduate | 90757. | 21441. |
| 18-25 | FALSE | HighSchoolOrCollege | 36027. | 15956. |
| 18-25 | FALSE | Low | 36598. | 19367. |
| 18-25 | TRUE | Bachelors | -98265. | -24964. |
| 18-25 | TRUE | Graduate | -111545. | -25002. |
```
p <- ggplot(ab_final, aes(x = Wage, y = agegroup, fill = haveKids)) +
geom_col() +
scale_x_continuous(breaks = seq(-60000, 60000, 30000),
labels = paste0("$",as.character(c(seq(60, 0, -30), seq(30, 60, 30))),"k")) +
labs (x = "Annual Average Wage (USD)", y = "Age Group", title='Ohio Annual Average Wages based on Age Group') +
theme_bw() +
theme(axis.ticks.y = element_blank()) +
scale_fill_manual(values = c("TRUE" = "lightblue", "FALSE" = "lightpink"))
p
```
The output gives me the sum of wages based on the different age group.
```
dput(ab_final)
structure(list(agegroup = c("18-25", "18-25", "18-25", "18-25",
"18-25", "18-25", "18-25", "18-25", "26-30", "26-30", "26-30",
"26-30", "26-30", "26-30", "26-30", "26-30", "31-35", "31-35",
"31-35", "31-35", "31-35", "31-35", "31-35", "31-35", "36-40",
"36-40", "36-40", "36-40", "36-40", "36-40", "36-40", "36-40",
"41-45", "41-45", "41-45", "41-45", "41-45", "41-45", "41-45",
"41-45", "46-50", "46-50", "46-50", "46-50", "46-50", "46-50",
"46-50", "46-50", "51-55", "51-55", "51-55", "51-55", "51-55",
"51-55", "51-55", "51-55", "56-60", "56-60", "56-60", "56-60",
"56-60", "56-60", "56-60", "56-60"), haveKids = c(FALSE, FALSE,
FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE,
TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE,
TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE,
FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE,
FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE,
TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE,
TRUE, TRUE), educationLevel = c("Bachelors", "Graduate", "HighSchoolOrCollege",
"Low", "Bachelors", "Graduate", "HighSchoolOrCollege", "Low",
"Bachelors", "Graduate", "HighSchoolOrCollege", "Low", "Bachelors",
"Graduate", "HighSchoolOrCollege", "Low", "Bachelors", "Graduate",
"HighSchoolOrCollege", "Low", "Bachelors", "Graduate", "HighSchoolOrCollege",
"Low", "Bachelors", "Graduate", "HighSchoolOrCollege", "Low",
"Bachelors", "Graduate", "HighSchoolOrCollege", "Low", "Bachelors",
"Graduate", "HighSchoolOrCollege", "Low", "Bachelors", "Graduate",
"HighSchoolOrCollege", "Low", "Bachelors", "Graduate", "HighSchoolOrCollege",
"Low", "Bachelors", "Graduate", "HighSchoolOrCollege", "Low",
"Bachelors", "Graduate", "HighSchoolOrCollege", "Low", "Bachelors",
"Graduate", "HighSchoolOrCollege", "Low", "Bachelors", "Graduate",
"HighSchoolOrCollege", "Low", "Bachelors", "Graduate", "HighSchoolOrCollege",
"Low"), Wage = c(73427.6242255194, 90756.8740271891, 36027.1045766046,
36597.8823458904, -98265.2264842072, -111544.761238973, -40888.1302113056,
-29690.7404136359, 63434.2899782702, 79826.8839356714, 32912.6351345271,
28951.8407896055, -67638.6009175875, -98570.8320239257, -46688.2105971457,
-2365.18889956123, 73507.9183782092, 83276.4013393718, 35053.1036609163,
35918.5441251045, -105208.124255318, -100419.654285681, -48013.5199894127,
-31465.9994442994, 73863.5692259624, 91219.6688660635, 37944.7293875051,
24295.1828359983, -71489.157887881, -113628.534898322, -40874.9689695586,
-15048.4351165345, 63622.1379383326, 76162.2011422263, 35856.5165542073,
35290.3184801558, -90556.4678989271, -139740.754762728, -47300.5763646887,
-2351.94028134572, 57111.653529917, 88916.5286764648, 34743.1169364354,
33034.2740885343, -102954.526388641, -110730.908830255, -44183.0808505653,
-2431.62242073533, 75520.2374263526, 97118.4509577243, 40206.2010005338,
15303.2183724372, -100459.961036613, -118603.619362369, -47062.636642258,
-18136.0117958843, 68441.752176008, 78569.1358672976, 33696.7694674256,
39621.6228202485, -96083.9762853549, -113037.604308105, -39670.0761714582,
-76544.9368650725), Expenses = c(18581.7882554702, 21441.1145218955,
15955.8190788926, 19366.6794157381, -24963.6038601631, -25001.8628498845,
-18052.2160481047, -12745.725568342, 19825.5493832019, 21067.8133641346,
15513.3625856376, 12853.4842200847, -26688.4009083829, -25557.0157549876,
-19718.5033101881, -152.186005570974, 21576.3976579329, 22632.772851812,
14712.230494066, 20079.6454981138, -24514.3995124845, -31520.0721153124,
-17579.291010834, -15501.7362071054, 20980.2291762055, 21389.5574110701,
15308.3678040099, 16557.8188855836, -24639.7689642704, -26130.2577363506,
-15954.9566546377, -7768.13947033146, 20491.8443246166, 17922.4189300169,
16909.3747309647, 13233.3579986897, -23432.693758128, -22597.7448653988,
-20468.0995939873, -123.331037209483, 22093.8122932499, 19918.1372430818,
16884.6652423487, 15485.6086554647, -23946.2595731495, -22228.0345344589,
-20282.1042419724, -171.43286214832, 19531.7423065772, 20657.0373190312,
16615.5145240842, 6467.10392954871, -26143.4628401692, -22481.8353859449,
-19962.9682370225, -9238.12956845112, 21714.2834145535, 23397.9260820337,
15825.4708571827, 18634.178657809, -23591.149852639, -25458.1674870612,
-16577.2976554664, -24842.1579584659)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -64L), groups = structure(list(
agegroup = c("18-25", "18-25", "26-30", "26-30", "31-35",
"31-35", "36-40", "36-40", "41-45", "41-45", "46-50", "46-50",
"51-55", "51-55", "56-60", "56-60"), haveKids = c(FALSE,
TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE,
FALSE, TRUE, FALSE, TRUE, FALSE, TRUE), .rows = structure(list(
1:4, 5:8, 9:12, 13:16, 17:20, 21:24, 25:28, 29:32, 33:36,
37:40, 41:44, 45:48, 49:52, 53:56, 57:60, 61:64), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -16L), .drop = TRUE))
``` | 2022/04/23 | [
"https://Stackoverflow.com/questions/71981738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18156605/"
] | There are a number of issues with your code, first, and the cause of the error message you posted, is that it should be `AUTO_INCREMENT` and not `AUTOINCREMENT`.
Second you need to specify the column you insert values into, i.e. `query = 'INSERT INTO data (content) VALUES (%s)'`
Third you should insert the list using `cursor.executemany(query, values)` where each row corresponds to a tuple containing the value since `cursor.execute()` cannot insert multiple rows at once.
Fourth `readlines()` returns the newline character at the end of each line, which you probably do not want, so to read the file and insert them you could e.g. do ~:
```py
query = 'INSERT INTO data (content) VALUES (%s)'
with open('test.txt', 'rt') as file:
values = [(value,) for value in file.read().splitlines()]
cursor.executemany(query, values)
``` | The error you show means that you want to insert your data in the table `file` which doesn't exist. You've created a table `data`. When you initialize `query`, do `query = 'INSERT INTO data VALUES (%s)'` instead. |
342,393 | What's a word for someone who is generally good but might perform without a blink of an eye a sin of sorts, if it is for someone who is powerful, out of awe and admiration for that person and their name in society.
So for example a social worker who knows a family is treating their children badly but despite the fact that the children beg her to help, because she knows the family is rich and powerful and there is a sort of non-spoken agreement that these people can get away with anything, she does nothing...
Hope that makes any sense.
example: She knew Madeleine was suffering there, but one glance at her mother in the hall, arranging her gold necklace reminded her that it was nothing to worry about. She left the house with a positive written review that was left with no weight on her conscience, and out of pure \_\_\_\_\_\_\_\_\_\_. | 2016/08/12 | [
"https://english.stackexchange.com/questions/342393",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/190902/"
] | Check if ***sycophant(ic)*** fits.
Though it does not *explicitly* mean "*someone who is generally good*", it does mean someone who "*might perform without a blink of an eye a sin of sorts, if it is for someone who is powerful*". Also, the definition of ***sycophant*** does *not* explicitly exclude "*someone who is generally good*". You can also check one of the synonyms from ODO (reproduced below).
From [dictionary.cambridge.org](http://dictionary.cambridge.org/dictionary/english/sycophantic?q=sycophant):
>
> **sycophantic**
> *adjective*; *formal disapproving*
>
>
> (of a person or of behaviour) praising people in authority in a way that is not sincere, usually in
> order to get some advantage from them:
>
>
> There was sycophantic laughter
> from the audience at every one of his terrible jokes.
>
>
> **sycophant**
> *noun*
>
>
> The prime minister is surrounded by sycophants.
>
>
>
From [ODO](http://www.oxforddictionaries.com/definition/english/sycophant):
>
> **sycophant**
> *NOUN*
>
>
> A person who acts obsequiously towards someone important in order to
> gain advantage.
>
>
> Example sentences:
>
>
> An assortment of hatchet men, opportunists and sycophants gained
> access to the levers of power.
>
>
> There will be several servile sycophants who will come forward as
> ‘White Knights’ to regain their lost positions.
>
>
> Only the most sycophantic of the sycophants would even begin to make
> such a comparison. [In the past] there was at least a real enemy,
> there were real things to be done.
>
>
> **Synonyms**:
>
>
> toady, creep, crawler, fawner, flatterer, flunkey, truckler,
> groveller, doormat, lickspittle, kowtower, obsequious person, minion,
> hanger-on, leech, puppet, spaniel, Uriah Heep
>
>
> *informal* bootlicker, yes-man
>
>
> *vulgar slang* arse-licker, arse-kisser, brown-nose
>
>
> *North American vulgar slang* suckhole
>
>
> | Maybe...
>
> [**traitor**](http://www.merriam-webster.com/dictionary/traitor) - person who is not loyal to his or her own country, friends, etc. : a person who betrays a country or group of people by helping or supporting an enemy
>
>
> [**treachery**](http://www.oxforddictionaries.com/us/definition/american_english/treacherous) - Guilty of or involving betrayal or deception
>
>
> |
342,393 | What's a word for someone who is generally good but might perform without a blink of an eye a sin of sorts, if it is for someone who is powerful, out of awe and admiration for that person and their name in society.
So for example a social worker who knows a family is treating their children badly but despite the fact that the children beg her to help, because she knows the family is rich and powerful and there is a sort of non-spoken agreement that these people can get away with anything, she does nothing...
Hope that makes any sense.
example: She knew Madeleine was suffering there, but one glance at her mother in the hall, arranging her gold necklace reminded her that it was nothing to worry about. She left the house with a positive written review that was left with no weight on her conscience, and out of pure \_\_\_\_\_\_\_\_\_\_. | 2016/08/12 | [
"https://english.stackexchange.com/questions/342393",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/190902/"
] | As a single-word-request, there might not be a perfect word that specifies "giving in to an authority".
More general words include
If the connotation is that the person doesn't want to do it but is doing it out of fear of reprecussions:
* *Impressionable*
* *Meek*
* *Weak-willed*
If the connotation is that the person is doing it because they have an agreement with the authority figure:
* *Corrupt*
* A *lackey* or *servant*
In your example, though you specify that the person has no weight on her conscience by her action of doing as the authority figure wants, which points to someone who isn't meek, but is more cold-hearted or unfeeling. In such context you might want to be more descriptive than a single word and specify why the person has no weight on her conscience.
"She left the house [...] and, out of pure **selfishness**, had no weight on her conscience because the repercussions of acting against the mother would have far outweighed any feeling of good-doing that helping Madeleine could have given her." | Maybe...
>
> [**traitor**](http://www.merriam-webster.com/dictionary/traitor) - person who is not loyal to his or her own country, friends, etc. : a person who betrays a country or group of people by helping or supporting an enemy
>
>
> [**treachery**](http://www.oxforddictionaries.com/us/definition/american_english/treacherous) - Guilty of or involving betrayal or deception
>
>
> |
342,393 | What's a word for someone who is generally good but might perform without a blink of an eye a sin of sorts, if it is for someone who is powerful, out of awe and admiration for that person and their name in society.
So for example a social worker who knows a family is treating their children badly but despite the fact that the children beg her to help, because she knows the family is rich and powerful and there is a sort of non-spoken agreement that these people can get away with anything, she does nothing...
Hope that makes any sense.
example: She knew Madeleine was suffering there, but one glance at her mother in the hall, arranging her gold necklace reminded her that it was nothing to worry about. She left the house with a positive written review that was left with no weight on her conscience, and out of pure \_\_\_\_\_\_\_\_\_\_. | 2016/08/12 | [
"https://english.stackexchange.com/questions/342393",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/190902/"
] | The behaviour of indulging the wrongdoing of authority is actually so common, that it is a person displaying the opposite behaviour who is called by a specific term: *whistleblower*.
Historically the failure to report a criminal offence was itself a criminal offence called *misprision*, but the term is now as archaic as the obligation.
A catch-all term nowadays would probably be a *collaborator*, which is capable of not only including those who actively assist or cover-up, but those who wilfully turn a blind eye, including through approval, blameworthy weakness of character, or a wrong ordering of moral priorities. | Maybe...
>
> [**traitor**](http://www.merriam-webster.com/dictionary/traitor) - person who is not loyal to his or her own country, friends, etc. : a person who betrays a country or group of people by helping or supporting an enemy
>
>
> [**treachery**](http://www.oxforddictionaries.com/us/definition/american_english/treacherous) - Guilty of or involving betrayal or deception
>
>
> |
342,393 | What's a word for someone who is generally good but might perform without a blink of an eye a sin of sorts, if it is for someone who is powerful, out of awe and admiration for that person and their name in society.
So for example a social worker who knows a family is treating their children badly but despite the fact that the children beg her to help, because she knows the family is rich and powerful and there is a sort of non-spoken agreement that these people can get away with anything, she does nothing...
Hope that makes any sense.
example: She knew Madeleine was suffering there, but one glance at her mother in the hall, arranging her gold necklace reminded her that it was nothing to worry about. She left the house with a positive written review that was left with no weight on her conscience, and out of pure \_\_\_\_\_\_\_\_\_\_. | 2016/08/12 | [
"https://english.stackexchange.com/questions/342393",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/190902/"
] | Check if ***sycophant(ic)*** fits.
Though it does not *explicitly* mean "*someone who is generally good*", it does mean someone who "*might perform without a blink of an eye a sin of sorts, if it is for someone who is powerful*". Also, the definition of ***sycophant*** does *not* explicitly exclude "*someone who is generally good*". You can also check one of the synonyms from ODO (reproduced below).
From [dictionary.cambridge.org](http://dictionary.cambridge.org/dictionary/english/sycophantic?q=sycophant):
>
> **sycophantic**
> *adjective*; *formal disapproving*
>
>
> (of a person or of behaviour) praising people in authority in a way that is not sincere, usually in
> order to get some advantage from them:
>
>
> There was sycophantic laughter
> from the audience at every one of his terrible jokes.
>
>
> **sycophant**
> *noun*
>
>
> The prime minister is surrounded by sycophants.
>
>
>
From [ODO](http://www.oxforddictionaries.com/definition/english/sycophant):
>
> **sycophant**
> *NOUN*
>
>
> A person who acts obsequiously towards someone important in order to
> gain advantage.
>
>
> Example sentences:
>
>
> An assortment of hatchet men, opportunists and sycophants gained
> access to the levers of power.
>
>
> There will be several servile sycophants who will come forward as
> ‘White Knights’ to regain their lost positions.
>
>
> Only the most sycophantic of the sycophants would even begin to make
> such a comparison. [In the past] there was at least a real enemy,
> there were real things to be done.
>
>
> **Synonyms**:
>
>
> toady, creep, crawler, fawner, flatterer, flunkey, truckler,
> groveller, doormat, lickspittle, kowtower, obsequious person, minion,
> hanger-on, leech, puppet, spaniel, Uriah Heep
>
>
> *informal* bootlicker, yes-man
>
>
> *vulgar slang* arse-licker, arse-kisser, brown-nose
>
>
> *North American vulgar slang* suckhole
>
>
> | [myrmidon](http://www.merriam-webster.com/dictionary/myrmidon) - a person who executes without scruples his master's commands, like the teacher the chairman of our department kept reappointing to the personnel committee. |
342,393 | What's a word for someone who is generally good but might perform without a blink of an eye a sin of sorts, if it is for someone who is powerful, out of awe and admiration for that person and their name in society.
So for example a social worker who knows a family is treating their children badly but despite the fact that the children beg her to help, because she knows the family is rich and powerful and there is a sort of non-spoken agreement that these people can get away with anything, she does nothing...
Hope that makes any sense.
example: She knew Madeleine was suffering there, but one glance at her mother in the hall, arranging her gold necklace reminded her that it was nothing to worry about. She left the house with a positive written review that was left with no weight on her conscience, and out of pure \_\_\_\_\_\_\_\_\_\_. | 2016/08/12 | [
"https://english.stackexchange.com/questions/342393",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/190902/"
] | As a single-word-request, there might not be a perfect word that specifies "giving in to an authority".
More general words include
If the connotation is that the person doesn't want to do it but is doing it out of fear of reprecussions:
* *Impressionable*
* *Meek*
* *Weak-willed*
If the connotation is that the person is doing it because they have an agreement with the authority figure:
* *Corrupt*
* A *lackey* or *servant*
In your example, though you specify that the person has no weight on her conscience by her action of doing as the authority figure wants, which points to someone who isn't meek, but is more cold-hearted or unfeeling. In such context you might want to be more descriptive than a single word and specify why the person has no weight on her conscience.
"She left the house [...] and, out of pure **selfishness**, had no weight on her conscience because the repercussions of acting against the mother would have far outweighed any feeling of good-doing that helping Madeleine could have given her." | [myrmidon](http://www.merriam-webster.com/dictionary/myrmidon) - a person who executes without scruples his master's commands, like the teacher the chairman of our department kept reappointing to the personnel committee. |
342,393 | What's a word for someone who is generally good but might perform without a blink of an eye a sin of sorts, if it is for someone who is powerful, out of awe and admiration for that person and their name in society.
So for example a social worker who knows a family is treating their children badly but despite the fact that the children beg her to help, because she knows the family is rich and powerful and there is a sort of non-spoken agreement that these people can get away with anything, she does nothing...
Hope that makes any sense.
example: She knew Madeleine was suffering there, but one glance at her mother in the hall, arranging her gold necklace reminded her that it was nothing to worry about. She left the house with a positive written review that was left with no weight on her conscience, and out of pure \_\_\_\_\_\_\_\_\_\_. | 2016/08/12 | [
"https://english.stackexchange.com/questions/342393",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/190902/"
] | The behaviour of indulging the wrongdoing of authority is actually so common, that it is a person displaying the opposite behaviour who is called by a specific term: *whistleblower*.
Historically the failure to report a criminal offence was itself a criminal offence called *misprision*, but the term is now as archaic as the obligation.
A catch-all term nowadays would probably be a *collaborator*, which is capable of not only including those who actively assist or cover-up, but those who wilfully turn a blind eye, including through approval, blameworthy weakness of character, or a wrong ordering of moral priorities. | [myrmidon](http://www.merriam-webster.com/dictionary/myrmidon) - a person who executes without scruples his master's commands, like the teacher the chairman of our department kept reappointing to the personnel committee. |
342,393 | What's a word for someone who is generally good but might perform without a blink of an eye a sin of sorts, if it is for someone who is powerful, out of awe and admiration for that person and their name in society.
So for example a social worker who knows a family is treating their children badly but despite the fact that the children beg her to help, because she knows the family is rich and powerful and there is a sort of non-spoken agreement that these people can get away with anything, she does nothing...
Hope that makes any sense.
example: She knew Madeleine was suffering there, but one glance at her mother in the hall, arranging her gold necklace reminded her that it was nothing to worry about. She left the house with a positive written review that was left with no weight on her conscience, and out of pure \_\_\_\_\_\_\_\_\_\_. | 2016/08/12 | [
"https://english.stackexchange.com/questions/342393",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/190902/"
] | Check if ***sycophant(ic)*** fits.
Though it does not *explicitly* mean "*someone who is generally good*", it does mean someone who "*might perform without a blink of an eye a sin of sorts, if it is for someone who is powerful*". Also, the definition of ***sycophant*** does *not* explicitly exclude "*someone who is generally good*". You can also check one of the synonyms from ODO (reproduced below).
From [dictionary.cambridge.org](http://dictionary.cambridge.org/dictionary/english/sycophantic?q=sycophant):
>
> **sycophantic**
> *adjective*; *formal disapproving*
>
>
> (of a person or of behaviour) praising people in authority in a way that is not sincere, usually in
> order to get some advantage from them:
>
>
> There was sycophantic laughter
> from the audience at every one of his terrible jokes.
>
>
> **sycophant**
> *noun*
>
>
> The prime minister is surrounded by sycophants.
>
>
>
From [ODO](http://www.oxforddictionaries.com/definition/english/sycophant):
>
> **sycophant**
> *NOUN*
>
>
> A person who acts obsequiously towards someone important in order to
> gain advantage.
>
>
> Example sentences:
>
>
> An assortment of hatchet men, opportunists and sycophants gained
> access to the levers of power.
>
>
> There will be several servile sycophants who will come forward as
> ‘White Knights’ to regain their lost positions.
>
>
> Only the most sycophantic of the sycophants would even begin to make
> such a comparison. [In the past] there was at least a real enemy,
> there were real things to be done.
>
>
> **Synonyms**:
>
>
> toady, creep, crawler, fawner, flatterer, flunkey, truckler,
> groveller, doormat, lickspittle, kowtower, obsequious person, minion,
> hanger-on, leech, puppet, spaniel, Uriah Heep
>
>
> *informal* bootlicker, yes-man
>
>
> *vulgar slang* arse-licker, arse-kisser, brown-nose
>
>
> *North American vulgar slang* suckhole
>
>
> | That person can be considered *meek*
>
> quiet, gentle, and easily imposed on; submissive.
>
>
>
The action itself may be performed out of *cowardice*
>
> lack of bravery.
>
>
> |
342,393 | What's a word for someone who is generally good but might perform without a blink of an eye a sin of sorts, if it is for someone who is powerful, out of awe and admiration for that person and their name in society.
So for example a social worker who knows a family is treating their children badly but despite the fact that the children beg her to help, because she knows the family is rich and powerful and there is a sort of non-spoken agreement that these people can get away with anything, she does nothing...
Hope that makes any sense.
example: She knew Madeleine was suffering there, but one glance at her mother in the hall, arranging her gold necklace reminded her that it was nothing to worry about. She left the house with a positive written review that was left with no weight on her conscience, and out of pure \_\_\_\_\_\_\_\_\_\_. | 2016/08/12 | [
"https://english.stackexchange.com/questions/342393",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/190902/"
] | As a single-word-request, there might not be a perfect word that specifies "giving in to an authority".
More general words include
If the connotation is that the person doesn't want to do it but is doing it out of fear of reprecussions:
* *Impressionable*
* *Meek*
* *Weak-willed*
If the connotation is that the person is doing it because they have an agreement with the authority figure:
* *Corrupt*
* A *lackey* or *servant*
In your example, though you specify that the person has no weight on her conscience by her action of doing as the authority figure wants, which points to someone who isn't meek, but is more cold-hearted or unfeeling. In such context you might want to be more descriptive than a single word and specify why the person has no weight on her conscience.
"She left the house [...] and, out of pure **selfishness**, had no weight on her conscience because the repercussions of acting against the mother would have far outweighed any feeling of good-doing that helping Madeleine could have given her." | That person can be considered *meek*
>
> quiet, gentle, and easily imposed on; submissive.
>
>
>
The action itself may be performed out of *cowardice*
>
> lack of bravery.
>
>
> |
342,393 | What's a word for someone who is generally good but might perform without a blink of an eye a sin of sorts, if it is for someone who is powerful, out of awe and admiration for that person and their name in society.
So for example a social worker who knows a family is treating their children badly but despite the fact that the children beg her to help, because she knows the family is rich and powerful and there is a sort of non-spoken agreement that these people can get away with anything, she does nothing...
Hope that makes any sense.
example: She knew Madeleine was suffering there, but one glance at her mother in the hall, arranging her gold necklace reminded her that it was nothing to worry about. She left the house with a positive written review that was left with no weight on her conscience, and out of pure \_\_\_\_\_\_\_\_\_\_. | 2016/08/12 | [
"https://english.stackexchange.com/questions/342393",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/190902/"
] | The behaviour of indulging the wrongdoing of authority is actually so common, that it is a person displaying the opposite behaviour who is called by a specific term: *whistleblower*.
Historically the failure to report a criminal offence was itself a criminal offence called *misprision*, but the term is now as archaic as the obligation.
A catch-all term nowadays would probably be a *collaborator*, which is capable of not only including those who actively assist or cover-up, but those who wilfully turn a blind eye, including through approval, blameworthy weakness of character, or a wrong ordering of moral priorities. | That person can be considered *meek*
>
> quiet, gentle, and easily imposed on; submissive.
>
>
>
The action itself may be performed out of *cowardice*
>
> lack of bravery.
>
>
> |
12,178,769 | At the moment I have a form with a tChart control called tChart:..
```
Private Sub txtChart1_Click(sender As System.Object, e As System.EventArgs) Handles txtChart1.Click
TChart1.Series.Clear()
Dim series1 As New Steema.TeeChart.Chart
Dim FirstLabel = New Label()
FirstLabel.Name = "FirstLabel.Name"
FirstLabel.Text = " FirstLabel.Text"
Dim SecondLabel = New System.Windows.Forms.Label()
Dim GridBand = New Steema.TeeChart.Tools.GridBand()
'Main bar 1
Dim BarSeries1 = New Steema.TeeChart.Styles.Bar()
BarSeries1.Brush.Color = System.Drawing.Color.FromArgb(192, 255, 48)
BarSeries1.MultiBar = Steema.TeeChart.Styles.MultiBars.Stacked
BarSeries1.Pen.Color = Color.FromArgb(48, 255, 192)
BarSeries1.Title = "barSeries1"
BarSeries1.XValues.DataMember = "X"
BarSeries1.XValues.Order = Steema.TeeChart.Styles.ValueListOrder.Ascending
BarSeries1.YValues.DataMember = "Bar"
BarSeries1.Add({123, 123, 123, 123, 123})
TChart1.Series.Add(BarSeries1)
'Main bar 2
Dim BarSeries2 = New Steema.TeeChart.Styles.Bar()
BarSeries2.Brush.Color = System.Drawing.Color.FromArgb(48, 255, 192)
BarSeries2.MultiBar = Steema.TeeChart.Styles.MultiBars.Stacked
BarSeries2.Pen.Color = Color.FromArgb(48, 255, 192)
BarSeries2.Title = "barSeries2"
BarSeries2.XValues.DataMember = "X"
BarSeries2.XValues.Order = Steema.TeeChart.Styles.ValueListOrder.Ascending
BarSeries2.YValues.DataMember = "Bar"
BarSeries2.Add({123, 123, 123, 123, 123})
TChart1.Series.Add(BarSeries2)
TChart1.Aspect.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
End Sub
```
...in the same form class I have this event handler...
```
Private Sub TChart1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles TChart1.MouseDown
mouseX.Text = e.X
mouseY.Text = e.Y
If TChart1.Series.Count > 0 Then
Dim CollectionOfBars As New List(Of String)
For idxSeries As Integer = 0 To TChart1.Series.Count - 1
Dim srs As Steema.TeeChart.Styles.Bar = TChart1.Series(idxSeries)
If srs.BarBounds.Contains(e.X, e.Y) Then
CollectionOfBars.Add(srs.TitleOrName)
End If
Next
txtCollisions.Text = Join(CollectionOfBars.ToArray, ", ")
End If
End Sub
```
...but what it does is only work for the last stack of bars. I need something that will work for all bars.
Please help. | 2012/08/29 | [
"https://Stackoverflow.com/questions/12178769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1271898/"
] | It supports parallel running by specifying an property.
Parameters of Ant-contrib's `<for>` task:
>
> parallel
>
> If true, all iterations of the nested will execute in parallel. Defaults to false, which forces sequential execution of the iterations. It is up to the caller to ensure that parallel execution is safe.
>
>
> threadCount
>
> The maximum number of allowable threads when executing in parallel.
>
>
>
So if you can set `parallel="true"`. Please note that there is nothing to do with the nested `<sequential>` element, because the tasks inside `<sequential>` are still executed sequentially; by setting `parallel` parameter, you tell `<for>` tasks to execute multiple `<sequential>`s at the same time -- how many? It depends on the number of elements in your list, as well as the value of `threadCount`.
Please check
<http://ant-contrib.sourceforge.net/tasks/tasks/for.html>
to see all the parameters.
---
And for `<foreach>` task, it executes the specified target for each element in your list, or each file in the nested fileset. You can also use `parallel` property to make the execution parallel.
Check
<http://ant-contrib.sourceforge.net/tasks/tasks/foreach.html> | Here is the sample piece of code:
```
<for list="some_list" param="list_param" delimiter="any_delimiter" parallel="true">
<sequential>
...
</sequential>
</for>
``` |
13,099,252 | I want to know if there is a function in C library that convert a decimal to binary number and save number by number in a position on an array.
For example: 2 -> 10 -> array [0] = 0 array[1] = 1.
Thanks. | 2012/10/27 | [
"https://Stackoverflow.com/questions/13099252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1777068/"
] | here:
```
void dec2bin(int c)
{
int i = 0;
for(i = 31; i >= 0; i--){
if((c & (1 << i)) != 0){
printf("1");
}else{
printf("0");
}
}
}
```
But this only prints the value of an integer in binary format. All data is represented in binary format internally anyway. | the function should go like this:
```
int dec2bin(int n){
static int bin,osn=1,c;
if(n==0) return 0;
else {
c=n%2;
bin += c*osn;
osn*=10;
dec2bin(n/2);
}
return bin;
}
``` |
13,099,252 | I want to know if there is a function in C library that convert a decimal to binary number and save number by number in a position on an array.
For example: 2 -> 10 -> array [0] = 0 array[1] = 1.
Thanks. | 2012/10/27 | [
"https://Stackoverflow.com/questions/13099252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1777068/"
] | You did not define what is a decimal number for you. I am guessing it is character representation (e.g. in ASCII) of that number.
Notice that numbers are just numbers. Binary or decimal numbers do not exist, but a given number may have a binary, and a decimal, representation. Numbers are not made of digits!
Then you probably want [sscanf(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/scanf.3.html) or [strtol(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/strtol.3.html) pr `atoi` to convert a string to an integer (e.g. an `int` or a `long`), and [snprintf(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/sprintf.3.html) to convert an integer to a string.
If you want to convert a number to a binary string (with only `0` or `1` `char`-s in it) you need to code that conversion by yourself. To convert a binary string to some `long` use `strtol`. | Here is a version that explicitly uses a string buffer:
```
#include <string.h>
const char *str2bin(int num, char buffer[], const int BUFLEN)
{
(void) memset(buffer, '\0', BUFLEN );
int i = BUFLEN - 1; /* Index into buffer, running backwards. */
int r = 0; /* Remainder. */
char *p = &buffer[i - 1]; /* buffer[i] holds string terminator '\0'. */
while (( i >= 0 ) && ( num > 0 )) {
r = num % 2;
num = num / 2;
*p = r + '0';
i--;
p--;
}
return (p+1);
}
``` |
13,099,252 | I want to know if there is a function in C library that convert a decimal to binary number and save number by number in a position on an array.
For example: 2 -> 10 -> array [0] = 0 array[1] = 1.
Thanks. | 2012/10/27 | [
"https://Stackoverflow.com/questions/13099252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1777068/"
] | here:
```
void dec2bin(int c)
{
int i = 0;
for(i = 31; i >= 0; i--){
if((c & (1 << i)) != 0){
printf("1");
}else{
printf("0");
}
}
}
```
But this only prints the value of an integer in binary format. All data is represented in binary format internally anyway. | If it helps you can convert any decimal to binary using bitset library, for example:
```
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main(){
int decimal = 20;
bitset<5> binary20(decimal);
cout << binary20 << endl;
return 0;
}
```
So, you have an output like **10100**. Bitsets also have a "**toString()**" method for any purpose. |
13,099,252 | I want to know if there is a function in C library that convert a decimal to binary number and save number by number in a position on an array.
For example: 2 -> 10 -> array [0] = 0 array[1] = 1.
Thanks. | 2012/10/27 | [
"https://Stackoverflow.com/questions/13099252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1777068/"
] | You did not define what is a decimal number for you. I am guessing it is character representation (e.g. in ASCII) of that number.
Notice that numbers are just numbers. Binary or decimal numbers do not exist, but a given number may have a binary, and a decimal, representation. Numbers are not made of digits!
Then you probably want [sscanf(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/scanf.3.html) or [strtol(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/strtol.3.html) pr `atoi` to convert a string to an integer (e.g. an `int` or a `long`), and [snprintf(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/sprintf.3.html) to convert an integer to a string.
If you want to convert a number to a binary string (with only `0` or `1` `char`-s in it) you need to code that conversion by yourself. To convert a binary string to some `long` use `strtol`. | There is no such function in C standard library. Anyway, you can write your own:
```
void get_bin(int *dst, intmax_t x);
```
Where `dst` is the resulting array (with `1`s and `0`s), and `x` is the decimal number.
For example:
C89 version:
```
#include <limits.h>
void get_bin(int *dst, int x)
{
int i;
for (i = sizeof x * CHAR_BIT - 1; i >= 0; --i)
*dst++ = x >> i & 1;
}
```
C99 version:
```
/* C99 version */
#include <limits.h>
#include <stdint.h>
void get_bin(int *dst, intmax_t x)
{
for (intmax_t i = sizeof x * CHAR_BIT - 1; i >= 0; --i)
*dst++ = x >> i & 1;
}
```
It works as follow: we run through the binary representation of `x`, from left to right. The expression `(sizeof x * CHAR_BIT - 1)` give the number of bits of `x` - 1. Then, we get the value of each bit (`*dst++ = x >> i & 1`), and push it into the array.
Example of utilisation:
```
void get_bin(int *dst, int x)
{
int i;
for (i = sizeof x * CHAR_BIT - 1; i >= 0; --i)
*dst++ = x >> i & 1;
}
int main(void)
{
int buf[128]; /* binary number */
int n = 42; /* decimal number */
unsigned int i;
get_bin(buf, n);
for (i = 0; i < sizeof n * CHAR_BIT; ++i)
printf("%d", buf[i]);
return 0;
}
``` |
13,099,252 | I want to know if there is a function in C library that convert a decimal to binary number and save number by number in a position on an array.
For example: 2 -> 10 -> array [0] = 0 array[1] = 1.
Thanks. | 2012/10/27 | [
"https://Stackoverflow.com/questions/13099252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1777068/"
] | You did not define what is a decimal number for you. I am guessing it is character representation (e.g. in ASCII) of that number.
Notice that numbers are just numbers. Binary or decimal numbers do not exist, but a given number may have a binary, and a decimal, representation. Numbers are not made of digits!
Then you probably want [sscanf(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/scanf.3.html) or [strtol(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/strtol.3.html) pr `atoi` to convert a string to an integer (e.g. an `int` or a `long`), and [snprintf(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/sprintf.3.html) to convert an integer to a string.
If you want to convert a number to a binary string (with only `0` or `1` `char`-s in it) you need to code that conversion by yourself. To convert a binary string to some `long` use `strtol`. | As far as i know there is no such function in any C library. But here's a recursive function that returns a binary representation of a decimal number as int:
```
int dec2bin(int n)
{
if(n == 0) return 0;
return n % 2 + 10 * dec2bin(n / 2);
}
```
The max number that it can represent is 1023 (1111111111 in binary) because of *int* data type limit, but you can substitute *int* for *long long* data type to increase the range. Then, you can store the return value to array like this:
```
int array[100], i = 0;
int n = dec2bin(some_number);
do{
array[i] = n % 10;
n /= 10;
i++;
}while(n > 10)
```
I know this is an old post, but i hope this will still help somebody! |
13,099,252 | I want to know if there is a function in C library that convert a decimal to binary number and save number by number in a position on an array.
For example: 2 -> 10 -> array [0] = 0 array[1] = 1.
Thanks. | 2012/10/27 | [
"https://Stackoverflow.com/questions/13099252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1777068/"
] | There is no such function in C standard library. Anyway, you can write your own:
```
void get_bin(int *dst, intmax_t x);
```
Where `dst` is the resulting array (with `1`s and `0`s), and `x` is the decimal number.
For example:
C89 version:
```
#include <limits.h>
void get_bin(int *dst, int x)
{
int i;
for (i = sizeof x * CHAR_BIT - 1; i >= 0; --i)
*dst++ = x >> i & 1;
}
```
C99 version:
```
/* C99 version */
#include <limits.h>
#include <stdint.h>
void get_bin(int *dst, intmax_t x)
{
for (intmax_t i = sizeof x * CHAR_BIT - 1; i >= 0; --i)
*dst++ = x >> i & 1;
}
```
It works as follow: we run through the binary representation of `x`, from left to right. The expression `(sizeof x * CHAR_BIT - 1)` give the number of bits of `x` - 1. Then, we get the value of each bit (`*dst++ = x >> i & 1`), and push it into the array.
Example of utilisation:
```
void get_bin(int *dst, int x)
{
int i;
for (i = sizeof x * CHAR_BIT - 1; i >= 0; --i)
*dst++ = x >> i & 1;
}
int main(void)
{
int buf[128]; /* binary number */
int n = 42; /* decimal number */
unsigned int i;
get_bin(buf, n);
for (i = 0; i < sizeof n * CHAR_BIT; ++i)
printf("%d", buf[i]);
return 0;
}
``` | As far as i know there is no such function in any C library. But here's a recursive function that returns a binary representation of a decimal number as int:
```
int dec2bin(int n)
{
if(n == 0) return 0;
return n % 2 + 10 * dec2bin(n / 2);
}
```
The max number that it can represent is 1023 (1111111111 in binary) because of *int* data type limit, but you can substitute *int* for *long long* data type to increase the range. Then, you can store the return value to array like this:
```
int array[100], i = 0;
int n = dec2bin(some_number);
do{
array[i] = n % 10;
n /= 10;
i++;
}while(n > 10)
```
I know this is an old post, but i hope this will still help somebody! |
13,099,252 | I want to know if there is a function in C library that convert a decimal to binary number and save number by number in a position on an array.
For example: 2 -> 10 -> array [0] = 0 array[1] = 1.
Thanks. | 2012/10/27 | [
"https://Stackoverflow.com/questions/13099252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1777068/"
] | here:
```
void dec2bin(int c)
{
int i = 0;
for(i = 31; i >= 0; i--){
if((c & (1 << i)) != 0){
printf("1");
}else{
printf("0");
}
}
}
```
But this only prints the value of an integer in binary format. All data is represented in binary format internally anyway. | Use `char * itoa ( int value, char * str, int base );`
Find more [here](http://www.cplusplus.com/reference/cstdlib/itoa/) ... |
13,099,252 | I want to know if there is a function in C library that convert a decimal to binary number and save number by number in a position on an array.
For example: 2 -> 10 -> array [0] = 0 array[1] = 1.
Thanks. | 2012/10/27 | [
"https://Stackoverflow.com/questions/13099252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1777068/"
] | You did not define what is a decimal number for you. I am guessing it is character representation (e.g. in ASCII) of that number.
Notice that numbers are just numbers. Binary or decimal numbers do not exist, but a given number may have a binary, and a decimal, representation. Numbers are not made of digits!
Then you probably want [sscanf(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/scanf.3.html) or [strtol(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/strtol.3.html) pr `atoi` to convert a string to an integer (e.g. an `int` or a `long`), and [snprintf(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/sprintf.3.html) to convert an integer to a string.
If you want to convert a number to a binary string (with only `0` or `1` `char`-s in it) you need to code that conversion by yourself. To convert a binary string to some `long` use `strtol`. | If it helps you can convert any decimal to binary using bitset library, for example:
```
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main(){
int decimal = 20;
bitset<5> binary20(decimal);
cout << binary20 << endl;
return 0;
}
```
So, you have an output like **10100**. Bitsets also have a "**toString()**" method for any purpose. |
13,099,252 | I want to know if there is a function in C library that convert a decimal to binary number and save number by number in a position on an array.
For example: 2 -> 10 -> array [0] = 0 array[1] = 1.
Thanks. | 2012/10/27 | [
"https://Stackoverflow.com/questions/13099252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1777068/"
] | here:
```
void dec2bin(int c)
{
int i = 0;
for(i = 31; i >= 0; i--){
if((c & (1 << i)) != 0){
printf("1");
}else{
printf("0");
}
}
}
```
But this only prints the value of an integer in binary format. All data is represented in binary format internally anyway. | Here is a version that explicitly uses a string buffer:
```
#include <string.h>
const char *str2bin(int num, char buffer[], const int BUFLEN)
{
(void) memset(buffer, '\0', BUFLEN );
int i = BUFLEN - 1; /* Index into buffer, running backwards. */
int r = 0; /* Remainder. */
char *p = &buffer[i - 1]; /* buffer[i] holds string terminator '\0'. */
while (( i >= 0 ) && ( num > 0 )) {
r = num % 2;
num = num / 2;
*p = r + '0';
i--;
p--;
}
return (p+1);
}
``` |
13,099,252 | I want to know if there is a function in C library that convert a decimal to binary number and save number by number in a position on an array.
For example: 2 -> 10 -> array [0] = 0 array[1] = 1.
Thanks. | 2012/10/27 | [
"https://Stackoverflow.com/questions/13099252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1777068/"
] | You did not define what is a decimal number for you. I am guessing it is character representation (e.g. in ASCII) of that number.
Notice that numbers are just numbers. Binary or decimal numbers do not exist, but a given number may have a binary, and a decimal, representation. Numbers are not made of digits!
Then you probably want [sscanf(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/scanf.3.html) or [strtol(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/strtol.3.html) pr `atoi` to convert a string to an integer (e.g. an `int` or a `long`), and [snprintf(3)](http://www.kernel.org/doc/man-pages/online/pages/man3/sprintf.3.html) to convert an integer to a string.
If you want to convert a number to a binary string (with only `0` or `1` `char`-s in it) you need to code that conversion by yourself. To convert a binary string to some `long` use `strtol`. | the function should go like this:
```
int dec2bin(int n){
static int bin,osn=1,c;
if(n==0) return 0;
else {
c=n%2;
bin += c*osn;
osn*=10;
dec2bin(n/2);
}
return bin;
}
``` |
11,780,337 | I created a few PHP files for users of a popular hardware site to use to "Metro" their news posts. It works fairly well, you add the title of the article, links etc. and then it spits it out in Metro tile format.
Take a look: <http://briandempsey.org.uk/Newstool/index.php>
When the user submits, it uses the information provided to create the post. Now, I need to somehow use PHP or some other language to display the code that it generated underneath it so users can just copy and paste it. I'm not sure how to do this. | 2012/08/02 | [
"https://Stackoverflow.com/questions/11780337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1571793/"
] | ```
header('Content-Type: text/plain');
``` | Since you're passing your form data using the method GET, you could instead pass it to a page that creates a url to pull the html from...
**index.php** will have the form as you've shown above and will post to urlCreator.php.
**form.php** can be deleted as it is not needed anymore, the magic will happen in the urlCreator.php file.
**urlCreator.php** (NEW) will have code in it like so:
```
<?php
// urlCreator.php will get variables passed to it from index.php
// Now create the url using the passed variables
$url = "http://briandempsey.org.uk/Newstool/form.php?title=" . $_GET['title'] . "&color=" . $_GET['color'] . "&Articlecontent=" . $_GET['Articlecontent'] //and so on to build the whole url
//Now get the pages html
$html = file_get_contents($url);
?>
```
Now that you have the html in a variable you can clean it using str\_replace or manipulate it however you'd like.
```
<?php
// Still in urlCreator.php
// With the html in a variable you could now edit out the divs and echo the results
$html = str_replace("<div style=\"background-color: #008299; height: auto; width: 100%; margin-left: 10px;\">", "", $html); //removes the intro div
$html = str_replace("</div>", "", $html); //removes the closing div
//Finally echo out the html to the page for copy+paste purposes
echo $html;
?>
``` |
50,409,414 | Hello so i am trying to read lines from a txt file.
My code is the following:
```
import sys
accFiletypes = '.txt'
f = None
filnavn = None
correctFiletype = False
while (correctFiletype == False):
filnavn = input("Filename (Type exit to leave):")
if (filnavn.endswith(accFiletypes) == True):
try:
f = open(filnavn, 'r')
correctFiletype = True
print("File successfully opened!")
except IOError:
print("File is not existing")
elif (filnavn == "exit"):
sys.exit("Program closed")
else:
print("Accepted filetypes: " + accFiletypes)
line = f.readline
print(line())
print(line(2))
print(line(3))
print(line(4))
print(line(5))
print(line(6))
f.close()
```
This prints the following:
```
Filename (Type exit to leave):test.txt
File successfully opened!
0000 00000000
00
00
0000
1
0000 0
```
The first 10 lines in "test.txt"
```
0000 00000000
0000 00001
0000 00001111
0000 000099
0000 00009999
0000 0000w
0000 5927499
0000 634252
0000 6911703
0000 701068
```
I want it to print out the lines in the txt file but i prints something completely different. What do i do? | 2018/05/18 | [
"https://Stackoverflow.com/questions/50409414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8670650/"
] | This worked for me:
Include this in your imports:
```
from sqlalchemy import func
```
then:
```
total_passed = db.session.query(func.sum(ReportRecord.count)).scalar()
```
This returns **930** instead of **[(Decimal('930'),)]**
Read more about [.scalar()](https://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.scalar) | How about converting the decimal while querying it?
Try `int(func.sum(ReportRecord.count).label('total_passed'))`
try enforcing your db to cast values into integer should solve your problem
I cannot check but there is a cast function which might be useful as well
```
from sqlalchemy.sql.expression import cast
cast(func.sum(ReportRecord.count).label('total_passed'),sqlalchemy.Integer)
``` |
3,026,977 | I have a table with:
```
id | parameter
1 | A
1 | B
2 | A
3 | A
3 | B
```
That represent objects defined with the values as:
```
1 -> A,B
2 -> A
3 -> A,B
```
I want to count the number of objects with different parameters using a SQL query, so in this case it would be 2 unique objects as 1 and 3 have the same parameters.
There is no constraint on the number of parameters, there can be 0, or any other number.
The database is a Microsoft SQL Server 2000. But I do not mind knowing the solution for other databases. | 2010/06/12 | [
"https://Stackoverflow.com/questions/3026977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229414/"
] | If I understand correctly, you want the number of distinct *combinations* of `parameter`s per `id` represented in your table, possibly with the number of entities exhibiting each of those distinct combinations.
I can't speak for SQL Server, but under MySQL you could do something like this:
```
SELECT parameter_set, COUNT(*) AS entity_count
FROM (
-- Here we "flatten" the different parameter combinations per id
SELECT id,
GROUP_CONCAT(parameter ORDER BY parameter) AS parameter_set
FROM tbl
GROUP BY id
) d
GROUP BY parameter_set;
```
which will give you this:
```
parameter_set | entity_count
---------------+--------------
A,B | 2 -- two entities have params A, B
A | 1 -- one entity has param A
```
and `SELECT COUNT(DISTINCT parameter_set FROM (... flattening query ...)) d` will give you the number of distinct parameter sets. | You can use a `having` clause to filter for two unique parameters:
```
select count(*)
from YourTable
group by
id
having count(distinct parameter) > 1
``` |
3,026,977 | I have a table with:
```
id | parameter
1 | A
1 | B
2 | A
3 | A
3 | B
```
That represent objects defined with the values as:
```
1 -> A,B
2 -> A
3 -> A,B
```
I want to count the number of objects with different parameters using a SQL query, so in this case it would be 2 unique objects as 1 and 3 have the same parameters.
There is no constraint on the number of parameters, there can be 0, or any other number.
The database is a Microsoft SQL Server 2000. But I do not mind knowing the solution for other databases. | 2010/06/12 | [
"https://Stackoverflow.com/questions/3026977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229414/"
] | Okay, here's my attempt. It might be possible to implement this logic in a way that doesn't require 5 accesses to the same table, but I can't think of it right now.
The logic here is to first eliminate duplicate objects, then count the remaining IDs. The `NOT IN` subquery represents objects that have a matching object with a smaller ID. The subquery joins the parameters of two objects t1 and t2, then counts how many parameters matched for each t1/t2 pair. If the number of matching parameters is the same as the number of parameters in t1 and in t2, then t2 and t1 are matches and we should exclude t1 from the resultset.
```
DECLARE @tab TABLE (ID int, parameter varchar(2));
INSERT INTO @tab
SELECT 1, 'A' UNION ALL
SELECT 1, 'B' UNION ALL
SELECT 2, 'A' UNION ALL
SELECT 3, 'A' UNION ALL
SELECT 3, 'B' UNION ALL
SELECT 4, 'A' UNION ALL
SELECT 5, 'C' UNION ALL
SELECT 5, 'D';
SELECT
COUNT(DISTINCT t.ID) AS num_groups
FROM
@tab AS t
WHERE
t.ID NOT IN
(SELECT
t1.ID AS ID1
FROM
@tab AS t1
INNER JOIN
@tab AS t2
ON
t1.ID > t2.ID AND
t1.parameter = t2.parameter
GROUP BY
t1.ID,
t2.ID
HAVING
COUNT(*) = (SELECT COUNT(*) FROM @tab AS dupe WHERE dupe.ID = t1.ID) AND
COUNT(*) = (SELECT COUNT(*) FROM @tab AS dupe WHERE dupe.ID = t2.ID)
);
```
Result on SQL Server 2008 R2:
```
num_groups
3
```
As for objects with 0 parameters, it depends on how they're stored, but generally, you'd just need to add one to the answer above if there are any objects with 0 parameters. | You can use a `having` clause to filter for two unique parameters:
```
select count(*)
from YourTable
group by
id
having count(distinct parameter) > 1
``` |
3,026,977 | I have a table with:
```
id | parameter
1 | A
1 | B
2 | A
3 | A
3 | B
```
That represent objects defined with the values as:
```
1 -> A,B
2 -> A
3 -> A,B
```
I want to count the number of objects with different parameters using a SQL query, so in this case it would be 2 unique objects as 1 and 3 have the same parameters.
There is no constraint on the number of parameters, there can be 0, or any other number.
The database is a Microsoft SQL Server 2000. But I do not mind knowing the solution for other databases. | 2010/06/12 | [
"https://Stackoverflow.com/questions/3026977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229414/"
] | There is no foolproof way to do this in SQL Server 2000, with the conditions specified, but the following will work for most situations and it will warn you if it won't work.
Given table, "**tbl**":
```
ID Parameter
1 A
1 B
2 A
3 A
3 B
4 A
4 NULL
5 C
5 D
6 NULL
```
.
Create this function:
```
CREATE FUNCTION MakeParameterListFor_tblID (@ID INT)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE
@ParameterList VARCHAR(8000),
@ListLen INT
SET
@ParameterList = ''
SELECT
@ParameterList = @ParameterList + COALESCE (Parameter, '*null*') + ', '
FROM
tbl
WHERE
ID = @ID
ORDER BY
Parameter
SET @ListLen = LEN (@ParameterList)
IF @ListLen > 7800 -- 7800 is a SWAG.
SET @ParameterList = '*Caution: overflow!*' + @ParameterList
ELSE
SET @ParameterList = LEFT (@ParameterList, @ListLen-1) -- Kill trailing comma.
RETURN @ParameterList
END
GO
```
.
Then this query:
```
SELECT
COUNT (ID) AS NumIDs,
NumParams,
ParamList
FROM
(
SELECT
ID,
COUNT (Parameter) AS NumParams,
dbo.MakeParameterListFor_tblID (ID) AS ParamList
FROM
tbl
GROUP BY
ID
) AS ParamsByID
GROUP BY
ParamsByID.ParamList,
ParamsByID.NumParams
ORDER BY
NumIDs DESC,
NumParams DESC,
ParamList ASC
```
.
Will give what you asked for.
Results:
```
NumIDs NumParams ParamList
2 2 A, B
1 2 C, D
1 1 *null*, A
1 1 A
1 0 *null*
``` | You can use a `having` clause to filter for two unique parameters:
```
select count(*)
from YourTable
group by
id
having count(distinct parameter) > 1
``` |
3,026,977 | I have a table with:
```
id | parameter
1 | A
1 | B
2 | A
3 | A
3 | B
```
That represent objects defined with the values as:
```
1 -> A,B
2 -> A
3 -> A,B
```
I want to count the number of objects with different parameters using a SQL query, so in this case it would be 2 unique objects as 1 and 3 have the same parameters.
There is no constraint on the number of parameters, there can be 0, or any other number.
The database is a Microsoft SQL Server 2000. But I do not mind knowing the solution for other databases. | 2010/06/12 | [
"https://Stackoverflow.com/questions/3026977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229414/"
] | I resolved the problem with the link Cheran S provided (as Microsoft SQL Server still does not have a GROUP\_CONCAT() function)
<http://dataeducation.com/rowset-string-concatenation-which-method-is-best/> | You can use a `having` clause to filter for two unique parameters:
```
select count(*)
from YourTable
group by
id
having count(distinct parameter) > 1
``` |
3,026,977 | I have a table with:
```
id | parameter
1 | A
1 | B
2 | A
3 | A
3 | B
```
That represent objects defined with the values as:
```
1 -> A,B
2 -> A
3 -> A,B
```
I want to count the number of objects with different parameters using a SQL query, so in this case it would be 2 unique objects as 1 and 3 have the same parameters.
There is no constraint on the number of parameters, there can be 0, or any other number.
The database is a Microsoft SQL Server 2000. But I do not mind knowing the solution for other databases. | 2010/06/12 | [
"https://Stackoverflow.com/questions/3026977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229414/"
] | If I understand correctly, you want the number of distinct *combinations* of `parameter`s per `id` represented in your table, possibly with the number of entities exhibiting each of those distinct combinations.
I can't speak for SQL Server, but under MySQL you could do something like this:
```
SELECT parameter_set, COUNT(*) AS entity_count
FROM (
-- Here we "flatten" the different parameter combinations per id
SELECT id,
GROUP_CONCAT(parameter ORDER BY parameter) AS parameter_set
FROM tbl
GROUP BY id
) d
GROUP BY parameter_set;
```
which will give you this:
```
parameter_set | entity_count
---------------+--------------
A,B | 2 -- two entities have params A, B
A | 1 -- one entity has param A
```
and `SELECT COUNT(DISTINCT parameter_set FROM (... flattening query ...)) d` will give you the number of distinct parameter sets. | There is no foolproof way to do this in SQL Server 2000, with the conditions specified, but the following will work for most situations and it will warn you if it won't work.
Given table, "**tbl**":
```
ID Parameter
1 A
1 B
2 A
3 A
3 B
4 A
4 NULL
5 C
5 D
6 NULL
```
.
Create this function:
```
CREATE FUNCTION MakeParameterListFor_tblID (@ID INT)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE
@ParameterList VARCHAR(8000),
@ListLen INT
SET
@ParameterList = ''
SELECT
@ParameterList = @ParameterList + COALESCE (Parameter, '*null*') + ', '
FROM
tbl
WHERE
ID = @ID
ORDER BY
Parameter
SET @ListLen = LEN (@ParameterList)
IF @ListLen > 7800 -- 7800 is a SWAG.
SET @ParameterList = '*Caution: overflow!*' + @ParameterList
ELSE
SET @ParameterList = LEFT (@ParameterList, @ListLen-1) -- Kill trailing comma.
RETURN @ParameterList
END
GO
```
.
Then this query:
```
SELECT
COUNT (ID) AS NumIDs,
NumParams,
ParamList
FROM
(
SELECT
ID,
COUNT (Parameter) AS NumParams,
dbo.MakeParameterListFor_tblID (ID) AS ParamList
FROM
tbl
GROUP BY
ID
) AS ParamsByID
GROUP BY
ParamsByID.ParamList,
ParamsByID.NumParams
ORDER BY
NumIDs DESC,
NumParams DESC,
ParamList ASC
```
.
Will give what you asked for.
Results:
```
NumIDs NumParams ParamList
2 2 A, B
1 2 C, D
1 1 *null*, A
1 1 A
1 0 *null*
``` |
3,026,977 | I have a table with:
```
id | parameter
1 | A
1 | B
2 | A
3 | A
3 | B
```
That represent objects defined with the values as:
```
1 -> A,B
2 -> A
3 -> A,B
```
I want to count the number of objects with different parameters using a SQL query, so in this case it would be 2 unique objects as 1 and 3 have the same parameters.
There is no constraint on the number of parameters, there can be 0, or any other number.
The database is a Microsoft SQL Server 2000. But I do not mind knowing the solution for other databases. | 2010/06/12 | [
"https://Stackoverflow.com/questions/3026977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229414/"
] | If I understand correctly, you want the number of distinct *combinations* of `parameter`s per `id` represented in your table, possibly with the number of entities exhibiting each of those distinct combinations.
I can't speak for SQL Server, but under MySQL you could do something like this:
```
SELECT parameter_set, COUNT(*) AS entity_count
FROM (
-- Here we "flatten" the different parameter combinations per id
SELECT id,
GROUP_CONCAT(parameter ORDER BY parameter) AS parameter_set
FROM tbl
GROUP BY id
) d
GROUP BY parameter_set;
```
which will give you this:
```
parameter_set | entity_count
---------------+--------------
A,B | 2 -- two entities have params A, B
A | 1 -- one entity has param A
```
and `SELECT COUNT(DISTINCT parameter_set FROM (... flattening query ...)) d` will give you the number of distinct parameter sets. | I resolved the problem with the link Cheran S provided (as Microsoft SQL Server still does not have a GROUP\_CONCAT() function)
<http://dataeducation.com/rowset-string-concatenation-which-method-is-best/> |
3,026,977 | I have a table with:
```
id | parameter
1 | A
1 | B
2 | A
3 | A
3 | B
```
That represent objects defined with the values as:
```
1 -> A,B
2 -> A
3 -> A,B
```
I want to count the number of objects with different parameters using a SQL query, so in this case it would be 2 unique objects as 1 and 3 have the same parameters.
There is no constraint on the number of parameters, there can be 0, or any other number.
The database is a Microsoft SQL Server 2000. But I do not mind knowing the solution for other databases. | 2010/06/12 | [
"https://Stackoverflow.com/questions/3026977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229414/"
] | Okay, here's my attempt. It might be possible to implement this logic in a way that doesn't require 5 accesses to the same table, but I can't think of it right now.
The logic here is to first eliminate duplicate objects, then count the remaining IDs. The `NOT IN` subquery represents objects that have a matching object with a smaller ID. The subquery joins the parameters of two objects t1 and t2, then counts how many parameters matched for each t1/t2 pair. If the number of matching parameters is the same as the number of parameters in t1 and in t2, then t2 and t1 are matches and we should exclude t1 from the resultset.
```
DECLARE @tab TABLE (ID int, parameter varchar(2));
INSERT INTO @tab
SELECT 1, 'A' UNION ALL
SELECT 1, 'B' UNION ALL
SELECT 2, 'A' UNION ALL
SELECT 3, 'A' UNION ALL
SELECT 3, 'B' UNION ALL
SELECT 4, 'A' UNION ALL
SELECT 5, 'C' UNION ALL
SELECT 5, 'D';
SELECT
COUNT(DISTINCT t.ID) AS num_groups
FROM
@tab AS t
WHERE
t.ID NOT IN
(SELECT
t1.ID AS ID1
FROM
@tab AS t1
INNER JOIN
@tab AS t2
ON
t1.ID > t2.ID AND
t1.parameter = t2.parameter
GROUP BY
t1.ID,
t2.ID
HAVING
COUNT(*) = (SELECT COUNT(*) FROM @tab AS dupe WHERE dupe.ID = t1.ID) AND
COUNT(*) = (SELECT COUNT(*) FROM @tab AS dupe WHERE dupe.ID = t2.ID)
);
```
Result on SQL Server 2008 R2:
```
num_groups
3
```
As for objects with 0 parameters, it depends on how they're stored, but generally, you'd just need to add one to the answer above if there are any objects with 0 parameters. | There is no foolproof way to do this in SQL Server 2000, with the conditions specified, but the following will work for most situations and it will warn you if it won't work.
Given table, "**tbl**":
```
ID Parameter
1 A
1 B
2 A
3 A
3 B
4 A
4 NULL
5 C
5 D
6 NULL
```
.
Create this function:
```
CREATE FUNCTION MakeParameterListFor_tblID (@ID INT)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE
@ParameterList VARCHAR(8000),
@ListLen INT
SET
@ParameterList = ''
SELECT
@ParameterList = @ParameterList + COALESCE (Parameter, '*null*') + ', '
FROM
tbl
WHERE
ID = @ID
ORDER BY
Parameter
SET @ListLen = LEN (@ParameterList)
IF @ListLen > 7800 -- 7800 is a SWAG.
SET @ParameterList = '*Caution: overflow!*' + @ParameterList
ELSE
SET @ParameterList = LEFT (@ParameterList, @ListLen-1) -- Kill trailing comma.
RETURN @ParameterList
END
GO
```
.
Then this query:
```
SELECT
COUNT (ID) AS NumIDs,
NumParams,
ParamList
FROM
(
SELECT
ID,
COUNT (Parameter) AS NumParams,
dbo.MakeParameterListFor_tblID (ID) AS ParamList
FROM
tbl
GROUP BY
ID
) AS ParamsByID
GROUP BY
ParamsByID.ParamList,
ParamsByID.NumParams
ORDER BY
NumIDs DESC,
NumParams DESC,
ParamList ASC
```
.
Will give what you asked for.
Results:
```
NumIDs NumParams ParamList
2 2 A, B
1 2 C, D
1 1 *null*, A
1 1 A
1 0 *null*
``` |
3,026,977 | I have a table with:
```
id | parameter
1 | A
1 | B
2 | A
3 | A
3 | B
```
That represent objects defined with the values as:
```
1 -> A,B
2 -> A
3 -> A,B
```
I want to count the number of objects with different parameters using a SQL query, so in this case it would be 2 unique objects as 1 and 3 have the same parameters.
There is no constraint on the number of parameters, there can be 0, or any other number.
The database is a Microsoft SQL Server 2000. But I do not mind knowing the solution for other databases. | 2010/06/12 | [
"https://Stackoverflow.com/questions/3026977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/229414/"
] | Okay, here's my attempt. It might be possible to implement this logic in a way that doesn't require 5 accesses to the same table, but I can't think of it right now.
The logic here is to first eliminate duplicate objects, then count the remaining IDs. The `NOT IN` subquery represents objects that have a matching object with a smaller ID. The subquery joins the parameters of two objects t1 and t2, then counts how many parameters matched for each t1/t2 pair. If the number of matching parameters is the same as the number of parameters in t1 and in t2, then t2 and t1 are matches and we should exclude t1 from the resultset.
```
DECLARE @tab TABLE (ID int, parameter varchar(2));
INSERT INTO @tab
SELECT 1, 'A' UNION ALL
SELECT 1, 'B' UNION ALL
SELECT 2, 'A' UNION ALL
SELECT 3, 'A' UNION ALL
SELECT 3, 'B' UNION ALL
SELECT 4, 'A' UNION ALL
SELECT 5, 'C' UNION ALL
SELECT 5, 'D';
SELECT
COUNT(DISTINCT t.ID) AS num_groups
FROM
@tab AS t
WHERE
t.ID NOT IN
(SELECT
t1.ID AS ID1
FROM
@tab AS t1
INNER JOIN
@tab AS t2
ON
t1.ID > t2.ID AND
t1.parameter = t2.parameter
GROUP BY
t1.ID,
t2.ID
HAVING
COUNT(*) = (SELECT COUNT(*) FROM @tab AS dupe WHERE dupe.ID = t1.ID) AND
COUNT(*) = (SELECT COUNT(*) FROM @tab AS dupe WHERE dupe.ID = t2.ID)
);
```
Result on SQL Server 2008 R2:
```
num_groups
3
```
As for objects with 0 parameters, it depends on how they're stored, but generally, you'd just need to add one to the answer above if there are any objects with 0 parameters. | I resolved the problem with the link Cheran S provided (as Microsoft SQL Server still does not have a GROUP\_CONCAT() function)
<http://dataeducation.com/rowset-string-concatenation-which-method-is-best/> |
57,826,232 | I'd like to get the index and column name of the minimum value in a pandas DataFrame across all rows and all columns.
I've tried .idxmin but this seems to only work when applied on a column. Ideally the function is a one-liner that doesn't require loops. It seems like a very common problem, but I haven't found a solution yet.
My DataFrame:
```
col0, col1, col2
index0 1 2 3
index1 2 3 4
index2 5 6 7
```
I'd like to get the index and column for the minimum value across matrix: 1.
so:
```
some_func(df) = (index0,col0)
``` | 2019/09/06 | [
"https://Stackoverflow.com/questions/57826232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8326436/"
] | Try this:
```
df.stack().idxmin()
Out[108]: ('index0', 'col0')
``` | ### Numpy and `divmod`
```
i, j = divmod(np.argmin(np.ravel(df)), df.shape[1])
(df.index[i], df.columns[j])
('index0', 'col0')
``` |
2,650,955 | I have the following second-order linear differential equation that I am unable to solve: $y''+4y'+4y=t$. The method for solving homogeneous linear second-order differential equations obviously doesn't work, but I am unsure how to apply the technique to solve non-homogenous linear second-order differential equations because this equation has repeated roots. Is there a particular method I should be applying? | 2018/02/14 | [
"https://math.stackexchange.com/questions/2650955",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/295059/"
] | A particular solution is obviously a degree $1$ polynomial: $y\_0=at+b$. Since $y\_0'=a$ and $y\_0''=0$, the relation yields $4a+at+b=t$, that is, $a=1$ and $b=-4$.
For the general solution the general method *does* work! When the characteristic polynomial has a root $\lambda$ of multiplicity $m$, you get linearly independent solutions of the form $t^{k}e^{\lambda t}$, for $k=0,1,\dots,m-1$.
In this case, you get $y\_1=e^{-2t}$ and $y\_2=te^{-2t}$. | one solution is given by $$C\_1e^{-2t}$$ and you must for the second one $$C\_2te^{-2t}$$
since both solutions must be independend |
95,456 | How can I get all list items created or changed by the currently logged in user with [this function](http://www.plusconsulting.com/blog/2013/05/crud-on-list-items-using-rest-services-jquery/)? What's the correct query?
```
// Getting list items based on ODATA Query
function getListItems(url, listname, query, complete, failure) {
// Executing our colors ajax request
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
complete(data); // Returns JSON collection of the results
},
error: function (data) {
failure(data);
}
});
}
``` | 2014/04/07 | [
"https://sharepoint.stackexchange.com/questions/95456",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/13373/"
] | Use the [$filter](http://www.odata.org/developers/protocols/uri-conventions#FilterSystemQueryOption) query option with `Author` property to filter items by `Modified` field:
```
$filter=AuthorId eq <UserId>
```
How to retrieve current user via SharePoint REST API
----------------------------------------------------
If the current user is not determined, then it could be requested using the following method:
```
function getCurrentUser(url,complete, failure)
{
$.ajax({
url: url + "/_api/web/currentUser",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
complete(data.d);
},
error: function (data) {
failure(data);
}
});
}
```
Afterwards, you could retrieve my list items as demonstrated below.
Example: retrieve my list items using SharePoint REST API
```
function getMyListItems(url, listname,complete, failure) {
getCurrentUser(url,
function(user){
var query = '?$filter=AuthorId eq ' + user.Id;
getListItems(url,listname,query,complete,failure);
},
failure
);
}
```
References
----------
[Use OData query operations in SharePoint REST requests](http://msdn.microsoft.com/en-us/library/office/fp142385%28v=office.15%29.aspx) | ```
//Display items created by user id 1
var currentUserId = 1;
var url = SPAppWebUrl + "/_api/SP.AppContextSite(@target)" +
"/web/lists/getbytitle('" + listName + "')/items?$orderby=OfficeLocation,Department,FirstName&$filter=AuthorId eq " + currentUserId + "&" + "@target='" + SPHostUrl + "'";
$.ajax(
{
url: url,
type: "GET",
contentType: "application/json;odata=verbose",
headers: { "Accept": "application/json;odata=verbose" },
success: function (data) {
var result = data.d.results;
for (var i = 0; i < result.length; i++) {
alert(result[i].FirstName);
alert(result[i].LastName);
}
}
error: function (err) {
alert(JSON.stringify(err));
}
}
``` |
95,456 | How can I get all list items created or changed by the currently logged in user with [this function](http://www.plusconsulting.com/blog/2013/05/crud-on-list-items-using-rest-services-jquery/)? What's the correct query?
```
// Getting list items based on ODATA Query
function getListItems(url, listname, query, complete, failure) {
// Executing our colors ajax request
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
complete(data); // Returns JSON collection of the results
},
error: function (data) {
failure(data);
}
});
}
``` | 2014/04/07 | [
"https://sharepoint.stackexchange.com/questions/95456",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/13373/"
] | Use the [$filter](http://www.odata.org/developers/protocols/uri-conventions#FilterSystemQueryOption) query option with `Author` property to filter items by `Modified` field:
```
$filter=AuthorId eq <UserId>
```
How to retrieve current user via SharePoint REST API
----------------------------------------------------
If the current user is not determined, then it could be requested using the following method:
```
function getCurrentUser(url,complete, failure)
{
$.ajax({
url: url + "/_api/web/currentUser",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
complete(data.d);
},
error: function (data) {
failure(data);
}
});
}
```
Afterwards, you could retrieve my list items as demonstrated below.
Example: retrieve my list items using SharePoint REST API
```
function getMyListItems(url, listname,complete, failure) {
getCurrentUser(url,
function(user){
var query = '?$filter=AuthorId eq ' + user.Id;
getListItems(url,listname,query,complete,failure);
},
failure
);
}
```
References
----------
[Use OData query operations in SharePoint REST requests](http://msdn.microsoft.com/en-us/library/office/fp142385%28v=office.15%29.aspx) | I don't believe there is much you can do since the list only stores the User Id. Rather than querying the UserInformationList for the Id, you can grab it from **\_spPageContextInfo** if you are doing this from the client side.
```
<script type="text/javascript">
$(document).ready( function(){
var userId = _spPageContextInfo.userId;
var restURL = url + "?$filter=AuthorId eq " + userId;
$.ajax({
dataType: "json",
url: restURL,
success: function(data) {
//iterate through json objects and output 'my items' to a table
}
});
});
</script>
``` |
95,456 | How can I get all list items created or changed by the currently logged in user with [this function](http://www.plusconsulting.com/blog/2013/05/crud-on-list-items-using-rest-services-jquery/)? What's the correct query?
```
// Getting list items based on ODATA Query
function getListItems(url, listname, query, complete, failure) {
// Executing our colors ajax request
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
complete(data); // Returns JSON collection of the results
},
error: function (data) {
failure(data);
}
});
}
``` | 2014/04/07 | [
"https://sharepoint.stackexchange.com/questions/95456",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/13373/"
] | I don't believe there is much you can do since the list only stores the User Id. Rather than querying the UserInformationList for the Id, you can grab it from **\_spPageContextInfo** if you are doing this from the client side.
```
<script type="text/javascript">
$(document).ready( function(){
var userId = _spPageContextInfo.userId;
var restURL = url + "?$filter=AuthorId eq " + userId;
$.ajax({
dataType: "json",
url: restURL,
success: function(data) {
//iterate through json objects and output 'my items' to a table
}
});
});
</script>
``` | ```
//Display items created by user id 1
var currentUserId = 1;
var url = SPAppWebUrl + "/_api/SP.AppContextSite(@target)" +
"/web/lists/getbytitle('" + listName + "')/items?$orderby=OfficeLocation,Department,FirstName&$filter=AuthorId eq " + currentUserId + "&" + "@target='" + SPHostUrl + "'";
$.ajax(
{
url: url,
type: "GET",
contentType: "application/json;odata=verbose",
headers: { "Accept": "application/json;odata=verbose" },
success: function (data) {
var result = data.d.results;
for (var i = 0; i < result.length; i++) {
alert(result[i].FirstName);
alert(result[i].LastName);
}
}
error: function (err) {
alert(JSON.stringify(err));
}
}
``` |
108,798 | Original question: [How do I create an in-memory handle in Haskell?](https://stackoverflow.com/questions/60569/how-do-i-create-an-in-memory-handle-in-haskell)
This was asked two years ago; at the time, the answer was "not possible due to library limitations". However, since then the limitations have been fixed, and I wrote a library which solves the original problem.
I added an answer with a link, but since it's down at the bottom it will probably never be seen.
Is it OK to edit the accepted answer to point to my library? | 2011/10/09 | [
"https://meta.stackexchange.com/questions/108798",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/170495/"
] | No, you shouldn't ever do this. I know that answer *might* be wrong but it shouldn't be edited from
```
You can't
```
to
```
You can
```
Just give OP some time to reaccept other answer (he was last seen 2 days ago). | Normally, I'd say "yes". And I'd still say *someone* should edit the answer, if it is indeed now incorrect and the asker doesn't respond by changing the accepted answer.
But you should probably avoid editing in a link to your own project, simply to avoid the appearance of impropriety. Leave a comment if you're concerned someone might miss your answer. |
557,678 | I have a web server running CentOS. I didn't pay attention when I installed it, but now the system running out disk space. I have to check it everyday to delete some unimportant stuffs to make enough space to the system to work. But I think that the server has two hard drives by running the command: fdisk -l , with outputs:
```
Disk /dev/sda: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x345698d9
Device Boot Start End Blocks Id System
/dev/sda1 * 1 39 307200 83 Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2 39 137 786432 82 Linux swap / Solaris
Partition 2 does not end on cylinder boundary.
Disk /dev/sdb: 250.1 GB, 250059350016 bytes
255 heads, 63 sectors/track, 30401 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x4cfa1f2d
Device Boot Start End Blocks Id System
/dev/sdb1 1 30402 244197376 83 Linux
```
I don't really understand the above outputs. I got some questions:
Does the system has 2 HDs? and which one is being used and which one is not?
If the one is not in use, Can I combine it with the main disk to make the system disk space bigger?
For more infomation, when I run the command: df -hT, the output are:
```
Filesystem Type Size Used Avail Use% Mounted on
/dev/sdb1 ext4 230G 152G 66G 70% /
tmpfs tmpfs 1.9G 0 1.9G 0% /dev/shm
/dev/sda1 ext4 291M 33M 244M 12% /boot
```
Please help! | 2013/11/26 | [
"https://serverfault.com/questions/557678",
"https://serverfault.com",
"https://serverfault.com/users/200658/"
] | >
> Does the system has 2 HDs?
>
>
>
Yes you appear to have a 160GB drive and a 250GB drive
>
> and which one is being used and which one is not?
>
>
>
Both are being used. the 160GB has a small boot partition(sda1), and a small swap partition(sda2) and a huge amount of free space. The 250GB drive has the root filesystem (sdb1).
>
> If the one is not in use, Can I combine it with the main disk to make the system disk space bigger?
>
>
>
You can, but it would take re-installing. You could also just create another partition and filesystem on that 160GB drive, and mount it somewhere and move some of your data do it. Without knowing exactly how your data is distributed through your disk I can't make any recommendations about where exactly you would mount it. Running `du -h /` would give would give you an good idea.
You might for example create a filesystem for `/var/log`. It should be easy enough to create this partition/filesystem and move content to it without majorly interrupting things. | I think you are looking for LVM. Take a look here:
<http://ostechnix.wordpress.com/2013/02/03/linux-basics-lvm-logical-volume-manager-tutorial/>
At the moment, partition 1 on your first hard disk /dev/sda seems to be used for the /boot partition while partition 1 on your second hard disk /dev/sdb is used for /. |
557,678 | I have a web server running CentOS. I didn't pay attention when I installed it, but now the system running out disk space. I have to check it everyday to delete some unimportant stuffs to make enough space to the system to work. But I think that the server has two hard drives by running the command: fdisk -l , with outputs:
```
Disk /dev/sda: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x345698d9
Device Boot Start End Blocks Id System
/dev/sda1 * 1 39 307200 83 Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2 39 137 786432 82 Linux swap / Solaris
Partition 2 does not end on cylinder boundary.
Disk /dev/sdb: 250.1 GB, 250059350016 bytes
255 heads, 63 sectors/track, 30401 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x4cfa1f2d
Device Boot Start End Blocks Id System
/dev/sdb1 1 30402 244197376 83 Linux
```
I don't really understand the above outputs. I got some questions:
Does the system has 2 HDs? and which one is being used and which one is not?
If the one is not in use, Can I combine it with the main disk to make the system disk space bigger?
For more infomation, when I run the command: df -hT, the output are:
```
Filesystem Type Size Used Avail Use% Mounted on
/dev/sdb1 ext4 230G 152G 66G 70% /
tmpfs tmpfs 1.9G 0 1.9G 0% /dev/shm
/dev/sda1 ext4 291M 33M 244M 12% /boot
```
Please help! | 2013/11/26 | [
"https://serverfault.com/questions/557678",
"https://serverfault.com",
"https://serverfault.com/users/200658/"
] | >
> Does the system has 2 HDs?
>
>
>
Yes you appear to have a 160GB drive and a 250GB drive
>
> and which one is being used and which one is not?
>
>
>
Both are being used. the 160GB has a small boot partition(sda1), and a small swap partition(sda2) and a huge amount of free space. The 250GB drive has the root filesystem (sdb1).
>
> If the one is not in use, Can I combine it with the main disk to make the system disk space bigger?
>
>
>
You can, but it would take re-installing. You could also just create another partition and filesystem on that 160GB drive, and mount it somewhere and move some of your data do it. Without knowing exactly how your data is distributed through your disk I can't make any recommendations about where exactly you would mount it. Running `du -h /` would give would give you an good idea.
You might for example create a filesystem for `/var/log`. It should be easy enough to create this partition/filesystem and move content to it without majorly interrupting things. | You currently only have 1 Drive and 2 partitions.
For future expansion, consider using LVM or RAID based setups like X-RAID, RAID0,5,6,10 JBOD, ect... which allows you to clump a bunch of disks as one. |
26,948 | At risk of sounding like the over-pushy head mistress from Daddy Daycare....
My wife and I are both monolingual Brits, living Britain, with a four-month old daughter. It seems a shame to waste this early stage (or perhaps the near future stage) when children are able to absorb language skills so quickly. Is there a gentle way to introduce some foreign language skills to our daughter now that would help her to enjoy a greater aptitude for learning languages later in life? I don't expect that our daughter will be fully bilingual, but could there be something in between raising a bilingual kid and not bothering at all? Foreign babysitter? Foreign children's movies? | 2016/08/27 | [
"https://parenting.stackexchange.com/questions/26948",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/20399/"
] | I'd recommend the foreign babysitter option. You'll want her to come on a regular basis, several hours a week at least, and you'll want her to speak to the child exclusively or almost exclusively in her own language. Make it clear that you want her just to speak the language, and not to attempt to teach it to the child; children don't learn languages natively the way they learn them in classrooms later on.
The child will probably speak back to her in English, and that's okay. She'll still learn to hear the sounds, which it more than half the battle of being able to speak them later on.
Perhaps more importantly, she'll learn at a fundamental level about the difference between meanings and words, since different languages use different words for the same meaning. This is thought to provide mental flexibility which can be highly useful even if she never actually learns a foreign language to a functional level. | Congratulation, you will give a precious gift to your child.
Children of that age learn by listening, **only by listening**. Before reaching 7 years old their acoustic filters are not fixed by one particular language yet. The *gentle way*, in your situation, is a **foreign nanny**, **movies or tv programs** plus **listening to music** in that second language you want your child to learn.
I speak by experience. My daughter, now 16, is almost bilingual, studying spanish as third language and actually starting to learn gaelic, for fun. How come? Because we spoke to her in three languages until 6 years old. We listened to music in five or six different language, just for the sounds. Learning a language is easy and fun, once you understand how it works. Check the link to Tomatis centers.
My suggestion, besides movies, music and the **fluent** nanny. Why not start learning a new language at home with an immigrant teacher. You, your wife and the child. Start learning mandarin or russian with an fluent immigrant. These languages have a very large frequency bandwith and **listening to large frequency bands** is the key to early learning.
Check [this link](http://europsycenter.ru/en/foreign-languages-tomatis) about frequency bands and language learning.
p.s. The **fluency in a language is a must to teach** young children. For an adult it is not as important to be perfectly fluent. |
26,948 | At risk of sounding like the over-pushy head mistress from Daddy Daycare....
My wife and I are both monolingual Brits, living Britain, with a four-month old daughter. It seems a shame to waste this early stage (or perhaps the near future stage) when children are able to absorb language skills so quickly. Is there a gentle way to introduce some foreign language skills to our daughter now that would help her to enjoy a greater aptitude for learning languages later in life? I don't expect that our daughter will be fully bilingual, but could there be something in between raising a bilingual kid and not bothering at all? Foreign babysitter? Foreign children's movies? | 2016/08/27 | [
"https://parenting.stackexchange.com/questions/26948",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/20399/"
] | Congratulation, you will give a precious gift to your child.
Children of that age learn by listening, **only by listening**. Before reaching 7 years old their acoustic filters are not fixed by one particular language yet. The *gentle way*, in your situation, is a **foreign nanny**, **movies or tv programs** plus **listening to music** in that second language you want your child to learn.
I speak by experience. My daughter, now 16, is almost bilingual, studying spanish as third language and actually starting to learn gaelic, for fun. How come? Because we spoke to her in three languages until 6 years old. We listened to music in five or six different language, just for the sounds. Learning a language is easy and fun, once you understand how it works. Check the link to Tomatis centers.
My suggestion, besides movies, music and the **fluent** nanny. Why not start learning a new language at home with an immigrant teacher. You, your wife and the child. Start learning mandarin or russian with an fluent immigrant. These languages have a very large frequency bandwith and **listening to large frequency bands** is the key to early learning.
Check [this link](http://europsycenter.ru/en/foreign-languages-tomatis) about frequency bands and language learning.
p.s. The **fluency in a language is a must to teach** young children. For an adult it is not as important to be perfectly fluent. | My boss at a previous employer was Japanese, his wife was American, they lived in Germany, and so their 3 sons were already fluent in English and German and had a good grasp of Japanese. My boss decided to send them to a French-speaking school. According to my boss, they picked up French pretty quickly and didn't have any further problems. I don't know how it worked out long term for them - hopefully fine!
That's just an interesting example that I thought I'd throw in there - as for my opinion, it's based on my partner's and my efforts to bring up our children bi-lingual in German and English in the UK. The kids are 6 and 4 and so far, so good. At the moment after spending 2 weeks in Germany, they are chatting fluently in German with each other. We do notice that they lag slightly in English behind the 2 or 3 bright kids in their school and nursery classes who we have decided are the 'reference' English children we compare our with. Apparently this disadvantage disappears once their vocabulary has matured.
The nursery linguistics expert talked to us about non-English mother-tongue children and gave us her opinion that confirms what some of the other answers say. Apparently as they learnt to talk themselves, hearing 2nd or 3rd languages is very beneficial. She also told us that to gain fluency, the child should be exposed to the 2nd language for at least 40 hours per week.
My partner and I achieved this by making German our house language - even though mine is a bit poor. I was dubious about the benefit I was bringing with my German, but it seemed to help. My daughter now corrects my German!
Again as others say, songs, audio books and TV are all useful and helped us achieve that 40 hour mark.
For me, it was clear that my partner's mother tongue was the 2nd language of choice (in fact it is competing to be the 1st language) but for you as monolingual people, I would recommend taking the plunge yourselves and learning a second language too. You could find a lot of synergies in the efforts you are making for your child - you could read books for her in that language yourself, you could go along to foreign-language play groups and actually converse in that language yourselves with the adults there, you could go on holiday to that country and actually get by with the locals etc etc.
By the way, with all this concentration on language, don't forget how beneficial to mental development music is too. So give her a bit of Brahms or Chopin in between the French / German / Mandarin....
Good luck! |
26,948 | At risk of sounding like the over-pushy head mistress from Daddy Daycare....
My wife and I are both monolingual Brits, living Britain, with a four-month old daughter. It seems a shame to waste this early stage (or perhaps the near future stage) when children are able to absorb language skills so quickly. Is there a gentle way to introduce some foreign language skills to our daughter now that would help her to enjoy a greater aptitude for learning languages later in life? I don't expect that our daughter will be fully bilingual, but could there be something in between raising a bilingual kid and not bothering at all? Foreign babysitter? Foreign children's movies? | 2016/08/27 | [
"https://parenting.stackexchange.com/questions/26948",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/20399/"
] | I'd recommend the foreign babysitter option. You'll want her to come on a regular basis, several hours a week at least, and you'll want her to speak to the child exclusively or almost exclusively in her own language. Make it clear that you want her just to speak the language, and not to attempt to teach it to the child; children don't learn languages natively the way they learn them in classrooms later on.
The child will probably speak back to her in English, and that's okay. She'll still learn to hear the sounds, which it more than half the battle of being able to speak them later on.
Perhaps more importantly, she'll learn at a fundamental level about the difference between meanings and words, since different languages use different words for the same meaning. This is thought to provide mental flexibility which can be highly useful even if she never actually learns a foreign language to a functional level. | I've recently came across a [TED talk](https://www.ted.com/talks/patricia_kuhl_the_linguistic_genius_of_babies?language=en) about this subject which probably answers some of your questions. I suggest you watching the whole talk, but here are the key things:
* Children are generally brilliant at learning languages until the age
of 7. After puberty it takes much more effort.
* The critical period for **sound development** is under the age of 1. This is where babies learn to differentiate between the noise and the sounds of their language. So exposing them to different languages even at this young age sounds like a good idea.
* However exposure to **TV or video does not help in this period**. The social interaction that is crucial in this process cannot be replaced.
I'd like to emphasise the last point here, as this will probably narrow down your possibilities, but overall to me it seems like a good idea to expose babies to a second language. |
26,948 | At risk of sounding like the over-pushy head mistress from Daddy Daycare....
My wife and I are both monolingual Brits, living Britain, with a four-month old daughter. It seems a shame to waste this early stage (or perhaps the near future stage) when children are able to absorb language skills so quickly. Is there a gentle way to introduce some foreign language skills to our daughter now that would help her to enjoy a greater aptitude for learning languages later in life? I don't expect that our daughter will be fully bilingual, but could there be something in between raising a bilingual kid and not bothering at all? Foreign babysitter? Foreign children's movies? | 2016/08/27 | [
"https://parenting.stackexchange.com/questions/26948",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/20399/"
] | I'd recommend the foreign babysitter option. You'll want her to come on a regular basis, several hours a week at least, and you'll want her to speak to the child exclusively or almost exclusively in her own language. Make it clear that you want her just to speak the language, and not to attempt to teach it to the child; children don't learn languages natively the way they learn them in classrooms later on.
The child will probably speak back to her in English, and that's okay. She'll still learn to hear the sounds, which it more than half the battle of being able to speak them later on.
Perhaps more importantly, she'll learn at a fundamental level about the difference between meanings and words, since different languages use different words for the same meaning. This is thought to provide mental flexibility which can be highly useful even if she never actually learns a foreign language to a functional level. | My boss at a previous employer was Japanese, his wife was American, they lived in Germany, and so their 3 sons were already fluent in English and German and had a good grasp of Japanese. My boss decided to send them to a French-speaking school. According to my boss, they picked up French pretty quickly and didn't have any further problems. I don't know how it worked out long term for them - hopefully fine!
That's just an interesting example that I thought I'd throw in there - as for my opinion, it's based on my partner's and my efforts to bring up our children bi-lingual in German and English in the UK. The kids are 6 and 4 and so far, so good. At the moment after spending 2 weeks in Germany, they are chatting fluently in German with each other. We do notice that they lag slightly in English behind the 2 or 3 bright kids in their school and nursery classes who we have decided are the 'reference' English children we compare our with. Apparently this disadvantage disappears once their vocabulary has matured.
The nursery linguistics expert talked to us about non-English mother-tongue children and gave us her opinion that confirms what some of the other answers say. Apparently as they learnt to talk themselves, hearing 2nd or 3rd languages is very beneficial. She also told us that to gain fluency, the child should be exposed to the 2nd language for at least 40 hours per week.
My partner and I achieved this by making German our house language - even though mine is a bit poor. I was dubious about the benefit I was bringing with my German, but it seemed to help. My daughter now corrects my German!
Again as others say, songs, audio books and TV are all useful and helped us achieve that 40 hour mark.
For me, it was clear that my partner's mother tongue was the 2nd language of choice (in fact it is competing to be the 1st language) but for you as monolingual people, I would recommend taking the plunge yourselves and learning a second language too. You could find a lot of synergies in the efforts you are making for your child - you could read books for her in that language yourself, you could go along to foreign-language play groups and actually converse in that language yourselves with the adults there, you could go on holiday to that country and actually get by with the locals etc etc.
By the way, with all this concentration on language, don't forget how beneficial to mental development music is too. So give her a bit of Brahms or Chopin in between the French / German / Mandarin....
Good luck! |
26,948 | At risk of sounding like the over-pushy head mistress from Daddy Daycare....
My wife and I are both monolingual Brits, living Britain, with a four-month old daughter. It seems a shame to waste this early stage (or perhaps the near future stage) when children are able to absorb language skills so quickly. Is there a gentle way to introduce some foreign language skills to our daughter now that would help her to enjoy a greater aptitude for learning languages later in life? I don't expect that our daughter will be fully bilingual, but could there be something in between raising a bilingual kid and not bothering at all? Foreign babysitter? Foreign children's movies? | 2016/08/27 | [
"https://parenting.stackexchange.com/questions/26948",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/20399/"
] | I've recently came across a [TED talk](https://www.ted.com/talks/patricia_kuhl_the_linguistic_genius_of_babies?language=en) about this subject which probably answers some of your questions. I suggest you watching the whole talk, but here are the key things:
* Children are generally brilliant at learning languages until the age
of 7. After puberty it takes much more effort.
* The critical period for **sound development** is under the age of 1. This is where babies learn to differentiate between the noise and the sounds of their language. So exposing them to different languages even at this young age sounds like a good idea.
* However exposure to **TV or video does not help in this period**. The social interaction that is crucial in this process cannot be replaced.
I'd like to emphasise the last point here, as this will probably narrow down your possibilities, but overall to me it seems like a good idea to expose babies to a second language. | My boss at a previous employer was Japanese, his wife was American, they lived in Germany, and so their 3 sons were already fluent in English and German and had a good grasp of Japanese. My boss decided to send them to a French-speaking school. According to my boss, they picked up French pretty quickly and didn't have any further problems. I don't know how it worked out long term for them - hopefully fine!
That's just an interesting example that I thought I'd throw in there - as for my opinion, it's based on my partner's and my efforts to bring up our children bi-lingual in German and English in the UK. The kids are 6 and 4 and so far, so good. At the moment after spending 2 weeks in Germany, they are chatting fluently in German with each other. We do notice that they lag slightly in English behind the 2 or 3 bright kids in their school and nursery classes who we have decided are the 'reference' English children we compare our with. Apparently this disadvantage disappears once their vocabulary has matured.
The nursery linguistics expert talked to us about non-English mother-tongue children and gave us her opinion that confirms what some of the other answers say. Apparently as they learnt to talk themselves, hearing 2nd or 3rd languages is very beneficial. She also told us that to gain fluency, the child should be exposed to the 2nd language for at least 40 hours per week.
My partner and I achieved this by making German our house language - even though mine is a bit poor. I was dubious about the benefit I was bringing with my German, but it seemed to help. My daughter now corrects my German!
Again as others say, songs, audio books and TV are all useful and helped us achieve that 40 hour mark.
For me, it was clear that my partner's mother tongue was the 2nd language of choice (in fact it is competing to be the 1st language) but for you as monolingual people, I would recommend taking the plunge yourselves and learning a second language too. You could find a lot of synergies in the efforts you are making for your child - you could read books for her in that language yourself, you could go along to foreign-language play groups and actually converse in that language yourselves with the adults there, you could go on holiday to that country and actually get by with the locals etc etc.
By the way, with all this concentration on language, don't forget how beneficial to mental development music is too. So give her a bit of Brahms or Chopin in between the French / German / Mandarin....
Good luck! |
5,167,025 | >
> **Possible Duplicate:**
>
> [In SQL server is there any way to get the 'use database' command to accept a variable](https://stackoverflow.com/questions/969046/in-sql-server-is-there-any-way-to-get-the-use-database-command-to-accept-a-var)
>
>
>
We can change the database by their name is no problem as below
```
USE master
GO
```
But I need this in a script and have the database name in a variable. How to make this?
```
select @cmd = N'use ' + @oldDb + N';'
exec sp_executesql @cmd
```
That doesn't work - the current database stays the same after the execution.
Is something possible at all? | 2011/03/02 | [
"https://Stackoverflow.com/questions/5167025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/248616/"
] | Apparently the problem is with using GO within a dynamic sql statement, because execute sql doesn't support multiple batches. Please see this link for the solution. [Change Database with Dynamic SQL](http://ask.sqlservercentral.com/questions/3974/database-use-issues-with-dynamic-sql) | Perhaps there's a valid reason for this, but if possible I would recommend naming the DB by name in your script where required. for example
databasename.table.owner.field |
54,591,724 | In my karate tests i need to write response id's to txt files (or any other file format such as JSON), was wondering if it has any capability to do this, I haven't seen otherwise in the documentation. In the case of no, is there a simple JavaScript function to do so? | 2019/02/08 | [
"https://Stackoverflow.com/questions/54591724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7261723/"
] | Try the [`karate.write(value, filename)`](https://github.com/karatelabs/karate#karate-write) API but we don't encourage it. Also the file will be written only to the current "build" directory which will be `target` for Maven projects / stand-alone JAR.
`value` can be any data-type, and Karate will write the bytes (or plain-text) out. There is no built-in support for any other format.
Here is an [example](https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/embed/embed-pdf.js).
EDIT: for others coming across this answer in the future the right thing to do is:
1. don't write files in the first place, you never need to do this, and this question is typically asked by inexperienced folks who for some reason think that the only way to "save" a response before validation is to write it to a file. No, please don't waste your time - and please just `match` against the `response`. You can save it (or parts of it) to variables while you make other HTTP requests. And do not write your tests so that scenarios (or features) depend on other scenarios, this is a [very bad practice](https://stackoverflow.com/a/46080568/143475). Also note that by default, Karate will dump all HTTP requests and responses in the log file (typically in `target/karate.log`) and also in the HTML report.
2. see if `karate.write()` works for you as per this answer
3. write a custom Java (or JS function that uses the JVM) to do what you want using [Java interop](https://github.com/intuit/karate#calling-java)
Also note that you can use [`karate.toCsv()`](https://github.com/karatelabs/karate#karate-tocsv) to convert JSON into CSV if needed. | My justification for writing to a file is a different one. I am using karate explicitly to implement a mock. I want to expose an endpoint wherein the upstream system will send some basic data through json payload using POST/PUT method and karate will construct the subsequent payload file and stores it the specific folder, and this newly created payload file will be exposed through another GET call. |
42,038 | I'm new to cryptography. While reading about symmetric key encryption, it was mentioned that it requires secret key exchange so that 2 parties can decrypt the ciphertext.
Now, using some encryption software like GPG, we can use symmetric encryption by `gpg --symmetric abc.txt`
It asks for password there.
Is the key generated using the password?
Can I actually see the secret key if I want to?
Symmetric key cryptography requires secure key exchange. But in real world the 'key' itself is not exchanged right? Instead the password should be securely exchanged right?
Also, is the key actually present in the ciphertext & unlocked by the password or is it generated on-the-spot when we give our password?
Thank you! | 2013/09/08 | [
"https://security.stackexchange.com/questions/42038",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/30534/"
] | >
> Is the key generated using the password?
>
>
>
Yes. In this sort of scenario, the password is run through a key derivation function ([KDF](http://en.wikipedia.org/wiki/Key_derivation_function)) such as [PBKDF2](http://en.wikipedia.org/wiki/PBKDF2) to generate the key.
>
> Can I actually see the secret key if I want to?
>
>
>
AFAIK, the symmetric key in this case is not stored anywhere. Instead, the key is derived from the password each and every time you want to encrypt or decrypt something. If you really want to obtain the key, you can run your password through the KDF assuming you know the salt and iteration count.
>
> Symmetric key cryptography requires secure key exchange. But in real world the 'key' itself is not exchanged right? Instead the password should be securely exchanged right?
>
>
>
This is quite a complex topic. In the case of GPG in symmetric mode, the key is not transferred by any means. Knowledge of the password is required to decrypt the encrypted data.
If you want to "share" the encrypted data with another entity, you usually make use of a [hybrid cryptosystem](http://en.wikipedia.org/wiki/Hybrid_cryptosystem). In the case of GPG, you will be encrypting the file *without* the `--symmetric` flag. What this does is encrypt the data with a **randomly generated** symmetric key. This randomly generated key is then encrypted with the *public* key of your target (the recipient in GPG-speak). The encrypted symmetric key is appended with the encrypted blob and sent to your target. Your target will then decrypt the encrypted symmetric key with his *private* key and use the decrypted symmetric key to decrypt the encrypted blob. | 1) Yes, --symmetric does derive a 128bit key from the password and a salt prepended to the encrypted output. It uses a function called Password Based Key Derivation Function 2 (PBKDF2) to do this. Infact, this is also how gpg encrypts the private key so that only your passphrase can use the file.
2) Well, you could run the password and salt yourself through the function to generate the key.
3) In real life asymmetric cryptography is usually used to exchange symmetric keys generated for that session. Then those symmetric keys are used for the actual encryption of the data/message. |
66,680,836 | I want to obtain the value that is under the header count (2500)
but the line number of the file can change
I tried with this
```
value=$(awk 'NR==6' $log_file)
echo $value
```
Also
```
value=$(awk 'NR==1' | awk '/^[0-9]+/ { print }' $log_file)
echo $value
```
log\_file
```
PC220 - Production on Feb 13
Connected ...
CONNECT to DB
count
--------------------
2500
1 rows affected
Good bye!
User "BILL" disconnect successfully.
FIN
```
I want to get the value of 2500 that is below the count header | 2021/03/17 | [
"https://Stackoverflow.com/questions/66680836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14242596/"
] | This `awk` should work for you:
```sh
awk '$0 == "count" {n = NR+2} NR == n {print; exit}' file
2500
```
Just save line number when we get `count` record and print the value when we get 2nd records afterwards. | You can find a line that is equal to `count` and then get the first field of the second line below with
```
awk '$0 == "count"{getline;getline;print $1;exit}' $log_file
```
See the [online demo](https://ideone.com/CDep2z):
```sh
#!/bin/bash
s='PC220 - Production on Feb 13
Connected ...
CONNECT to DB
count
--------------------
2500
1 rows affected
Good bye!
User "BILL" disconnect successfully.
FIN'
awk '$0 == "count"{getline;getline;print $1;exit}' <<< "$s"
# => 2500
``` |
66,680,836 | I want to obtain the value that is under the header count (2500)
but the line number of the file can change
I tried with this
```
value=$(awk 'NR==6' $log_file)
echo $value
```
Also
```
value=$(awk 'NR==1' | awk '/^[0-9]+/ { print }' $log_file)
echo $value
```
log\_file
```
PC220 - Production on Feb 13
Connected ...
CONNECT to DB
count
--------------------
2500
1 rows affected
Good bye!
User "BILL" disconnect successfully.
FIN
```
I want to get the value of 2500 that is below the count header | 2021/03/17 | [
"https://Stackoverflow.com/questions/66680836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14242596/"
] | shorter with `sed`
```
$ value=$(sed -n '/^count$/{n;n;p;q}' file)
```
find the header, next line, next line, print, quit. | You can find a line that is equal to `count` and then get the first field of the second line below with
```
awk '$0 == "count"{getline;getline;print $1;exit}' $log_file
```
See the [online demo](https://ideone.com/CDep2z):
```sh
#!/bin/bash
s='PC220 - Production on Feb 13
Connected ...
CONNECT to DB
count
--------------------
2500
1 rows affected
Good bye!
User "BILL" disconnect successfully.
FIN'
awk '$0 == "count"{getline;getline;print $1;exit}' <<< "$s"
# => 2500
``` |
56,675,794 | I would like the output to look like this:
```
stephen
peter
ben
```
but with the 'e' characters having a background colour. Is this possible using the below code and some javascript?
```
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
stephen
<p id="demo">peter</p>
ben
</div>
<script>
</script>
</body>
</html>
``` | 2019/06/19 | [
"https://Stackoverflow.com/questions/56675794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9445711/"
] | Get the names, split them into letters, pass each letter through a comparison function and add a span with the highlight class if it is an e.
```js
var names = document.querySelectorAll('p');
names.forEach(function(name){
var letters = name.innerText.split('');
var newName = '';
letters.forEach(function(letter){
newName += isE(letter);
})
name.innerHTML = newName;
})
function isE(letter){
let newStr =''
letter.toLowerCase() == 'e'
? newStr += '<span class="highlight">'+ letter +'</span>'
: newStr = letter;
return newStr;
}
```
```css
.highlight {
background-color: yellow
}
```
```html
<p id="demo1">stephen</p>
<p id="demo2">peter</p>
<p id="demo3">ben</p>
``` | And my solution
```js
const elementDiv = document.querySelector('div');
const elementText = elementDiv.textContent.trim().split(/\s+/);
elementDiv.innerHTML = '';
elementText.forEach(element => {
elementDiv.innerHTML += `<br>${element.replace(/e/gi, '<span style="color: red;">e</span>')}`;
});
```
```html
<div>
stephen
<p id="demo">peter</p>
ben
</div>
``` |
6,975,378 | There is Campaign Entity and for that, I have CampaignRepository which have this functions
1. public IList FindAll();
2. public Campaign FindByCampaignNumber(string number);
But now i want this criterias -:
1. Find campaigns that are created today.
2. Find campaigns that are created in this month
3. Find top 5 latest campaigns.
4. Find campaigns that are created in this year.
So for all these campaigns filters,
**Do i create separate function for each of them in repository ?**
and implement like this way.
Getall campaigns and then filter required campaigns, but i do not want all campaigns. While searching in google i find this solution's
1: <http://russelleast.wordpress.com/2008/09/20/implementing-the-repository-and-finder-patterns/>
**Is there any method i can avoid multiple functions or do i go ahead and create seperate functions for each of this filter ?** | 2011/08/07 | [
"https://Stackoverflow.com/questions/6975378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535531/"
] | Have you considered implementing [Specification](http://en.wikipedia.org/wiki/Specification_pattern) pattern in your application? Maybe it looks like an overkill, but it may prove useful if your app will have some complex user filter options.
```
class CampaignSpecification
{
public CampaignSpecification Number(string number);
public CampaignSpecification DateBetween(DateTime from, date to);
public CampaignSpecification Year(DateTime year);
} //I have omitted all the AND/OR stuff it can be easily implemented with any SQL like query language
```
Here is an example how loading from the repository may look like
```
var campaignList = CampaignRepository.load(
new CampaignSpec()
.Number("2")
.Year(DateTime.Now);
```
Also I'd like to add that it depends much on what kind of data access solution you are using, it makes implementing easier when you know what kind of API you will be using(Criteria API, SQL or whatever) so you can tweak your Specification interface to make its implementation simpler.
**UPDATE**: if you are implementing specifications in .NET using linq and nHibernate please check out <http://linqspecs.codeplex.com/> | I would go with creating two Specifications: TopCampaignSpec and CampaingCreatedSpec.
```
var spec = CampaignCreatedSpec.ThisYear();
var campaigns = CampaignsRepository.FindSatisfying(spec);
```
CampaingCreatedSpec can also be replaced with more generic DateRange class if you need this functionality elsewhere:
```
var thisYear = DateRange.ThisYear();
var campaigns = CampaignsRepository.FindByDateRange(spec);
```
I also highly recommend staying away from 'generic' repositories and entities. Please read [this](http://codebetter.com/gregyoung/2009/01/16/ddd-the-generic-repository/)
From DDD perspective it does not matter whether data access code is implemented as SQL/HQL/ICriteria or even web service call. This code belongs to repository implementation (data access layer). This is just a sample:
```
public IList<Campaign> FindByDateRange(CampaignCreatedSpec spec) {
ICriteria c = _nhibernateSession.CreateCriteria(typeof(Campaign));
c.Add(Restrictions.Between("_creationDate", spec.StartDate, spec.EndDate));
return c.List<Campaign>();
}
``` |
6,975,378 | There is Campaign Entity and for that, I have CampaignRepository which have this functions
1. public IList FindAll();
2. public Campaign FindByCampaignNumber(string number);
But now i want this criterias -:
1. Find campaigns that are created today.
2. Find campaigns that are created in this month
3. Find top 5 latest campaigns.
4. Find campaigns that are created in this year.
So for all these campaigns filters,
**Do i create separate function for each of them in repository ?**
and implement like this way.
Getall campaigns and then filter required campaigns, but i do not want all campaigns. While searching in google i find this solution's
1: <http://russelleast.wordpress.com/2008/09/20/implementing-the-repository-and-finder-patterns/>
**Is there any method i can avoid multiple functions or do i go ahead and create seperate functions for each of this filter ?** | 2011/08/07 | [
"https://Stackoverflow.com/questions/6975378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535531/"
] | Have you considered implementing [Specification](http://en.wikipedia.org/wiki/Specification_pattern) pattern in your application? Maybe it looks like an overkill, but it may prove useful if your app will have some complex user filter options.
```
class CampaignSpecification
{
public CampaignSpecification Number(string number);
public CampaignSpecification DateBetween(DateTime from, date to);
public CampaignSpecification Year(DateTime year);
} //I have omitted all the AND/OR stuff it can be easily implemented with any SQL like query language
```
Here is an example how loading from the repository may look like
```
var campaignList = CampaignRepository.load(
new CampaignSpec()
.Number("2")
.Year(DateTime.Now);
```
Also I'd like to add that it depends much on what kind of data access solution you are using, it makes implementing easier when you know what kind of API you will be using(Criteria API, SQL or whatever) so you can tweak your Specification interface to make its implementation simpler.
**UPDATE**: if you are implementing specifications in .NET using linq and nHibernate please check out <http://linqspecs.codeplex.com/> | You should be able to do all of the above with the following repository method:
```
List<Campaign> findCampaigns(Date fromCreationDate, Date toCreationDate, int offset, Integer limit) {
if (fromCreationDate != null) add criteria...
if (toCreationDate != null) add criteria...
if (limit != null) add limit...
}
```
This is how I do it and it works very well. |
6,975,378 | There is Campaign Entity and for that, I have CampaignRepository which have this functions
1. public IList FindAll();
2. public Campaign FindByCampaignNumber(string number);
But now i want this criterias -:
1. Find campaigns that are created today.
2. Find campaigns that are created in this month
3. Find top 5 latest campaigns.
4. Find campaigns that are created in this year.
So for all these campaigns filters,
**Do i create separate function for each of them in repository ?**
and implement like this way.
Getall campaigns and then filter required campaigns, but i do not want all campaigns. While searching in google i find this solution's
1: <http://russelleast.wordpress.com/2008/09/20/implementing-the-repository-and-finder-patterns/>
**Is there any method i can avoid multiple functions or do i go ahead and create seperate functions for each of this filter ?** | 2011/08/07 | [
"https://Stackoverflow.com/questions/6975378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535531/"
] | Have you considered implementing [Specification](http://en.wikipedia.org/wiki/Specification_pattern) pattern in your application? Maybe it looks like an overkill, but it may prove useful if your app will have some complex user filter options.
```
class CampaignSpecification
{
public CampaignSpecification Number(string number);
public CampaignSpecification DateBetween(DateTime from, date to);
public CampaignSpecification Year(DateTime year);
} //I have omitted all the AND/OR stuff it can be easily implemented with any SQL like query language
```
Here is an example how loading from the repository may look like
```
var campaignList = CampaignRepository.load(
new CampaignSpec()
.Number("2")
.Year(DateTime.Now);
```
Also I'd like to add that it depends much on what kind of data access solution you are using, it makes implementing easier when you know what kind of API you will be using(Criteria API, SQL or whatever) so you can tweak your Specification interface to make its implementation simpler.
**UPDATE**: if you are implementing specifications in .NET using linq and nHibernate please check out <http://linqspecs.codeplex.com/> | Here is how I would do this:
```
class Campaigns{
IEnumerable<Campaign> All(){...}
IEnumerable<Campaign> ByNumber(int number){...}
IEnumerable<Campaign> CreatedToday(){...}
IEnumerable<Campaign> CreatedThisMonth(){...}
IEnumerable<Campaign> CreatedThisYear(){...}
IEnumerable<Campaign> Latest5(){...}
private IQueryable<Campaign> GetSomething(Something something){
//used by public methods to dry out repository
}
}
```
Reasoning is simple - it matters by what You are interested to look for campaigns (that knowledge is part of Your domain). If we explicitly state functions to reflect that, we will always know it.
---
>
> Is it appropriate to add all this methods in campaign repository ?
>
>
>
I don't see anything wrong with that.
>
> Arnis i want some code, how u implementing Created today function in domain itself, Are you injecting repository here in this function ? Thanks for your cooperation
>
>
>
I wouldn't implement CreatedToday function in my domain. It would sit in repository and repository implementations should not be concern of domain. If You mean how I would use Campaign repository and if it should be used from domain - no, it should not be used from within of domain. If You mean if I would inject repository inside of repository - You are listening too much of [xzibit](http://knowyourmeme.com/memes/xzibit-yo-dawg). |
6,975,378 | There is Campaign Entity and for that, I have CampaignRepository which have this functions
1. public IList FindAll();
2. public Campaign FindByCampaignNumber(string number);
But now i want this criterias -:
1. Find campaigns that are created today.
2. Find campaigns that are created in this month
3. Find top 5 latest campaigns.
4. Find campaigns that are created in this year.
So for all these campaigns filters,
**Do i create separate function for each of them in repository ?**
and implement like this way.
Getall campaigns and then filter required campaigns, but i do not want all campaigns. While searching in google i find this solution's
1: <http://russelleast.wordpress.com/2008/09/20/implementing-the-repository-and-finder-patterns/>
**Is there any method i can avoid multiple functions or do i go ahead and create seperate functions for each of this filter ?** | 2011/08/07 | [
"https://Stackoverflow.com/questions/6975378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535531/"
] | I would go with creating two Specifications: TopCampaignSpec and CampaingCreatedSpec.
```
var spec = CampaignCreatedSpec.ThisYear();
var campaigns = CampaignsRepository.FindSatisfying(spec);
```
CampaingCreatedSpec can also be replaced with more generic DateRange class if you need this functionality elsewhere:
```
var thisYear = DateRange.ThisYear();
var campaigns = CampaignsRepository.FindByDateRange(spec);
```
I also highly recommend staying away from 'generic' repositories and entities. Please read [this](http://codebetter.com/gregyoung/2009/01/16/ddd-the-generic-repository/)
From DDD perspective it does not matter whether data access code is implemented as SQL/HQL/ICriteria or even web service call. This code belongs to repository implementation (data access layer). This is just a sample:
```
public IList<Campaign> FindByDateRange(CampaignCreatedSpec spec) {
ICriteria c = _nhibernateSession.CreateCriteria(typeof(Campaign));
c.Add(Restrictions.Between("_creationDate", spec.StartDate, spec.EndDate));
return c.List<Campaign>();
}
``` | You should be able to do all of the above with the following repository method:
```
List<Campaign> findCampaigns(Date fromCreationDate, Date toCreationDate, int offset, Integer limit) {
if (fromCreationDate != null) add criteria...
if (toCreationDate != null) add criteria...
if (limit != null) add limit...
}
```
This is how I do it and it works very well. |
6,975,378 | There is Campaign Entity and for that, I have CampaignRepository which have this functions
1. public IList FindAll();
2. public Campaign FindByCampaignNumber(string number);
But now i want this criterias -:
1. Find campaigns that are created today.
2. Find campaigns that are created in this month
3. Find top 5 latest campaigns.
4. Find campaigns that are created in this year.
So for all these campaigns filters,
**Do i create separate function for each of them in repository ?**
and implement like this way.
Getall campaigns and then filter required campaigns, but i do not want all campaigns. While searching in google i find this solution's
1: <http://russelleast.wordpress.com/2008/09/20/implementing-the-repository-and-finder-patterns/>
**Is there any method i can avoid multiple functions or do i go ahead and create seperate functions for each of this filter ?** | 2011/08/07 | [
"https://Stackoverflow.com/questions/6975378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535531/"
] | Here is how I would do this:
```
class Campaigns{
IEnumerable<Campaign> All(){...}
IEnumerable<Campaign> ByNumber(int number){...}
IEnumerable<Campaign> CreatedToday(){...}
IEnumerable<Campaign> CreatedThisMonth(){...}
IEnumerable<Campaign> CreatedThisYear(){...}
IEnumerable<Campaign> Latest5(){...}
private IQueryable<Campaign> GetSomething(Something something){
//used by public methods to dry out repository
}
}
```
Reasoning is simple - it matters by what You are interested to look for campaigns (that knowledge is part of Your domain). If we explicitly state functions to reflect that, we will always know it.
---
>
> Is it appropriate to add all this methods in campaign repository ?
>
>
>
I don't see anything wrong with that.
>
> Arnis i want some code, how u implementing Created today function in domain itself, Are you injecting repository here in this function ? Thanks for your cooperation
>
>
>
I wouldn't implement CreatedToday function in my domain. It would sit in repository and repository implementations should not be concern of domain. If You mean how I would use Campaign repository and if it should be used from domain - no, it should not be used from within of domain. If You mean if I would inject repository inside of repository - You are listening too much of [xzibit](http://knowyourmeme.com/memes/xzibit-yo-dawg). | You should be able to do all of the above with the following repository method:
```
List<Campaign> findCampaigns(Date fromCreationDate, Date toCreationDate, int offset, Integer limit) {
if (fromCreationDate != null) add criteria...
if (toCreationDate != null) add criteria...
if (limit != null) add limit...
}
```
This is how I do it and it works very well. |
61,912,299 | I'm designing an app for the company I work for that uses a basic y=mx+c (or y=mx+b if you're from the US) to take 2 calibrated values and 2 input values to output scale and offset values. The app takes a users input from a total of 4 text fields, and then uses a few formulas to output into a text view. My problem is that the input values need to be 'Doubles' for use in the formulas (Divisor, m\_FinalScale, m\_FinalOffset) whereas the values that the user inputs are 'Strings?' because they are from a text field. How could I go about unwrapping and converting those optional strings to then use?
```
override func viewDidLoad() {
super.viewDidLoad()
Cal1Field.delegate = self
Cal2Field.delegate = self
Input1Field.delegate = self
Input2Field.delegate = self
}
//Actions
@IBAction func CalibrateTapped(_ sender: Any) {
var Divisor = 0.0, m_FinalScale = 0.0, m_FinalOffset = 0.0
// this is what the formulas are
Divisor = Input2Field.text - Input1Field.text
m_FinalScale = (Cal2Field.text - Cal1Field.text)/Divisor
m_FinalOffset = Cal1Field.text - (m_FinalScale*Input1Field.text)
}
``` | 2020/05/20 | [
"https://Stackoverflow.com/questions/61912299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4177171/"
] | You can use `flatMap` here:
```
let input1 = input2Field.text.flatMap(Double.init)
let input2 = input2Field.text.flatMap(Double.init)
let cal1 = cal2Field.text.flatMap(Double.init)
let cal2 = cal2Field.text.flatMap(Double.init)
```
If you want to avoid the code duplication, you can add an extension over `UITextField`:
```swift
extension UITextfield {
var doubleValue: Double? { text.flatMap(Double.init) }
}
```
, which you can later use like this:
```swift
let input1 = input2Field.doubleValue
let input2 = input2Field.doubleValue
let cal1 = cal2Field.text.doubleValue
let cal2 = cal2Field.text.doubleValue
```
A couple of notes here:
1. I renamed the text fields to start with a lowercase letter, to follow the Swift [naming conventions](https://swift.org/documentation/api-design-guidelines/#follow-case-conventions).
2. `input1`, `input2`, `cal1`, `cal2` are optionals, it your call what to do if some are nil (e.g. the user entered invalid values). | You can use this extension
```
extension String {
var convertItToDouble: Double? {
return Double(self)
}
}
```
then in your method
```
@IBAction func CalibrateTapped(_ sender: Any) {
var Divisor = 0.0, m_FinalScale = 0.0, m_FinalOffset = 0.0
// this is what the formulas are
if let doubleCal1Field = Cal1Field.text?.convertItToDouble,
let doubleCal2Field = Cal2Field.text?.convertItToDouble,
let doubleInput1Field = Input1Field.text?.convertItToDouble,
let doubleInput2Field = Input2Field.text?.convertItToDouble {
Divisor = doubleInput2Field - doubleInput1Field
m_FinalScale = (doubleCal2Field - doubleCal1Field)/Divisor
m_FinalOffset = doubleCal1Field - (m_FinalScale*doubleInput1Field)
}
}
``` |
9,550 | 'An entry which increases an asset account is called a debit.'
So if my bank account is my asset account, when I debit money, money actually goes out so it is a 'decrease'. But the above statement has it the other way round.
Kindly help me understand this. | 2011/07/11 | [
"https://money.stackexchange.com/questions/9550",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/2991/"
] | There are two basic issues here. First, there is the difference between accounting terms and their dictionary definitions. Second, once you dig into it there are dichotomies similar to put vs call options, long sales vs short sales, bond yield vs interest rate. (That is, while they are relatively simple ideas and opposite sides of the same coin, it will probably take some effort to get comfortable with them.)
The salient points from the Wikipedia [article on debits and credits](http://en.wikipedia.org/wiki/Debits_and_credits):
>
> In double-entry bookkeeping debit is used for increases in asset and expense transactions and credit is used for increases in a liability, income (gain) or equity transaction.
>
>
> For bank transactions, money deposited in a checking account is treated as a credit transaction (increase) and money paid out is treated as a debit transaction, because checking account balances are bank liabilities. If cash is deposited, the cash becomes a bank asset and is treated as a debit transaction (increase) to a bank asset account. Thus a cash deposit becomes two equal increases: a debit to cash on hand and a credit to a customer's checking account.
>
>
>
Your bank account is an asset to you, but a liability to your bank. That makes for a third issue, namely perspective. | In this context, we're talking about terms of art in accounting, specifically double-entry book-keeping.
In accounting lingo, an "asset" account represents an actual asset and it's value. So if you buy a car with a loan for $10,000, you apply a $10,000 debit to the asset account and a $10,000 credit to the loan.
Debits and credits are confusing when you first start learning about accounting. |
9,550 | 'An entry which increases an asset account is called a debit.'
So if my bank account is my asset account, when I debit money, money actually goes out so it is a 'decrease'. But the above statement has it the other way round.
Kindly help me understand this. | 2011/07/11 | [
"https://money.stackexchange.com/questions/9550",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/2991/"
] | There are two basic issues here. First, there is the difference between accounting terms and their dictionary definitions. Second, once you dig into it there are dichotomies similar to put vs call options, long sales vs short sales, bond yield vs interest rate. (That is, while they are relatively simple ideas and opposite sides of the same coin, it will probably take some effort to get comfortable with them.)
The salient points from the Wikipedia [article on debits and credits](http://en.wikipedia.org/wiki/Debits_and_credits):
>
> In double-entry bookkeeping debit is used for increases in asset and expense transactions and credit is used for increases in a liability, income (gain) or equity transaction.
>
>
> For bank transactions, money deposited in a checking account is treated as a credit transaction (increase) and money paid out is treated as a debit transaction, because checking account balances are bank liabilities. If cash is deposited, the cash becomes a bank asset and is treated as a debit transaction (increase) to a bank asset account. Thus a cash deposit becomes two equal increases: a debit to cash on hand and a credit to a customer's checking account.
>
>
>
Your bank account is an asset to you, but a liability to your bank. That makes for a third issue, namely perspective. | "Debits'" and "Credits" are terms used in double-entry bookkeeping. Each transaction is entered in two different places to be able to double-check accuracy. The total debits and total credits being equal is what makes the balance sheet balance.
For explaining debits and credits, wikiversity has a good example using eggs that I found helpful as a student.
Debits and Credits
When a financial transaction is recorded, the Debits (Dr) and Credits (Cr) need to balance in order to keep the accounts in balance.
An easy rule to remember is, "Debit the Asset that Increases"
For example, if you want to practice accounting for cooking a simple breakfast, you might proceed as follows:
* Dr the frying pan 2 egg yolks
* Dr the frying pan 2 egg whites
* Dr the trash basket 2 egg shells
o Cr the carton of eggs 2 whole eggs
To record breaking the eggs and putting the eggs in the frying pan
In this transaction, an asset, (the egg) is split into parts and some of the asset goes in the pan and some in the trash. A Debit (Dr) is used to show that the assets in the pan and the trash both increase. A balancing Credit (Cr) is used to show that the amount of assets (whole eggs) in the egg carton has decreased.
This transaction is in balance because the total Credits equal the total Debits. Everything that is covered by the Debits (yolk, white and shell) is also covered by the Credits (one whole egg) |
9,550 | 'An entry which increases an asset account is called a debit.'
So if my bank account is my asset account, when I debit money, money actually goes out so it is a 'decrease'. But the above statement has it the other way round.
Kindly help me understand this. | 2011/07/11 | [
"https://money.stackexchange.com/questions/9550",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/2991/"
] | There are two basic issues here. First, there is the difference between accounting terms and their dictionary definitions. Second, once you dig into it there are dichotomies similar to put vs call options, long sales vs short sales, bond yield vs interest rate. (That is, while they are relatively simple ideas and opposite sides of the same coin, it will probably take some effort to get comfortable with them.)
The salient points from the Wikipedia [article on debits and credits](http://en.wikipedia.org/wiki/Debits_and_credits):
>
> In double-entry bookkeeping debit is used for increases in asset and expense transactions and credit is used for increases in a liability, income (gain) or equity transaction.
>
>
> For bank transactions, money deposited in a checking account is treated as a credit transaction (increase) and money paid out is treated as a debit transaction, because checking account balances are bank liabilities. If cash is deposited, the cash becomes a bank asset and is treated as a debit transaction (increase) to a bank asset account. Thus a cash deposit becomes two equal increases: a debit to cash on hand and a credit to a customer's checking account.
>
>
>
Your bank account is an asset to you, but a liability to your bank. That makes for a third issue, namely perspective. | Don't be confused by the terminology that your bank uses on *the bank's statement* of your account.
When you deposit money into your bank account, you are increasing that asset so you should **debit** that **asset account**.
Your bank looks at that same transaction from a different perspective, however. When your bank balance increases, that represents an increase in the amount that the bank *owes to you*. Your bank account is a **liability account** for the bank.
When you deposit money into your bank account, the bank will **credit** the **liability account** representing the amount that it owes you.
The accounts that your bank keeps are not that same as the accounts that you will keep. The bank will treat transactions differently to the way that you should. |
9,550 | 'An entry which increases an asset account is called a debit.'
So if my bank account is my asset account, when I debit money, money actually goes out so it is a 'decrease'. But the above statement has it the other way round.
Kindly help me understand this. | 2011/07/11 | [
"https://money.stackexchange.com/questions/9550",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/2991/"
] | "Debits'" and "Credits" are terms used in double-entry bookkeeping. Each transaction is entered in two different places to be able to double-check accuracy. The total debits and total credits being equal is what makes the balance sheet balance.
For explaining debits and credits, wikiversity has a good example using eggs that I found helpful as a student.
Debits and Credits
When a financial transaction is recorded, the Debits (Dr) and Credits (Cr) need to balance in order to keep the accounts in balance.
An easy rule to remember is, "Debit the Asset that Increases"
For example, if you want to practice accounting for cooking a simple breakfast, you might proceed as follows:
* Dr the frying pan 2 egg yolks
* Dr the frying pan 2 egg whites
* Dr the trash basket 2 egg shells
o Cr the carton of eggs 2 whole eggs
To record breaking the eggs and putting the eggs in the frying pan
In this transaction, an asset, (the egg) is split into parts and some of the asset goes in the pan and some in the trash. A Debit (Dr) is used to show that the assets in the pan and the trash both increase. A balancing Credit (Cr) is used to show that the amount of assets (whole eggs) in the egg carton has decreased.
This transaction is in balance because the total Credits equal the total Debits. Everything that is covered by the Debits (yolk, white and shell) is also covered by the Credits (one whole egg) | In this context, we're talking about terms of art in accounting, specifically double-entry book-keeping.
In accounting lingo, an "asset" account represents an actual asset and it's value. So if you buy a car with a loan for $10,000, you apply a $10,000 debit to the asset account and a $10,000 credit to the loan.
Debits and credits are confusing when you first start learning about accounting. |
9,550 | 'An entry which increases an asset account is called a debit.'
So if my bank account is my asset account, when I debit money, money actually goes out so it is a 'decrease'. But the above statement has it the other way round.
Kindly help me understand this. | 2011/07/11 | [
"https://money.stackexchange.com/questions/9550",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/2991/"
] | "Debits'" and "Credits" are terms used in double-entry bookkeeping. Each transaction is entered in two different places to be able to double-check accuracy. The total debits and total credits being equal is what makes the balance sheet balance.
For explaining debits and credits, wikiversity has a good example using eggs that I found helpful as a student.
Debits and Credits
When a financial transaction is recorded, the Debits (Dr) and Credits (Cr) need to balance in order to keep the accounts in balance.
An easy rule to remember is, "Debit the Asset that Increases"
For example, if you want to practice accounting for cooking a simple breakfast, you might proceed as follows:
* Dr the frying pan 2 egg yolks
* Dr the frying pan 2 egg whites
* Dr the trash basket 2 egg shells
o Cr the carton of eggs 2 whole eggs
To record breaking the eggs and putting the eggs in the frying pan
In this transaction, an asset, (the egg) is split into parts and some of the asset goes in the pan and some in the trash. A Debit (Dr) is used to show that the assets in the pan and the trash both increase. A balancing Credit (Cr) is used to show that the amount of assets (whole eggs) in the egg carton has decreased.
This transaction is in balance because the total Credits equal the total Debits. Everything that is covered by the Debits (yolk, white and shell) is also covered by the Credits (one whole egg) | Don't be confused by the terminology that your bank uses on *the bank's statement* of your account.
When you deposit money into your bank account, you are increasing that asset so you should **debit** that **asset account**.
Your bank looks at that same transaction from a different perspective, however. When your bank balance increases, that represents an increase in the amount that the bank *owes to you*. Your bank account is a **liability account** for the bank.
When you deposit money into your bank account, the bank will **credit** the **liability account** representing the amount that it owes you.
The accounts that your bank keeps are not that same as the accounts that you will keep. The bank will treat transactions differently to the way that you should. |
3,919 | You are a railroad entrepreneur in the 19th-century United States when trains become popular because they are the most efficient means of transporting large volumes of materials by land. There is a national need for railroad tracks from the east coast through some recently colonized lands in the west.
To accommodate this need, the U.S. government is going to levy a tax to subsidize railroads. They have promised to pay money to your railroad company for each mile of track laid. Since laying tracks in hilly and mountainous regions is more expensive than laying tracks in flat land, they adjust the amount they give accordingly. That is, the government will pay
* $5,000 per mile of track laid in flat land
* $12,500 per mile of track laid in hilly land
* $20,000 per mile of track laid in mountains.
Of course, this plan does not accurately reflect how much it actually costs to lay tracks.
You have hired some cartographers to draw relief maps of the regions where you will be laying track to analyze the elevation. Here is one such map:
```
S12321
121234
348E96
```
Each digit represents one square mile of land. `S` is the starting point, `E` is the ending point. Each number represents the intensity of the elevation changes in that region.
* Land numbered 1-3 constitutes flat land.
* Land numbered 4-6 constitutes hilly land.
* Land numbered 7-9 constitutes a mountain range.
You have, through years of experience building railroad tracks, assessed that the cost of track building (in dollars) satisfies this formula:
```
Cost_Per_Mile = 5000 + (1500 * (Elevation_Rating - 1))
```
That means building on certain elevation gradients will cost you more money than the government gives, sometimes it will be profitable, and sometimes you will just break even.
For example, a mile of track on an elevation gradient of 3 costs $8,000 to build, but you only get paid $5,000 for it, so you lose $3000. In contrast, building a mile of track on an elevation gradient of 7 costs $14,000, but you get paid $20,000 for it: a $6,000 profit!
Here is an example map, as well as two different possible paths.
```
S29 S#9 S##
134 1#4 1##
28E 2#E 2#E
```
The first track costs $30,000 dollars to construct, but the government pays you $30,000 for it. You make no profit from this track.
On the other hand, the second costs $56,500 to build, but you get paid $62,500 for it. You profit $6,000 from this track.
**Your goal:** given a relief map, find the most profitable (or perhaps merely the least expensive) path from the start to the end. If multiple paths tie, any one of them is an acceptable solution.
Program Details
===============
You are given text input separated with a rectangular map of numbers and one start and end point. Each number will be an integer inclusively between 1 and 9. Other than that, the input may be provided however you like, within reason.
The output should be in the same format as the input, with the numbers where track has been built replaced by a hash (`#`). Because of arbitrary regulations imposed by some capricious politicians, tracks can only go in horizontal or vertical paths. In other words, you can't backtrack or go diagonally.
The program should be able to solve in a reasonable amount of time (i.e. <10 minutes) for maps up to 6 rows and 6 columns.
This is a **code golf** challenge, so the shortest program wins.
I have an [example (non-golfed) implementation](http://jsbin.com/osugoz/17/edit#preview).
Sample I/O
==========
```
S12321
121234
348E96
S12321
######
3##E##
S73891
121234
348453
231654
97856E
S#3###
1###3#
3#####
######
#####E
``` | 2011/11/15 | [
"https://codegolf.stackexchange.com/questions/3919",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/788/"
] | Python, 307 chars
-----------------
```
import os
I=os.read(0,99)
n=I.find('\n')+1
I='\0'*n+I+'\0'*n
def P(p):
S=[]
for d in(-n,-1,1,n):
y=p[-1]+d
if'E'==I[y]:S+=[(sum((int(I[v])-1)/3*75-15*int(I[v])+15for v in p[1:]),p)]
if'0'<I[y]<':'and y not in p:S+=P(p+[y])
return S
for i in max(P([I.find('S')]))[1][1:]:I=I[:i]+'#'+I[i+1:]
print I,
```
`P` takes a partial path `p` and returns all ways of extending it to reach `E`. Each returned path is paired with its score so `max` can find the best one.
Takes about 80 seconds on a 6x6 map. | ### Ruby, 233 characters
```
R=->s{o=s=~/S/m
s=~/E/m?(q=[-1,1,-N,N].map{|t|s[f=o+t]>'0'?(n=s*1
n[o]='#'
n[f]='S'
a=R[n]
a&&[a[0]-(e=s[f].to_i-1)/3*5+e,a[1]]):nil}-[nil]
q.sort!&&q[0]):[0,(n=s*1;n[o]='E'
n[$_=~/S/m]='S'
n)]}
N=1+(gets(nil)=~/$/)
$><<R[$_+$/*N][1]
```
A Ruby brute-force approach which runs well inside the time constraints on a 6x6 board. The input must be given on STDIN.
*Examples:*
```
S12321
121234
348E96
S#2321
1#####
3##E##
--
S73891
121234
348453
231654
97856E
S#####
1212##
#####3
#3####
#####E
``` |
3,919 | You are a railroad entrepreneur in the 19th-century United States when trains become popular because they are the most efficient means of transporting large volumes of materials by land. There is a national need for railroad tracks from the east coast through some recently colonized lands in the west.
To accommodate this need, the U.S. government is going to levy a tax to subsidize railroads. They have promised to pay money to your railroad company for each mile of track laid. Since laying tracks in hilly and mountainous regions is more expensive than laying tracks in flat land, they adjust the amount they give accordingly. That is, the government will pay
* $5,000 per mile of track laid in flat land
* $12,500 per mile of track laid in hilly land
* $20,000 per mile of track laid in mountains.
Of course, this plan does not accurately reflect how much it actually costs to lay tracks.
You have hired some cartographers to draw relief maps of the regions where you will be laying track to analyze the elevation. Here is one such map:
```
S12321
121234
348E96
```
Each digit represents one square mile of land. `S` is the starting point, `E` is the ending point. Each number represents the intensity of the elevation changes in that region.
* Land numbered 1-3 constitutes flat land.
* Land numbered 4-6 constitutes hilly land.
* Land numbered 7-9 constitutes a mountain range.
You have, through years of experience building railroad tracks, assessed that the cost of track building (in dollars) satisfies this formula:
```
Cost_Per_Mile = 5000 + (1500 * (Elevation_Rating - 1))
```
That means building on certain elevation gradients will cost you more money than the government gives, sometimes it will be profitable, and sometimes you will just break even.
For example, a mile of track on an elevation gradient of 3 costs $8,000 to build, but you only get paid $5,000 for it, so you lose $3000. In contrast, building a mile of track on an elevation gradient of 7 costs $14,000, but you get paid $20,000 for it: a $6,000 profit!
Here is an example map, as well as two different possible paths.
```
S29 S#9 S##
134 1#4 1##
28E 2#E 2#E
```
The first track costs $30,000 dollars to construct, but the government pays you $30,000 for it. You make no profit from this track.
On the other hand, the second costs $56,500 to build, but you get paid $62,500 for it. You profit $6,000 from this track.
**Your goal:** given a relief map, find the most profitable (or perhaps merely the least expensive) path from the start to the end. If multiple paths tie, any one of them is an acceptable solution.
Program Details
===============
You are given text input separated with a rectangular map of numbers and one start and end point. Each number will be an integer inclusively between 1 and 9. Other than that, the input may be provided however you like, within reason.
The output should be in the same format as the input, with the numbers where track has been built replaced by a hash (`#`). Because of arbitrary regulations imposed by some capricious politicians, tracks can only go in horizontal or vertical paths. In other words, you can't backtrack or go diagonally.
The program should be able to solve in a reasonable amount of time (i.e. <10 minutes) for maps up to 6 rows and 6 columns.
This is a **code golf** challenge, so the shortest program wins.
I have an [example (non-golfed) implementation](http://jsbin.com/osugoz/17/edit#preview).
Sample I/O
==========
```
S12321
121234
348E96
S12321
######
3##E##
S73891
121234
348453
231654
97856E
S#3###
1###3#
3#####
######
#####E
``` | 2011/11/15 | [
"https://codegolf.stackexchange.com/questions/3919",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/788/"
] | Python, 307 chars
-----------------
```
import os
I=os.read(0,99)
n=I.find('\n')+1
I='\0'*n+I+'\0'*n
def P(p):
S=[]
for d in(-n,-1,1,n):
y=p[-1]+d
if'E'==I[y]:S+=[(sum((int(I[v])-1)/3*75-15*int(I[v])+15for v in p[1:]),p)]
if'0'<I[y]<':'and y not in p:S+=P(p+[y])
return S
for i in max(P([I.find('S')]))[1][1:]:I=I[:i]+'#'+I[i+1:]
print I,
```
`P` takes a partial path `p` and returns all ways of extending it to reach `E`. Each returned path is paired with its score so `max` can find the best one.
Takes about 80 seconds on a 6x6 map. | Python: 529 482 460 bytes
-------------------------
My solution will not win any prizes. However, since there are only two solutions posted and I found the problem interesting, I decided to post my answer anyway.
**Edit:** Thanks to Howard for his recommendations. I've managed to shave a lot of my score!
```
import sys
N=len
def S(m,c,p=0):
if m[c]=='E':return m,p
if m[c]<'S':
b=list(m);b[c]='#';m=''.join(b)
b=[],-float('inf')
for z in(1,-1,w,-w):
n=c+z
if 0<=n<N(m)and m[n]not in('S','#')and(-2<z<2)^(n/w!=c/w):
r=S(m,n,p+(0if m[n]=='E'else(int(m[n])-1)/3*5-int(m[n])+1))
if b[1]<r[1]:b=r
return b
m=''
while 1:
l=sys.stdin.readline().strip()
if l=='':break
w=N(l);m+=l
b,_=S(m,m.index('S'))
for i in range(0,N(b),w):print b[i:i+w]
``` |
1,891,175 | Does java's [`javax.comm`](http://java.sun.com/products/javacomm/reference/api/index.html) library support "9-bit" serial communication? (use of parity bit or "address bit" as an out-of-band signaling mechanism for framing information)
Does the win32 communications API support it?
I'm guessing the answer is no on both counts, but figured someone has more experience with this than me. | 2009/12/11 | [
"https://Stackoverflow.com/questions/1891175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44330/"
] | The win32 comm API does not support this as far as I can tell.
However, you can simulate it using the various parity modes.
Setting `MARKPARITY` will set the 9th bit to `1`
Setting `SPACEPARITY` will set the 9th bit to `0`
I can't say about the java version of the library, but I'm sure it supports setting parity modes so you can do the above and get your 9th bit. | Yout should follow this [Seeking FOSS serial port component which can handle 9 data bits](https://stackoverflow.com/q/9188015/463115).
Your main problem will be to handle 9-bit at all, as when the windows api can't handle it, how should java solve this?
Bt there exists professional cards/driver to solve this (see the link) |
1,891,175 | Does java's [`javax.comm`](http://java.sun.com/products/javacomm/reference/api/index.html) library support "9-bit" serial communication? (use of parity bit or "address bit" as an out-of-band signaling mechanism for framing information)
Does the win32 communications API support it?
I'm guessing the answer is no on both counts, but figured someone has more experience with this than me. | 2009/12/11 | [
"https://Stackoverflow.com/questions/1891175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44330/"
] | The win32 comm API does not support this as far as I can tell.
However, you can simulate it using the various parity modes.
Setting `MARKPARITY` will set the 9th bit to `1`
Setting `SPACEPARITY` will set the 9th bit to `0`
I can't say about the java version of the library, but I'm sure it supports setting parity modes so you can do the above and get your 9th bit. | I'd like to comment on **karoberts** answer, but I lack reputation. So I have to "answer".
**karoberts** proposes a good way if *we need a software solution to our problem* (JCS citation, almost, isn't it? ))
But there may arouse a situation I faced today with Python (2.7) trying to do exactly the same thing: my PC refused to accept PARITY\_MARK and PARITY\_SPACE as options to configure my /dev/ttyS5. So I searched in Stack Overflow what can be done - and encountered this topic...
And I've found an answer in that (closed) [question](https://stackoverflow.com/questions/9188015/seeking-foss-serial-port-component-which-can-handle-9-data-bits), **jeb** tells us in the next answer. **Tincho** points to an [article](http://electronicdesign.com/embedded/use-pcs-uart-9-bit-protocols) where it's proposed to set EVEN or ODD parity with each byte according to 2 factors: whether this is an address byte and what is the parity sum of it's bits.
I checked the solution and it works perfectly. |
93,894 | What is the topology of $\mathbb{P}\_2 (\mathbb{C}) \setminus \mathbb{P}\_2 (\mathbb{R})$? For example what is the homology of this manifold with coefficients in $\mathbb{Z}$. I know that this is known but I can't find a good reference for it. Can anyone give me a reference? | 2012/04/12 | [
"https://mathoverflow.net/questions/93894",
"https://mathoverflow.net",
"https://mathoverflow.net/users/13559/"
] | $H\_i (CP^2 \setminus RP^2)\cong H^{4-i}(CP^2, RP^2)$ by Poincare-Alexander-Lefschetz duality (Bredon, Topology and Geometry, Theorem 8.3 on p. 351). The latter can be computed using the long exact sequence. $H^4 = Z$, $H^0=H^1=0$ is immediate. The piece
$$0 \to H^2 (CP^2,RP^2) \to H^2 (CP^2) \to H^2 (RP^2) \to H^3 (CP^2 , RP^2) \to 0$$
needs an extra argument. The map $Z=H^2 (CP^2 ) \to H^2 (RP^2)=Z/2$ is onto because the tautological complex line bundle restricts to the complexification of the real tautological line bundle, whose first Chern class generates $H^2 (RP^2)$. Thus $H\_2 (CP^2 \setminus RP^2)=Z$ and $H\_1 (CP^2 \setminus RP^2)=0$.
Because the first map in the above sequence is multiplication by $2$ (after identification with $Z$), it follows that the inclusion $H\_2 (CP^2 \setminus RP^2)\to H\_2 (CP^2)$ takes a generator to twice a generator. A generator of $H\_2 (CP^2-RP^2)$ can be represented by an embedded sphere as follows. Take a quadric $Q \subset CP^2$ without real point, for example the one defined by the homogeneous equation $z\_{0}^{2}+z\_{1}^{2}+z\_{2}^{2}=0$. By the degree genus formula, $Q$ has genus $0$, hence is a sphere. It lies in $CP^2 - RP^2$, and because its fundamental class is twice a generator of $H\_2 (CP^2)$, it must represent a generator of $H\_2 (CP^2 - RP^2)$.
In fact, $CP^2-RP^2$ is diffeomorphic to the normal bundle of $Q$, see Tom's comment below. | There is [a beautiful (and elementary) paper by V. I. Arnold,](http://dl.dropbox.com/u/5188175/arnoldquadric.pdf) which discusses this and generalizations. |
54,014,931 | [enter image description here](https://i.stack.imgur.com/0SLf1.png)I have a menu that has multiple frame ranges for different objects being animated. I need that menu to save that frame range everytime its closed and reopened. Is it possible to save out data to an external file. | 2019/01/03 | [
"https://Stackoverflow.com/questions/54014931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10598486/"
] | I can't imagine why this would ever be done in practice explicitly with loops, but it is actually quite straightforward. iterate through columns and rows, replacing values as you go.
```
import numpy as np
import pandas as pd
def painful_fillna(df, fillvalue=0):
df = df.copy()
for col in df.columns:
for i, value in enumerate(df[col].values):
if np.isnan(value):
df[col][i] = fillvalue
return(df)
df = pd.DataFrame({'A':[1,2,'NaN',3,4,'NaN'],'B':[2,'NaN',3,'NaN',9, 'NaN']})
df = df.convert_objects(convert_numeric=True)
painful_fillna(df)
```
The average runtime of the above function on my machine is 1.05 ms. The average runtime of `df.fillna(0)` is 278 µs.
I've addressed a few issues above as well:
1. A and B were replaced with 'A' and 'B'.
2. A missing value was added to B ('NaN')
3. string 'NaN's were converted to np.NaN | Here is a similar question with several answers: [Iterating over rows and columns in Pandas](https://stackoverflow.com/questions/53996433/iterating-over-rows-and-columns-in-pandas/53998299?noredirect=1#comment94840712_53998299)
p.s. You can search this site first with different terms and try to find an answer. |
33,896,729 | Just trying to convert an integer to a string.
```
vars.put("test", i);
```
I'd like to put the value in the variable "test", but it does not working and I think I must convert the int to a string.
But I have no idea how to do that.
I just found a out how to parsing string to integer in BeanShellSampler. | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5133750/"
] | Use [String.valueOf()](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(int)) method
```
vars.put("test", String.valueOf(i));
```
Additional information on Beanshell scripting in JMeter - [How to Use BeanShell: JMeter's Favorite Built-in Component](https://blazemeter.com/blog/queen-jmeters-built-componentshow-use-beanshell) | BeanShell is a Java scripting language, so anything that works in Java should work in BeanShell, too.
I tend to use
`vars.put("test", new Integer(i).toString());`
If `i` is already an `Integer`, you only need to do `vars.put("test", i.toString());` |
33,896,729 | Just trying to convert an integer to a string.
```
vars.put("test", i);
```
I'd like to put the value in the variable "test", but it does not working and I think I must convert the int to a string.
But I have no idea how to do that.
I just found a out how to parsing string to integer in BeanShellSampler. | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5133750/"
] | There is yet a shortcut way, how to cast an `int i` to `String s`:
>
> `String s = ""+i;` .. just that simple!
>
>
>
So the asked example:
>
> `vars.put("test", ""+i);`
>
>
>
..Seriously, nobody gave that answer yet? See i.e. [4105331](https://stackoverflow.com/questions/4105331/how-do-i-convert-from-int-to-string) for further info. | BeanShell is a Java scripting language, so anything that works in Java should work in BeanShell, too.
I tend to use
`vars.put("test", new Integer(i).toString());`
If `i` is already an `Integer`, you only need to do `vars.put("test", i.toString());` |
33,896,729 | Just trying to convert an integer to a string.
```
vars.put("test", i);
```
I'd like to put the value in the variable "test", but it does not working and I think I must convert the int to a string.
But I have no idea how to do that.
I just found a out how to parsing string to integer in BeanShellSampler. | 2015/11/24 | [
"https://Stackoverflow.com/questions/33896729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5133750/"
] | Use [String.valueOf()](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(int)) method
```
vars.put("test", String.valueOf(i));
```
Additional information on Beanshell scripting in JMeter - [How to Use BeanShell: JMeter's Favorite Built-in Component](https://blazemeter.com/blog/queen-jmeters-built-componentshow-use-beanshell) | There is yet a shortcut way, how to cast an `int i` to `String s`:
>
> `String s = ""+i;` .. just that simple!
>
>
>
So the asked example:
>
> `vars.put("test", ""+i);`
>
>
>
..Seriously, nobody gave that answer yet? See i.e. [4105331](https://stackoverflow.com/questions/4105331/how-do-i-convert-from-int-to-string) for further info. |
68,016,297 | noticed PhpStorm doesn't format code properly. I'm using standard `Ctrl + Shift + L` shortcut and it works because it pops out info that content is properly formatted.
[](https://i.stack.imgur.com/kmLaF.png)
What's wrong? I'm using Material UI Theme. I've already tried to disable this plugin, no change.
[](https://i.stack.imgur.com/lMUxR.png) | 2021/06/17 | [
"https://Stackoverflow.com/questions/68016297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13824389/"
] | Open **File | Settings | Languages & Frameworks | Template Data Languages** & remove any customizations from there. That's a PhpStorm bug: <https://youtrack.jetbrains.com/issue/WI-42822> & <https://youtrack.jetbrains.com/issue/WI-42135>. | Goto Settings > Editor > File types.
For PHP files (as an example), look for PHP in the left column (under Recognize File Types), verify you have \*.php under the File name patterns column/box
That fixed it for me. |
199,384 | I have a 500 Gig external USB drive formatted as exFAT. I can not create an image from my 12.04 install to this drive with ReDo backup (I found out it lacks support for exFAT) . Note the image will be over 5 GIG so FAT32 is not an option for the external drive.
Is there another free program I can use to make an image? (Gui would be best)
Note I was able to add exfat support to 12.04 and can see the drive and add files manually as well as delete them. Thanks for any advise.
Please delete this post, I am new to linux and since I can not make an image I will not be using it anynore. I do not comprehend the answer but I appreciate the lone respone | 2012/10/12 | [
"https://askubuntu.com/questions/199384",
"https://askubuntu.com",
"https://askubuntu.com/users/73761/"
] | Simple way to find the version of C++ standard library is
```
gcc --version
```
Hope this helps | Fire up synaptic and search for libstdc++ and see which version is installed, or run `apt-cache search -n libstdc++` to see what versions are known, then you can check which one(s) are installed with `apt-cache policy libstdc++-XXXX` |
278,756 | Other than `tx` and `rx` being the transmit and recieve, can anyone explain what the fields mean in `ethtool -c`'s (Coalescing output) and what effect they have on how coalescing works?
```
Coalesce parameters for eth0:
Adaptive RX: off TX: off
stats-block-usecs: 999936
sample-interval: 0
pkt-rate-low: 0
pkt-rate-high: 0
rx-usecs: 18
rx-frames: 12
rx-usecs-irq: 18
rx-frames-irq: 2
tx-usecs: 80
tx-frames: 20
tx-usecs-irq: 18
tx-frames-irq: 2
rx-usecs-low: 0
rx-frame-low: 0
tx-usecs-low: 0
tx-frame-low: 0
rx-usecs-high: 0
rx-frame-high: 0
tx-usecs-high: 0
tx-frame-high: 0
``` | 2011/06/09 | [
"https://serverfault.com/questions/278756",
"https://serverfault.com",
"https://serverfault.com/users/2561/"
] | the delay between the tx and rx events and the generation of
interrupts for those events.
rx-frames[-irq]
rx-usecs[-irq]
tx-frames[-irq]
tx-usecs[-irq]
The frames parameters specify how many packets are received/transmitted
before generating an interrupt. The usecs parameters specify how many
microseconds after at least 1 packet is received/transmitted before
generating an interrupt. The [-irq] parameters are the corresponding
delays in updating the status when the interrupt is disabled. | Usable interrupt coalescing parameters for the Tigeon 3 Network cards [Image](https://i.stack.imgur.com/bYNGs.png)
From: <https://monarch.qucosa.de/api/qucosa%3A19496/attachment/ATT-0/> |
13,142,415 | one of the things we're building right now is a search functionality to look for people.
When starting simple, we've used Linq to entities to search, like this: `Entities.People.Where(z=>z.Birthdate < birthdate).ToList()`
Then, when new searchcriteria were added, the linq statement grew and grew, and now we have to refactor it because nobody understands it anymore.
At this point, we must facilitate search for 8 related items, like 'did you work here', 'do you speak this language', 'from these 6 skills, which ones do you master' etc.
All these items are 1:N or N:N relations in SqlServer, and we are searching for multiple items AND we want to know 'how much match' you have.
For example: we look for people who speak french and or English and or German, and we want to get all people who have at least 1 match, and for those people, we want to know how many matches (ie 1 out of 3 or 2 out of 3) every person has.
At this point the question is: what is a smart thing to do (approx 10.000 people in the database).
Brainstorming has lead us to the following options:
1. Do the quickest search in the database (so you retrieve limited
amount of records) and sort the rest in code
2. Keep on building with Linq
3. Perform the whole action in SqlServer
Any tips to get us started? | 2012/10/30 | [
"https://Stackoverflow.com/questions/13142415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103089/"
] | In WinForms:
Select the PictureBox -> properties -> BackColor -> web -> Transparent | What's the image type?
If it's a Bitmap object, you probably have a 24 bit bgr image. To get it to be transparent, you would need to make it a 32 bit bgra image and change every pixel which has the background color to have 0 in the a channel.
If it's an 8-bit color-mapped image, you would change the palette entry for the background color to a color with 0 in the a channel. |
350,130 | [](https://i.stack.imgur.com/TEQPv.jpg)
[](https://i.stack.imgur.com/NnxuT.jpg)
[](https://i.stack.imgur.com/nN2e4.jpg)
Hi, I am an amateur who is making a historical map.
As you can see in the picture, I have a problem using qgis2web.
The first picture is a normal scene output from QGIS version 3.8.
The second picture was taken from qgis2web with a Mapbox. Transparency is nice, but the text in the labels is terrible.
The third picture was taken from qgis2web with openlayers. Transparency, text in labels, it's all a mess.
I tested [this site](http://eastmaps.com/2019/09/10/%ED%85%8C%EC%8A%A4%ED%8A%B8/) a year ago, but it was fine at the time. What should I do ? It's too hard... | 2020/02/10 | [
"https://gis.stackexchange.com/questions/350130",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/157873/"
] | I finally got the answer!
I set the opacity of the color of the layer.
But the opacity of the layer rendering was 100%.
When I lowered the opacity of layer rendering, not a single symbol, the qgis2web worked successfully.
People who are struggling with this, I hope it helps! | Open the HTML file in notepad and scroll down the code until you get to the layer you want the transparency to change. it should look something like:
function style\_20YearFlood\_2\_0() {
```
return {
pane: 'pane_20YearFlood_2',
opacity: 1,
color: 'rgba(35,35,35,1.0)',
dashArray: '',
lineCap: 'butt',
lineJoin: 'miter',
weight: 1.0,
fill: true,
fillOpacity: 1,
fillColor: 'rgba(255,158,23,1.0)',
interactive: false,
```
20 year flood in my case was the layer I wanted to be partly transparent.Then just change the "fillOpacity:" to whatever you want. I chose 50% so it now looks like:
function style\_20YearFlood\_2\_0() {
```
return {
pane: 'pane_20YearFlood_2',
opacity: 0.5,
color: 'rgba(35,35,35,1.0)',
dashArray: '',
lineCap: 'butt',
lineJoin: 'miter',
weight: 1.0,
fill: true,
fillOpacity: 0.5,
fillColor: 'rgba(255,158,23,1.0)',
interactive: false,
```
Save the file, and then open the html in your browser. It should now be transparent to whatever % you indicated.
Hope this helps!
Ian |
19,763,955 | I am using following config for timezone in **config.php**
```
'timeZone' => 'UTC',
```
It is working fine and all dates are stored in database according to **UTC**. Now each user has its own timezone in his/her profile like **UTC+5**, **UTC-5**, **UTC+0**, etc.
Now how can I show dates in reports according to user timezone. I used active record to fetch records from database. Is there any general way for all queries or we have to convert date to user timezone each time manually in php ??
Thanks. | 2013/11/04 | [
"https://Stackoverflow.com/questions/19763955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300118/"
] | You can set Timezone in Yii by adding below value in main.php file of config
```
return array(
'timeZone' => 'Asia/Kolkata',
)
```
For time zone list in PHP : <http://php.net/manual/en/timezones.php> | After loading user data try:
>
>
> ```
> Yii:app()->timeZone = $userTimezone;
>
> ```
>
>
where $userTimezone - is loaded user timezone from db. It's for using in Yii
OR you can set timezone in mysql ones by:
>
>
> ```
> Yii::app()->db->createCommand('SET time_zone = <timezonename>')->execute()
>
> ```
>
>
and all TIMESTAMP fields will be in setted timezone for current session |
19,763,955 | I am using following config for timezone in **config.php**
```
'timeZone' => 'UTC',
```
It is working fine and all dates are stored in database according to **UTC**. Now each user has its own timezone in his/her profile like **UTC+5**, **UTC-5**, **UTC+0**, etc.
Now how can I show dates in reports according to user timezone. I used active record to fetch records from database. Is there any general way for all queries or we have to convert date to user timezone each time manually in php ??
Thanks. | 2013/11/04 | [
"https://Stackoverflow.com/questions/19763955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300118/"
] | You can set Timezone in Yii by adding below value in main.php file of config
```
return array(
'timeZone' => 'Asia/Kolkata',
)
```
For time zone list in PHP : <http://php.net/manual/en/timezones.php> | You can use afterFind to change the time accordingly
```
public function afterFind()
{
//apply your logic here
$zone = Yii:app()->timeZone;
// I don't know code to change time zone, so I assume there is a function named "functionToChangeTimeZone"
$this->time = functionToChangeTimeZone($this->time , $zone);
return parent::afterFind();
}
```
now every record will have there time zone changed according their settings |
20,290,224 | I'm trying to make a function with an array in PHP. Using a library called simple\_html\_dom.php to extract data from a site.
I've made a piece of code that work exactly how It's suppose to but its to repetitive. So I wanted to create a function with an array.
**Here the code I'm trying to make into a function this code works**
```
include('simple_html_dom.php');
$pos = 0;
$food = 1;
$col_num = array();
$col_food = array();
$html = file_get_html('website');
for($i = 0;$i<220;$i+=11){
// Extract all text from a given cell
//insert data into the array to the field it belongs to
array_push($col_num, $html->find('td', $i)->plaintext);
array_push($col_food, $html->find('td', $food)->plaintext);
$food += 11;
}
for($row = 0;$row<=19;$row++){
echo $col_num[$row].$col_food[$row]."<br>";
}
```
**Here is the code I attempted to make a function with an array**
```
include('simple_html_dom.php');
$pos = 0;
$food = 1;
$col_num = array();
$col_food = array();
$html = file_get_html('website');
function getcoleachrow($col = array(), $value){
for($value=$value;$value<220;$value+=11){
array_push($col, $html->find('td', $value)->plaintext);
}
for($rows = 0;$rows<=19;$rows++){
echo $col[$rows]."<br>";
}
}
getcoleachrow($col_num, $num);
getcoleachrow($col_food, $food);
```
The error message I'm getting is "**Notice: Undefined variable: html**" and "**Fatal error: Call to a member function find() on a non-object**" this is on the array\_push line in the function code. | 2013/11/29 | [
"https://Stackoverflow.com/questions/20290224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2802187/"
] | The problem is that $html is out of scope. You need to pass $html into the getcoleachrow function, e.g.:
```
function getcoleachrow($col = array(), $value, $html){
for($value=$value;$value<220;$value+=11){
array_push($col, $html->find('td', $value)->plaintext);
}
for($rows = 0;$rows<=19;$rows++){
echo $col[$rows]."<br>";
}
}
getcoleachrow($col_num, $num, $html);
```
And yes, I agree with Marc B - a good place to look for more information on the subject is here: <http://php.net/manual/en/language.variables.scope.php> | You need to add `global $html;` inside the function...
```
function getcoleachrow($col = array(), $value){
global $html;
for($value=$value;$value<220;$value+=11){
array_push($col, $html->find('td', $value)->plaintext);
}
for($rows = 0;$rows<=19;$rows++){
echo $col[$rows]."<br>";
}
}
``` |
45,886,682 | How can one store a variadic template to enable reuse in later instances?
Code Example:
```
template <typename T, typename ...initArgs>
Collection_class {
std::vector<T> storage;
initArgs ...constructorArguments;
Collection_class<T, initArgs>(initArgs... args) {
constuctorArguments = args;
}
void CreateInstance() {
storage.emplace(constructorArguments);
}
}
```
Is there any way you can store a varidic template as an object/collection that would enable you to reuse it, in this case for a constructor?
I have seen people storing the arguments in a `std::tuple` however I am unsure how I could use that in a generic class.
Much thanks, JJ. | 2017/08/25 | [
"https://Stackoverflow.com/questions/45886682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8137872/"
] | You can acheive this by storing the arguments in a tuple:
```
#include <vector>
#include <tuple>
template<typename T, int index, typename ...initArgs>
struct VectorInit {
static void append(std::vector<T> & dst,
std::tuple<initArgs...> const& args) {
VectorInit<T, index-1, initArgs...>::append(dst, args);
dst.emplace_back(std::get<index>(args));
}
};
template<typename T, typename ...initArgs>
struct VectorInit<T, 0, initArgs...> {
static void append(std::vector<T> & dst,
std::tuple<initArgs...> const& args) {
dst.emplace_back(std::get<0>(args));
}
};
template <typename T, typename ...initArgs>
class Collection_class {
std::vector<T> storage;
std::tuple<initArgs...> init_args;
public:
Collection_class(initArgs... args)
: init_args(args...) {
}
void CreateInstance() {
storage.reserve(sizeof...(initArgs));
VectorInit<T, sizeof...(initArgs)-1, initArgs...>::append(storage, init_args);
}
};
int main() {
Collection_class<double, float, int> test(1.2f, 4);
test.CreateInstance();
}
```
**Edit:** `CreateInstance()` can be implemented by recursively peeling each element of the tuple. I did it from `sizeof...(args)` to 0, which is why the recursion happens before the `emplace_back`.
There's probably a neater way to do this with parameter pack expansions, but this is a simple enough case that I find the template specialization route to be simpler. | Why don't you simply let the `std::vector` handle that:
```
template <typename T>
Collection_class {
std::vector<T> storage;
public:
Collection_class<T>(std::initializer_list<T> initargs) : storage(initargs) {
}
}
```
Note the deferred `CreateInstance()` won't be necessary anymore.
---
The `initArgs` variadic template parameters would let your `Collection_class` instantiations *"explode"* for any possible combination of parameters. That's certainly not what you actually want. |
51,908,039 | I have messages screen and implement custom `tableviewcell` for the display message. A message should be `text` or `image` and some case I need to display boxes with information(see image sender and receiver). it's working fine but some time messages view cut off(see image messages). I have used many `stackViews` to hiding and show some views.
Please find the [code here](https://files.fm/u/9ktvf5rr) for more understanding.
[](https://i.stack.imgur.com/1wp7p.png)
[](https://i.stack.imgur.com/oFUEm.png)
[](https://i.stack.imgur.com/0Y1f5.png) | 2018/08/18 | [
"https://Stackoverflow.com/questions/51908039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910061/"
] | I noticed that it was just some variables that didn't reset and after making a reset() function that resets those variables it worked! | Try to call `recreate()`. This works for me. |
211,243 | I have code looking something like this:
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table
SET BlobData = '" . mysql_real_escape_string($data) . "',
BlobHash = '$hash'
";
mysql_query($query);
```
I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.
Is there anything more efficient than the following solution?
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'";
mysql_query(sprintf($query, mysql_real_escape_string($data)));
``` | 2008/10/17 | [
"https://Stackoverflow.com/questions/211243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28835/"
] | Have you benchmarked the output buffering trick?
```
ob_start();
echo 'INSERT INTO some_table SET BlobData = \'', mysql_real_escape_string( $data ), '\', BlobHash = \'', $hash, '\'';
mysql_query( ob_get_clean() );
```
Another thing you could do is convert to mysqli or MDB2, which support bound parameters. That would allow you to skip the mysql\_real\_escape\_string call **and** the string concatenations. | Well if memory usage is your problem, you can read the large file in chunks and insert these chunks with CONCAT into the database field.
Sample code (not tested):
```
$id = 1337;
$h = fopen("path/to/file.ext", "r");
while (!feof($h))
{
$buffer = fread($h, 4096);
$sql = "UPDATE table SET my_field = CONCAT(my_field, '" . mysql_real_escape_string($buffer) . "') WHERE Id = " . $id;
mysql_query($sql);
}
```
This method will be slower but you'll require only 4Kb of your memory. |
211,243 | I have code looking something like this:
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table
SET BlobData = '" . mysql_real_escape_string($data) . "',
BlobHash = '$hash'
";
mysql_query($query);
```
I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.
Is there anything more efficient than the following solution?
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'";
mysql_query(sprintf($query, mysql_real_escape_string($data)));
``` | 2008/10/17 | [
"https://Stackoverflow.com/questions/211243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28835/"
] | If you are using PDO, and prepared statments you can use the PDO::PARAM\_LOB type. See example #2 on the LOB page showing how to insert an image to a database using the file pointer.
<http://us2.php.net/manual/en/pdo.lobs.php> | Have you benchmarked the output buffering trick?
```
ob_start();
echo 'INSERT INTO some_table SET BlobData = \'', mysql_real_escape_string( $data ), '\', BlobHash = \'', $hash, '\'';
mysql_query( ob_get_clean() );
```
Another thing you could do is convert to mysqli or MDB2, which support bound parameters. That would allow you to skip the mysql\_real\_escape\_string call **and** the string concatenations. |
211,243 | I have code looking something like this:
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table
SET BlobData = '" . mysql_real_escape_string($data) . "',
BlobHash = '$hash'
";
mysql_query($query);
```
I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.
Is there anything more efficient than the following solution?
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'";
mysql_query(sprintf($query, mysql_real_escape_string($data)));
``` | 2008/10/17 | [
"https://Stackoverflow.com/questions/211243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28835/"
] | You have two issues here:
#1, there are several different ways you can compute the MD5 hash:
* Do as you do and load into PHP as a string and use PHP's `md5()`
* Use PHP's `md5_file()`
* As of PHP 5.1+ you can use PHP's streams API with either of `md5` or `md5_file` to avoid loading entirely into memory
* Use `exec()` to call the system's `md5sum` command
* Use MySQL's `MD5()` function to compute the hash
Since these are all trivial to implement it would be easy for you to implement and benchmark them all for memory usage and speed. Here are [some benchmarks](http://www.php.net/manual/en/function.md5-file.php#81751) showing system md5 via `exec` to be a lot faster than PHP's `md5_file` as file size increases. Doing it your way is definitely the worst way as far as memory usage is concerned.
#2, `mysql_real_escape_string` performs a database query, so you're actually transmitting your blob data to the database, getting it back as a string, and transmitting it again(!) with the INSERT query. So it's traveling to/from the DB server 3x instead of 1x and using 2x the memory in PHP.
It's going to be more efficient to use [PHP5 prepared statements](http://devzone.zend.com/node/view/id/686#Heading11) and only send this data to the database once. Read the linked article section, you'll see it mentions that when you are binding parameters, you can use the blob type to stream blob data to the DB in chunks. The [PHP docs for `mysqli_stmt::send_long_data`](http://www.php.net/manual/en/mysqli-stmt.send-long-data.php) have a great simple example of this that INSERTs a file into a blob column just like you are.
By doing that, and by using either the streams API, `md5_file` or `exec` with the system md5 command, you can do your entire INSERT without ever loading the entire file into memory, which means memory usage for your series of operations can be as low as you want! | Have you benchmarked the output buffering trick?
```
ob_start();
echo 'INSERT INTO some_table SET BlobData = \'', mysql_real_escape_string( $data ), '\', BlobHash = \'', $hash, '\'';
mysql_query( ob_get_clean() );
```
Another thing you could do is convert to mysqli or MDB2, which support bound parameters. That would allow you to skip the mysql\_real\_escape\_string call **and** the string concatenations. |
211,243 | I have code looking something like this:
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table
SET BlobData = '" . mysql_real_escape_string($data) . "',
BlobHash = '$hash'
";
mysql_query($query);
```
I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.
Is there anything more efficient than the following solution?
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'";
mysql_query(sprintf($query, mysql_real_escape_string($data)));
``` | 2008/10/17 | [
"https://Stackoverflow.com/questions/211243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28835/"
] | If you are using PDO, and prepared statments you can use the PDO::PARAM\_LOB type. See example #2 on the LOB page showing how to insert an image to a database using the file pointer.
<http://us2.php.net/manual/en/pdo.lobs.php> | Well if memory usage is your problem, you can read the large file in chunks and insert these chunks with CONCAT into the database field.
Sample code (not tested):
```
$id = 1337;
$h = fopen("path/to/file.ext", "r");
while (!feof($h))
{
$buffer = fread($h, 4096);
$sql = "UPDATE table SET my_field = CONCAT(my_field, '" . mysql_real_escape_string($buffer) . "') WHERE Id = " . $id;
mysql_query($sql);
}
```
This method will be slower but you'll require only 4Kb of your memory. |
211,243 | I have code looking something like this:
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table
SET BlobData = '" . mysql_real_escape_string($data) . "',
BlobHash = '$hash'
";
mysql_query($query);
```
I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.
Is there anything more efficient than the following solution?
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'";
mysql_query(sprintf($query, mysql_real_escape_string($data)));
``` | 2008/10/17 | [
"https://Stackoverflow.com/questions/211243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28835/"
] | Would it make any difference if you didn't put the query into another variable, but instead passed it directly into the MySQL command. I've never tried this, but it may make a difference as the whole string isn't stored in another variable. | Well if memory usage is your problem, you can read the large file in chunks and insert these chunks with CONCAT into the database field.
Sample code (not tested):
```
$id = 1337;
$h = fopen("path/to/file.ext", "r");
while (!feof($h))
{
$buffer = fread($h, 4096);
$sql = "UPDATE table SET my_field = CONCAT(my_field, '" . mysql_real_escape_string($buffer) . "') WHERE Id = " . $id;
mysql_query($sql);
}
```
This method will be slower but you'll require only 4Kb of your memory. |
211,243 | I have code looking something like this:
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table
SET BlobData = '" . mysql_real_escape_string($data) . "',
BlobHash = '$hash'
";
mysql_query($query);
```
I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.
Is there anything more efficient than the following solution?
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'";
mysql_query(sprintf($query, mysql_real_escape_string($data)));
``` | 2008/10/17 | [
"https://Stackoverflow.com/questions/211243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28835/"
] | You have two issues here:
#1, there are several different ways you can compute the MD5 hash:
* Do as you do and load into PHP as a string and use PHP's `md5()`
* Use PHP's `md5_file()`
* As of PHP 5.1+ you can use PHP's streams API with either of `md5` or `md5_file` to avoid loading entirely into memory
* Use `exec()` to call the system's `md5sum` command
* Use MySQL's `MD5()` function to compute the hash
Since these are all trivial to implement it would be easy for you to implement and benchmark them all for memory usage and speed. Here are [some benchmarks](http://www.php.net/manual/en/function.md5-file.php#81751) showing system md5 via `exec` to be a lot faster than PHP's `md5_file` as file size increases. Doing it your way is definitely the worst way as far as memory usage is concerned.
#2, `mysql_real_escape_string` performs a database query, so you're actually transmitting your blob data to the database, getting it back as a string, and transmitting it again(!) with the INSERT query. So it's traveling to/from the DB server 3x instead of 1x and using 2x the memory in PHP.
It's going to be more efficient to use [PHP5 prepared statements](http://devzone.zend.com/node/view/id/686#Heading11) and only send this data to the database once. Read the linked article section, you'll see it mentions that when you are binding parameters, you can use the blob type to stream blob data to the DB in chunks. The [PHP docs for `mysqli_stmt::send_long_data`](http://www.php.net/manual/en/mysqli-stmt.send-long-data.php) have a great simple example of this that INSERTs a file into a blob column just like you are.
By doing that, and by using either the streams API, `md5_file` or `exec` with the system md5 command, you can do your entire INSERT without ever loading the entire file into memory, which means memory usage for your series of operations can be as low as you want! | Well if memory usage is your problem, you can read the large file in chunks and insert these chunks with CONCAT into the database field.
Sample code (not tested):
```
$id = 1337;
$h = fopen("path/to/file.ext", "r");
while (!feof($h))
{
$buffer = fread($h, 4096);
$sql = "UPDATE table SET my_field = CONCAT(my_field, '" . mysql_real_escape_string($buffer) . "') WHERE Id = " . $id;
mysql_query($sql);
}
```
This method will be slower but you'll require only 4Kb of your memory. |
211,243 | I have code looking something like this:
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table
SET BlobData = '" . mysql_real_escape_string($data) . "',
BlobHash = '$hash'
";
mysql_query($query);
```
I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.
Is there anything more efficient than the following solution?
```
$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'";
mysql_query(sprintf($query, mysql_real_escape_string($data)));
``` | 2008/10/17 | [
"https://Stackoverflow.com/questions/211243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28835/"
] | If you are using PDO, and prepared statments you can use the PDO::PARAM\_LOB type. See example #2 on the LOB page showing how to insert an image to a database using the file pointer.
<http://us2.php.net/manual/en/pdo.lobs.php> | Would it make any difference if you didn't put the query into another variable, but instead passed it directly into the MySQL command. I've never tried this, but it may make a difference as the whole string isn't stored in another variable. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.