id
stringlengths 50
55
| text
stringlengths 54
694k
|
---|---|
global_01_local_0_shard_00000017_processed.jsonl/33543 | Take the 2-minute tour ×
I have a VPS running on hypervm
in proceses list i have something like this
> /usr/libexec/mysqld --basedir=/usr
user : mysql
which takes 150 mb RAM
and then
/usr/sbin/named -u named -t /var/named/chroot
user : Named
50 mb RAM taken by this process
how can i solve this overusage of RAM and reduce it .
I have access to root and SSH
share|improve this question
add comment
2 Answers
up vote 2 down vote accepted
Do you use MySQL and/or Bind on this VPS? If not, remove or disable them. Otherwise, you'll need to dive into the configuration files for both services.
If all else fails, add more memory!
share|improve this answer
that's correct bind and mysql are not good togather.. – Mac Taylor May 15 '11 at 7:16
add comment
HyperVM isn't a virtualization platform, it's a control panel for either OpenVZ or Xen. Which of those your VPS is running on could be important for solving this, so you should find out which you are using.
If you're on OpenVZ, some of that memory "usage" could come from it measuring stack allocation instead of actual used memory. You should run 'ps aux' and pay attention to the RSS and the VSZ fields. If named or mysql are low in RSS but high in VSZ, you should try reducing the stack size with something like 'ulimit -s 256' in the startup script for the service. See lowendbox's article on this.
MySQL's memory usage can be cut way down by removing non-MyISAM table support, if your application will be alright with that. lowendbox has many articles about this, including one on running 18 static sites and wordpress on a 64MB VPS.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33555 | Forgot your password?
+ - Slashdot's own "Nobots" is now in print!
Submitted by mcgrew
mcgrew writes "Nobots isn't a Dice Holdings book, it's a slashdot book. The first chapter written was a response to a comment in a slashdot story way back in 2009. Quite a few chapters were typed directly into slashdot's journal entry. A few were posted before a book became apparent and all of them garnered comments that improved the story, and it became a book. Your book.
Right now you can only get it here, which I hope to change because of problems with the cover, the ISBN, and the bar code.
The crude first drafts of its chapters are here at slashdot already, and the final polished versions will be posted in my site weekly starting next Saturday. Chapter 1 is here. Chapter 2 will be posted Saturday.
The final book is about twice as long as the draft. It's a CC license, free to read, only the printed versions cost. Enjoy!"
Slashdot's own "Nobots" is now in print!
Comments Filter:
|
global_01_local_0_shard_00000017_processed.jsonl/33556 | Forgot your password?
Comment: Re:Is it on another planet? (Score 1) 405
by DwySteve (#34418494) Attached to: NASA Finds New Life (This Afternoon)
And more importantly, it would mean end of religions, unless we want to fool ourselves now on new, grandiose scale.
How do you figure? I don't recall any religions based on the tenant that arsenic-based life is impossible. Even the Catholic Church's official position on sentient alien life is that there's no reason it can't exist. It just introduces a bunch of largely philosophical questions about whether Jesus's sacrifice was just for us or for all sentient life and whether we have to start proselytizing. Read C.S. Lewis's space trilogy if you want a Christian perspective on alien life.
Comment: Re:These aren't cost overruns (Score 1) 153
by DwySteve (#34207860) Attached to: James Webb Space Telescope Cost Overruns Adding Up
This is why I would love to see the government sue people who grossly underbid contracts.
Governments typically ask companies to bid on things that may or may not be possible, then force them to put a price on it. Now you want them to be sued as well?
I can believe that companies keep using the same methodologies to make these bids, but don't understand why the government doesn't turn a wary eye to these predictions and multiply the given amount based on historical data. Then again, if nothing like this has ever been attempted it's hard to rely on historical data. No two projects will be over cost and over budget in the same way.
by DwySteve (#33725284) Attached to: Selling Incandescent Light Bulbs As Heating Devices
I don't know where you buy your CFLs from, but the ones I have come on like any normal incandescent light build does.
I guess you either live somewhere that's warm all the year round or you heat your rooms 24 hours a day. In winter mornings my room temperature is about 5 degrees C and it takes a minute for the CFLs to reach normal brightness. My wife insists that we keep the stairway light on all night so that the stairs are well lit, so I am not exactly sure we save any energy.
Cripes man! It's 5C in your house and the LIGHT is too slow for you? It'll take an hour to heat that space up.
I haven't had any trouble with the Sylvania Instant-On bulbs - get them in 2700K 'temperature' and they're just like incandescents. Then again, I live in Florida and it doesn't usually get that cold here.
Comment: Re:First Union? (Score 1) 576
by DwySteve (#33722506) Attached to: Unions Urging Actors Not To Work On Hobbit Movie
Otherwise, it's the same 'I've got mine so screw you' attitude that the greedy owners are taking.
Unless you're self-employed, if it wasn't for those "greedy owners", you'd be begging on the streets. That's why the anti-business mentality is so idiotic - without businesses the majority of people would be unemployed.
I agree with you entirely, but we must remember that when unions feel the need to organize to fight for something it's usually because whoever is running the business is being a bit too greedy. It doesn't apply to all businesses.
That being said, I am working towards setting up my own business and although I consider myself an enlightened person I find myself thinking very greedily. The whole purpose of setting up a business for me is 1) follow my passions and 2) get really really rich while doing it. The prospects for getting really really rich by just being a worker for 30 years are nil, even if you're an engineer, thus my reason for going into business.
I do want to do things like institute rules that are equitable, such as 'No employee may make more than 5x what the lowest paid employee makes.' But then a little voice inside of me says 'To hell with that, I want a million dollar salary and I'm not paying my plebes 200K a year! They don't deserve it! How complicated are their jobs!? *I* DESERVE IT DAMNIT! I TOOK THE RISK OF STARING MY OWN BUSINESS BLAH BLAH BLAH...'
The truth of the matter is, business owners/runners are not of an entirely different breed than workers. Most small business/entrepreneurs are people who don't see themselves as taking a risk - they know their target market/product well enough to realize their chances. And most of them don't use their own money to finance their business - they sell stock, borrow from banks, etc. And since their business is a corporation they just get to shut down when things get bad and creditors get 50 cents on the dollar if they're lucky. Then they can start a new business. The workers carry the same amount of risk as the owner for the most part. The only real risk to the owner is legal/civil proceedings. And the answer to that is - don't be a scumbag and you get a lot safer.
Of course, if most businesses could handle NOT being scumbags there'd be much less call for unions....
by DwySteve (#33721560) Attached to: Motorcyclist Wins Taping Case Against State Police
Just remove the monetary incentive. Fines are a stupid idea for a punishment even in a capitalist system.
Perhaps the system could be fixed significantly if the money from the ticket didn't go immediately back to the town in which the ticket was written, instead perhaps being given to the state and channeled equitably to the various towns and areas with police forces.
Comment: Re:First Union? (Score 2, Insightful) 576
by DwySteve (#33710598) Attached to: Unions Urging Actors Not To Work On Hobbit Movie
Those health insurance and retirement benefits won by the union?
So.. in your estimation unions shouldn't be fighting for the betterment of all workers, rather, good treatment is a benefit for those who pay for it.
I'd rather have real good guys in the fight for me - someone who fights for the better treatment of all workers, not just their friends. Otherwise, it's the same 'I've got mine so screw you' attitude that the greedy owners are taking.
Comment: Re:First Union? (Score 1) 576
by DwySteve (#33710562) Attached to: Unions Urging Actors Not To Work On Hobbit Movie
Excuse me, but aren't those things criminal? It looks like you're confusing unions with the mob.
It is, sadly, a close thing in some places/lines of work. Try garbage pickup in New York city. I've heard of businesses whose employees were required to take home a bag of garbage every week because the contracted garbage company didn't pick up the garbage. Of course, it was either required legally or 'in your best interest' (for whatever reason, be it intact kneecaps or doing it allowed you to deal with other unionized labor you needed) to choose this company to be your garbage collector. No matter what they did or didn't do, you have to keep them on. And it happened to have unionized labor.
There are such things as good unions. The handle contract negotiations for their members (where I live they apply equally to non-members, who tend to be quite happy about that). And when they call for a strike, I think they even reimburse non-members for their lost income (non-members will have to chose whether they join the strike and lose income, or go to work and sit there on their own). Good unions do not demand any kind of exclusivity, and personally I think any kind of exclusivity contract needs to be illegal. (Unfortunately it rarely it.)
This is very true, and I wish it was more prevalent. Sadly, when a lot of money is concentrated in any one place, even .01% of it is a fortune to someone. There's too much profit to be had by finding/creating a small cesspool where a little bit of money flows in and never flows out. This goes for everything - government, labor, corporations.
Comment: Re:...or you could add something for yourself... (Score 2, Insightful) 519
by DwySteve (#33678068) Attached to: As smart-phones go, my phone is ...
This has always bugged the hell out of me.
Is it my fault that serving staff are paid less? Am I obligated to pay them a tip, because their boss won't pay them a reasonable wage? Is it my problem that they can't/haven't gotten a better-paying job?
I agree with you, but we can also do something (maybe). Is there somewhere a list of places that DO pay their servers/waiters well that we can frequent? Heck, I'd start my own restaurant - with a big sign: "No tipping please, our waiters act professional and are paid accordingly. We don't keep unprofessional service staff around because we care about your dining experience."
Comment: Re:Weve seen that argument before (Score 1) 1066
by DwySteve (#33610498) Attached to: HDCP Master Key Is Legitimate; Blu-ray Is Cracked
And if you've ever bought used textbooks on the Internet, you'll probably quickly discover what a sweet discount you can get when the global market stays global for you. I've bought plenty of (English-language) textbooks that were originally sold to the Indian subcontinent; they're exactly the same between the covers as the American editions but priced quite differently, and you can often save some good money.
Do watch out though - I have seen some odd differences in the books. I believe one thermodynamics text many of us bought online only had metric-unit problems in the back instead of metric and imperial. It's kind of a small difference, but it can bite you.
Comment: Re:Weve seen that argument before (Score 1) 1066
by DwySteve (#33610448) Attached to: HDCP Master Key Is Legitimate; Blu-ray Is Cracked
I think that in a world without Copyright (and the like) the only think we would not have is the crap copyrightable stuff (e.g., Britney Spears, Eminem, etc...) mainly because such media is only famous due to its heavy marketing and not its quality.
Of course, it's all clear now! Without copyright, only the music you like would exist, and the music that other people like wouldn't. You just confirmed that copyright is doing what it's supposed to - helping produce music that people enjoy. But since only plebes enjoy that kind of music you're fine with trashing copyright.
Screw you. I like Eminem. I'd rather see him stick around than not. Your elitism does not make a persuasive argument for getting rid of copyright.
Comment: Re:Stop Sleepwalking! (Score 5, Insightful) 278
by DwySteve (#33567622) Attached to: Wal-Mart To Launch Unlimited Wireless Family Plan
Now that these companies have trashed any form of local retailer, they have to expand into new areas to swell their profits; this is why they now offer mobile phones, home insurance, pharmaceuticals and even home mortgages in some instances.
When is the populace going to wake up & realise that cheap is not necessarily best? >
I come at this from a different angle. I grew up in a town that was 20 minutes from a city. There were towns farther out that were an hour or two from anything worthwhile.
Living in these places SUCKS!
Everyone keeps going on about 'mom and pop' and 'buy local' but the experience I've had with local businesses in places like these is that they get away with charging obscene prices because they're the only game in town. Milk - costs more at the local mom and pop store because you have to drive 20 minutes in any direction to find a competitor. Gas? Same deal. And the selection is awful. You get whatever they give you and nothing more. People would drive an hour to get to a real store - a Walmart or a Target or a Best Buy - and stock up for a week or weeks at a time. Driving an hour to get a better price on gas when filling up your 100 gallon tank was justified.
So Walmart comes around and wants to build a store in your podunk town and suddenly hippes and 'progressives' from the city are telling you to oppose it because it 'destroys local business'. What? Mom and pop were trying to destroy us slowly with high prices and terrible selection for years, and now someone wants us to help them out because Walmart comes in and charges us a reasonable price for something? AND has a better selection? No thank you.
You know what else you get with a Walmart? It's a little slice of civilization compared to what you can find out there. That odd DVD rental machine in the front? A Godsend to someone who has no video rental store. And the faux bank where you can cash checks, send money, and have your taxes done in season? Compared to what was on offer before there was Walmart it's amazing. You go to a Wal-Mart in Chicago, Los Angeles, or Walcott Iowa and it's always the same - same selection, same prices, no favoritism, no prejudice no bullshit. They just sell you things.
So now they do cell phones too? If you live in a city, yeah, it's superfluous. If you live in the middle of nowhere it's another Godsend (as long as your nowhere has T-Mobile anyway). To have a place that will sell you something for a fair price and give you a decent selection of phones? Listen, you all may take it for granted, but plenty of people don't live in Chicago or New York or Los Angeles. They have significantly fewer options and Wal-Mart is on the whole a positive for them.
|
global_01_local_0_shard_00000017_processed.jsonl/33557 | Forgot your password?
Comment: Re:Can Apple be Far Behind? (Score 1) 194
by Karlt1 (#46440567) Attached to: Google Blocking Asus's Android-Windows "Duet"?
It should certainly be possible to put that in a MacBook Air to allow it to run iOS 7 and onward, so we can have both low power tablet and high power OSX in one small package.
There is no need to have an A7 in the Macbook Air to run iOS apps.
There is already a fully functional version of iOS 7 that runs on x86 based Macs and there has been since the app store was introduced. In fact I doubt that there is a single app in existence for iOS that hasn't at one point been run natively on an x86 based Mac.
When a developer runs an iOS app on the iPhone simulator for the Mac, they are not running on an emulator, the app is compiled as an x86 binary and linked against an x86 build of the iOS libraries.
Comment: Re:Google more restrictive than Microsoft (Score 4, Insightful) 194
by Karlt1 (#46440535) Attached to: Google Blocking Asus's Android-Windows "Duet"?
The one that wrote the article either has no clue what he was writing about or he's getting paid to be dumb. Basically, you want to use Google's services? You gotta do it the way *they* want you to do it. It's their services and their terms.
" if Google did not act, we faced a Draconian future, a future where one man, one company, one device, one carrier would be our only choice. So if you believe in openness, if you believe in choice, if you believe in innovation from everyone, then welcome to Android. Now letâ(TM)s get started.â
Andy Rubin......
Comment: Re: This sounds like accidents waiting to happen (Score 1) 264
by Karlt1 (#46392077) Attached to: Apple Launches CarPlay At Geneva Show
Now frankly, as a stockholder, I'd prefer that he'd work on getting Apple's diminishing marketshare issues resolved first before the Jobs Reality Distortion Effect finally wears off before spending time on green issues otherwise the green issues are kinda moot... but that's just me.
Right because chasing market share by lowering prices has worked so well for PC makers and Android manufacturers.
Comment: Re:Isn't there, though? (Score 1) 179
by Karlt1 (#46372933) Attached to: Apple's Messages Offers Free Texting With a Side of iPhone Lock-In
And then they turned their phone off. Do you expect Firefox to still be refreshing your tabs while your computer is powered off and dismantled?
They may have turned their phone off, but that doesn't mean that they turned off their iPod Touch, iPad, or Mac that are all capable of receiving iMessages.
Comment: Re:I thought this had been settled long ago. (Score 1) 491
by Karlt1 (#46348155) Attached to: Do We Really Have a Shortage of STEM Workers?
Mod parent up!
This is exactly what is going on. There isn't a shortage of STEM workers at all. There is a shortage of STEM workers willing to work for minimum wage. What companies want is H1-B factories. Cheap foreign labor. I don't know who will buy their products when nobody has a high enough paying job to afford them though.
I see hundreds of listings in the area where I live for qualified developers with a salary between $80 - $105,000, I've personally never had to look for more than two weeks to find another job. No it's not in California and the cost of living is not that high here.
Comment: Re:Run. (Score 2) 263
by Karlt1 (#46336679) Attached to: Ask Slashdot: When Is a Better Career Opportunity Worth a Pay Cut?
"Career opportunities" don't come with pay cuts. They come with pay raises. Run
Not true, for example if you're making good money as a "Senior COBOL developer" and all you do is maintenance work, it may make sense to take a slight pay cut to move into a newer technology and get architecture experience.
Comment: Re: Antitrust, are you kidding? (Score 1) 742
by Karlt1 (#46318671) Attached to: "Microsoft Killed My Pappy"
No. There will always be people who use Microsoft (for reasonable values of always), just as there will always be people who can't properly use the BLOCKQUOTE tag on Slashdot :-) Your inference falsely assumes that all the people in the world will eventually get a clue :-)
Comment: Re: Roku has Amazon Video Channel already, so why? (Score 2) 104
by Karlt1 (#46318071) Attached to: Amazon To Put Android In Set-top Box To Compete With Apple, Roku
The ability to use a phone other than an iPhone. Currently, Apple has a monopoly on phones compatible with Amazon video.
That's a weird business decision on the part of Amazon. Amazon Instant works on the Android based Fire. Why they decide not to support other Android devices is anyone's guess.
|
global_01_local_0_shard_00000017_processed.jsonl/33558 | Forgot your password?
Comment: Re:LinkedIn uses Node (Score 1) 304
LinkedIn uses it for their mobile backend.
Comment: Re:nothing new at all needed (Score 1) 717
I use both G+ and FB.
Eclipse has an excellent solution for this.
I miss that in MS Office and many other applications.
Comment: Re:A little late? (Score 4, Insightful) 136
by Laz10 (#38441038) Attached to: October, November the Worst Months For Writing Buggy Code
Looking back at my invoices, I can see that I usually work more hours those two months than any other months of the year.
I also get depressed from lack of sunlight in the dark Scandinavian autumn days.
On the other hand a total of one (and that was some trivial layout) bug was reported on the code I coded and shipped in that period this year.
Maybe the bugs are only found later?
That also suggests that the bugs found in October and November was introduced by the interns during the summer vacation?
Comment: Re:As much as I like this cool stuff (Score 2) 49
by Laz10 (#38367484) Attached to: NASA Developing Comet Harpoon For Sample Return
I am not a trekkie, but you must be referring to this:
The Enterprise arrives in the past, on April 4, 2063, the day before humanity's first encounter with alien life after Zefram Cochrane's historic warp drive flight.
So I assume that Zefram will invent it. I'll be sure to suggest that as a name candidate for my future grandchildren.
Comment: Don't build your own (Score 1) 135
by Laz10 (#37771554) Attached to: Ask Slashdot: Which OS For an Embedded Display Unit?
Make your black box join a wifi network or blutooth.
Then make apps for Android and iPhone that can control your device.
That way the customers can choose which device they want to control your device with.
As a default device you can tape som generic Android tablet to your device.
Same idea as http://ardrone.parrot.com/parrot-ar-drone/en/
Of course I realize that your application is probably much more serious than a flying toy, but the basic idea is good for many applications.
Comment: Re:Needs platform adoption first. (Score 3, Interesting) 338
by Laz10 (#37601996) Attached to: OCaml For the Masses
This is why I think Scala will succeed.
Scala has all the advantages that the article mentions AND you can integrate and reuse your old Java or .NET code and libraries.
It's there. The tooling doesn't suck half bad anymore. The world just needs to find out.
I personally think that Scala will win over the 10% best Java programmers as soon as the tooling is comparable to Javas.
And that might happen within the next 1-2 years.
|
global_01_local_0_shard_00000017_processed.jsonl/33561 | Forgot your password?
Comment: Re:Start your own provider? (Score 1) 353
by edgr (#44787519) Attached to: Ask Slashdot: How Do You Fight Usage Caps?
And that's just for ONE person without any file sharing; imagine a house full of people that actually use their technology.
But sometimes nice things are nice to have...
And there is no reason why a single person using their internet fairly sporadically should pay the same as a house full of people streaming HD video 24x7. Nice things are nice to have, but why should someone else pay for them?
Comment: Re:Privacy issue in Europe (Score 1) 684
by edgr (#40531133) Attached to: Ask Slashdot: Are Smart Meters Safe?
Yep, see for example Nonintrusive appliance load monitoring. It's possible to identify common appliances reasonably well using the size of changes to power consumption and, depending on the smart meter hardware used, the shape of the power-usage curve (e.g. the brief initial surge when turning on compact fluorescents). It's not perfect but it's not too bad and it's getting more accurate.
Comment: Re:So why offer an unlimited plan in the first pla (Score 1) 247
by edgr (#39246441) Attached to: AT&T Clarifies Data Limitations On "Unlimited" Data Plans
Exactly this happened in Australia with fixed-line broadband. ISPs offered 'unlimited' plans, in small print noting you get throttled after a certain figure. They got smacked down by the ACCC (the government consumer watchdog) and now plans are either "x GB - throttled" or "x GB - $y/GB excess fee", or genuinely unlimited.
Comment: Re:Spotify a promising alternative to Pandora (Score 2) 170
by edgr (#38849605) Attached to: How much of your music/video entertainment is streamed online?
I use spotify for almost all my music listening. I don't even bother with offline playlists, I generally just stream music on my mobile when I'm on the go. It's great being able to access such a vast library on the go - when someone is talking about a new track I can bring it up immediately, even if it's an artist I've never heard of.
I haven't paid for music for years, and now I'm spending $10 every month.
Comment: Re:Confused? (Score 1) 180
by edgr (#38081900) Attached to: $50,000 To Solve the Most Complicated Puzzle Ever
A lot of research has been done on the second step of this algorithm in bioinformatics. When sequencing a genome, generally all you get are millions of short sequences that need to be stuck together. The algorithms work by calculating probability scores for various pieces to be adjacent and then doing some funky statistics. It's a non-trivial problem to calculate those probabilities for the document reconstruction problem, and then the reconstruction is in 2d instead of 1d, but the bioinformatics algorithms could provide some interesting approaches.
Comment: Re:Obligatory XKCD (Score 5, Informative) 205
by edgr (#38020758) Attached to: DARPA Wants To Get Rid of Password Protection
i'm not sure i completely agree with that. for one thing, he calculates entropy wrong. according to wikipedia, the set of all ascci characters has an entropy of 6.5446 bits per character. given an 11 character password, thats ~72 bits. a 26 letter character set has an entropy of 4.7004 bits per character with 24 letters, that gives the password 112 bits. that doesn't make my case for why i disagree, just showing that he calculated entropy wrong. i actually don't even know how he came up with those numbers.
People understanding things in this way is exactly why everyone chooses bad passwords. His point is that if everyone has passwords like Tr0ub4dor&3, password guessers won't guess random printable ASCII characters, they'll guess a word and then try some substitutions on it.
So 'Troubador' can be guessed with a dictionary attack, which is why the word only gets about 16 bits of entropy (that puts it in the top 64000 most common words in English). There is additional entropy added by the substitutions but substituting '0' for 'o' is much easier to guess than changing the 'o' to a random character.
i'm not going to try to calculate the possible number of permutations of a 24 character english word password but its definitely significantly less than the 112 bits of entropy we calculated earlier. is it less than the 72 bits for the ascii character set? i don't know. but maybe someone smarter than me can go tell us that one.
And again, since an attacker would be using a dictionary attack, the correct way to calculate entropy is per word, not per character. The xkcd calculates 11 bits of entropy per common word which suggests these words are in the top 2^11=2048 most common words which seems reasonable (a quick glance at wikipedia suggests around 80% of the words in written texts are built from the most common 2000 words). So we get 44 bits of entropy. Obviously less than 72 bits but how many people are really going to create a completely random alpha-numeric-punctutation string of 11 characters (not built from a word or pattern)?
Comment: Re:Noscript wins again (Score 3, Interesting) 330
by edgr (#34532910) Attached to: Two Major Ad Networks Found Serving Malware
Most of the big banks in Sweden allow you to create a temporary (virtual) credit card with a specified limit and expiry date. You type the credit limit and expiry in, push a button and it spits out a new mastercard number. At least one bank (Swedbank, one of the largest in Scandinavia) requires this kind of card for all online transactions.
Comment: Re:Home Security Theater (Score 1) 633
by edgr (#34169868) Attached to: TSA Bans Toner and Ink Cartridges On Planes
The quickest path towards resolving this is genuinely for all non-criminal young Middle Easterners to start ejecting the radical element from within their ranks.
Just like when the IRA was having their campaigns, I should have told them to shut the hell up so I could go about my business? I'm an Australian, although I look Irish due to my ancestors around 4 generations ago emigrating from there. Racism is not the answer.
Comment: Re:A return to baseline... (Score 1) 506
by edgr (#32440642) Attached to: Caffeine Addicts Get No Additional Perk, Only a Return To Baseline
I think sporting bodies have researched this thoroughly. For example, in Australian football (the most popular sport in the country) caffeine was legalised a few years ago. The clubs spent big bucks testing their usefulness, but as far as I know none use them any more.
Comment: Re:Perspective (Score 1) 958
by edgr (#29691843) Attached to: How many countries have you visited?
When it is thousands and thousands of kilometers to get out of your own country in every direction if you don't can't the USA as a destination it is a bit more difficult to travel to many countries.
I live in Australia, you insensitive clod. I can drive for 25,000km on one highway without leaving the country. Apart from a few pacific islands, New Zealand is the only country within 6 hours flight of me (Melbourne).
And yet, most of my friends have travelled to several other countries. In the time it takes to drive 2000km, you can fly pretty much anywhere it the world.
|
global_01_local_0_shard_00000017_processed.jsonl/33562 | Forgot your password?
Comment: Re:Not Challenged based on fair use? (Score 1) 481
by mc+sd (#11753758) Attached to: Court Says FCC Out-of-Bounds With Digital TV
This is an excellent question. Fair use however perhaps ought not to be confused with the Sony ruling which was about Time shifting (not saying you're doing that, but they often get conflated).
Fair use, you may recall, only allows partial copying of a work for certain uses (social comment, research), not the making of complete copies for personal use, which is what most people want with their TiVo's.
I could be wrong, but my understanding of fair use is that it would not be helpful in such a case because of the strict rules about how much of an artefact can actually be copied.
The Sony case was more about personal use, with the likely understanding that copies would be temporary for convenience, not for long term archiving or sharing.
|
global_01_local_0_shard_00000017_processed.jsonl/33570 | Take the 2-minute tour ×
I asked this question before on stackoverflow ( http://stackoverflow.com/questions/5299338/filter-applause-from-videos ) and got the hint to ask it here:
I am currently watching a video from 27C3 and I would like to filter the applause, as it is very loud. Is this possible? I have heard something like this was made for Vuvuzelas.
I use Ubuntu. If this filter would work via ffmpeg / Audacity this would be great. If it is written in Python it would also be ok. I know the normalization with the VLC-Player, but thats not a very good solution
Here is an example: http://www.youtube.com/watch?v=TIViQuCX7XM#t=5m4s
share|improve this question
add comment
migrated from avp.stackexchange.com Jan 27 at 15:09
3 Answers
up vote 6 down vote accepted
Vuvuzelas are easily filterable because they are using is a specific frequency. Applause are basically random "clicks" which use a lot of the spectrum, and as such can't really be filterable. You could possibly detect applause and automatically lower the volume. But it's probably not trivial.
You might be able to get a good enough result by using a compressor or limiter, as that will lower the volume when it's high.
share|improve this answer
add comment
It sounds like you want to do this on the fly for your viewing pleasure. Unfortunately, sound engineers will recommend that you manually clean up your audio for the best result.
This can be done in various ways. It sounds as though the camera's mic was used to capture audio, as the audience is louder than the stage. Therefore you will have some trouble removing audience noise while the stage is performing. It is possible, however. I recommend you use a tracker with good envelopes or a waveform editor with a pencil tool. It's not procedure that can be taught in a paragraph. If you really want to do it, why not ask another question relating to that.
As far as automatic filtering, you've probably done the searches. Good luck.
share|improve this answer
add comment
You're not going to be able to filter the applause out without creating an underwater/comb filtered sound that would make the audio unintelligible at best. That is due to the very nature of applause. It's not a uniform tone like a vuvzela.
However, if your issue is that the applause is too loud you can combat the volume changes with a compressor. You would want a reasonably strong compression, so that the volume change between applause, and no applause is negligible. But it will depend heavily on the content you throw at it. So a one size fits all approach may be hard to find.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33580 | Take the 2-minute tour ×
Look at this script:
<a href=# onMOUSEOVER="document.getElementById('g').style.display='block'">
12</a><div id=g>hello world</div></html>
This is working but the
<div id=g>
is shown always when some one hover the link onetime. How to stop it so we can only see the content in div id 'g' if the link is hovered?
share|improve this question
By the way, leaving out the quotes around the g and the end tags for head and html are 20th century constructs, meant to save a couple of bytes, that we don't need any more today. Not to mention both tags for body. – Mr Lister Apr 7 '12 at 14:12
add comment
2 Answers
up vote 3 down vote accepted
Add an onmouseout on the div tag like this:
share|improve this answer
thank u for this lovely answer – user1126245 Apr 7 '12 at 14:12
add comment
<a href="#" onmouseover="document.getElementById('g').style.display='block'"
Also, wrap the id in quotation marks:
<div id='g'>
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33581 | Take the 2-minute tour ×
I am using Subsonic ORM by Rob Connery with Backbone.Js to build javascript single page demonstration application. in one of the service end point there is a contract that send all the records existing in the data source like below
[ScriptMethod(UseHttpGet = true)]
public TaskCollection GetAllTasks()
TaskCollection coll = new TaskCollection();
return coll;
but seems that each Task in the collection is polluted with loads of properties that are required only on server side. This is the JSON returned on request
"__type": "DAL.Task",
"Taskid": 1,
"Taskname": "welcome to india",
"Createdon": "\/Date(1334591056903)\/",
"Modifiedon": "\/Date(1334591056903)\/",
"ValidateWhenSaving": true,
"DirtyColumns": [],
"IsLoaded": true,
"IsNew": false,
"IsDirty": false,
"TableName": "task",
"ProviderName": null,
"NullExceptionMessage": "{0} requires a value",
"InvalidTypeExceptionMessage": "{0} is not a valid {1}",
"LengthExceptionMessage": "{0} exceeds the maximum length of {1}",
"Errors": []
all i require is CreatedOn,ModifiedOn and TaskName, TaskId . How do i make sure only these are sent down the wire using SubSonic ORM
share|improve this question
Most ORMs call this a "projection", basically making a query requesting a subset of columns to be returned. You may try googling for "subsonic projection", the top 4 results are all links to stack overflow. – Michael Maddox Apr 17 '12 at 11:15
@MichaelMaddox don't understand a thing either I am dumb or have no time to view SubSonic in details speaking of which the domain name subsonic project has also expired :( – Deeptechtons Apr 17 '12 at 11:42
add comment
2 Answers
up vote 1 down vote accepted
Here's a couple of ideas...
Use the viewmodel to autoselect the properties:
public class TaskView
public int TaskID { get; set; }
public string TaskDescription { get; set; }
var results = new Select().From(Tables.Task).ExecuteTypedList<TaskView>();
Use an anonymous type
var qry = new Select(new string[] { Task.Columns.TaskID, Task.Columns.TaskDescription }).From(Tables.Task);
var resultList = new List<object>();
using (IDataReader rdr = qry.ExecuteReader())
while (rdr.Read())
TaskID = rdr[0].ToString(),
TaskDescription = rdr[1].ToString(),
share|improve this answer
View model might fit the bill ( but still this is overwork I am abstracting more and more) anonymous typed?? i use .net 2.0 so i don't get to use goodness c# 3.0 provides :( – Deeptechtons Apr 17 '12 at 11:44
add comment
I don't use SubSonic, but I have to admit this does seem like a good example of where you might want to use a ViewModel, that is, a model that is populated from your Model specifically for the view. Now as far as binding the ViewModel to the Model, and/or possibly generating properties for many ViewModels from the model for the view (because generating ViewModels can definitely be tedious and error prone for a bunch of models), well, I've heard of several general solutions. I'm actually trying to find a solution I'm happy with myself; in the meantime I've been forced to hand write them until I find a better solution. I believe if you're wanting strongly typed ViewModels, you can use a tool like AutoMapper, though I've never used it myself. I've also seen solutions which use or inherit from a C# dynamic and then modify the accessors (though I think that might be slightly problematic to generate JSON from).
The primary reason I've used ViewModels is that I can easily control the format of the Dates. But that might be done better by using a different JSON serializer. Of course, the use of ViewModels can also allow you flexibility to change your data layer as needed. But I have to admit, it's been tedious. I think my implementation can be handled better with a bit of automation, but I don't know how to handle that so far.
I realize this is only a partial answer. I'm curious what other answers might come up.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33582 | Take the 2-minute tour ×
On MacOS 10.6, the default handle of QSlider is a ball, if a QSlider has ticks, then the handle changes its appearence (one side arrow shape), I want this kind of handle, but I don't like the ticks Qt provides. So, I'd like to store that picture of handle as qrc resource and use stylesheet to customize the look of qslider. That's the only way I can figure out.
Could anyone tell me how to write the style sheet, I mean that everything keep the same but only the handle changes.
BTW, there's another question. For a default QSlider on MacOS, the handle can't reach to the most left and most right position of the groove, how to use stylesheet to adjust it?
share|improve this question
add comment
2 Answers
up vote 1 down vote accepted
Add an image of the handle you want in your resources (.qrc) file. It should be quite easy to Photoshop the handle you like (or use some other program). Then try adding this in your code
setStyleSheet("QSlider::handle {image: url(:/resources/image.png);}");
You might need to experiment a bit with the padding and margins to get the slider positioned the way you want.
share|improve this answer
After I set the picture of handle, I found that other properties cannot take effect, such as "margin", by set the handle's margin the handle can expand outside the groove or leave an offset. – Royt Apr 26 '12 at 8:04
@Royt Try padding then, I know that works. – Anthony Apr 26 '12 at 13:17
I tried on Windows, QSlider::handle:horizontal {background-image: url(:/images/handle.png); } could work, while "image" property can't. but when use "background-image" property, the height and width can't work, if the image is small, it will be painted many times. And I tried padding-left and padding-right, they have no effect. – Royt May 9 '12 at 2:13
@Royt padding works fine for me on Windows. I'm using setStyleSheet("QSlider::handle {image: url(:/resources/image.png); padding-left: 5px;}");. Regarding the background image tiling itself, I think that is normal. If you don't want it to tile, you can subclass QWidget, give it a QImage for the background (not using style sheets), and then put a QSlider on top. You can remove the background of the QSlider however you like, e.g., using style sheets, since the QImage will serve as the new background, and can be resized however you like. – Anthony May 9 '12 at 2:44
add comment
You must change entire QSlider to manage such things. Otherwise it will fallback into default Mac OS X painting style. So you must change border and background of QSlider and handle itself. Take a look at this example
share|improve this answer
Thanks, now I know that many attributes should change together to make the customized look take effect. But, how to write the style sheet to make a qslider look like a native mac slider? – Royt Apr 25 '12 at 8:26
Well, I would use some graphics to do so. But why do you want to change native behaviour of slider on Mac OS X? – Kamil Klimek Apr 25 '12 at 8:40
Because I want to draw the ticks for slider by myself, but not use the dufault ticks Qt provides. So I should know the begin points and end points of the handle. But in a native Mac slider, the handle can't reach the most left and most right places, there is some offset, since the qt use Mac API to draw the Mac-style qslider, so I can't get the details. I want to custom it by style sheet and make it look like native control. – Royt Apr 26 '12 at 1:28
Then use some graphics to provide "quite native" look'n'feel – Kamil Klimek Apr 27 '12 at 12:03
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33583 | Take the 2-minute tour ×
I have created a function to call a function on each row in a dataset. I would like to have the output as a vector. As you can see below the function outputs the results to the screen, but I cannot figure out how to redirect the output to a vector that I can use outside the function.
n_markers <- nrow(data)
p_values <-rep(0, n_markers)
test_markers <- function()
for (i in 1:n_markers)
hets <- data[i, 2]
hom_1 <- data[i, 3]
hom_2 <- data[i, 4]
p_values[i] <- SNPHWE(hets, hom_1, hom_2)
share|improve this question
1. You should get in the habit of passing your functions arguments rather than relying on globals (c.f. stackoverflow.com/questions/5526322/… ). 2. There's already a function to do that. Look at apply(my.data, 1, ...) – Ari B. Friedman May 3 '12 at 13:20
shinyNewVector <- test_markers(). Do heed the advice from gsk3 too. – Chase May 3 '12 at 13:32
Read a basic introduction to R as well. You need to switch your mentality to thinking in vectors instead of for loops. – Hansi May 3 '12 at 13:33
I agree Hansi et al., but I also have to balance the demands of finishing my PhD with becoming a great R programmer. That is why I so much appreciate this site and its contributors! – Keith Larson May 3 '12 at 14:28
add comment
1 Answer
up vote 3 down vote accepted
Did you just take this code from here? I worry that you didn't even try to figure it out on your own first, but hopefully I am wrong.
You might be overthinking this. Simply store the results of your function in a vector like you do with other functions:
stored_vector <- test_markers()
But, as mentioned in the comments, your function could probably be reduced to:
stored_vector <- sapply(1:nrow(data), function(i) SNPHWE(data[i,2],data[i,3],data[i,4]) )
share|improve this answer
Many thanks for your help! – Keith Larson May 3 '12 at 14:30
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33584 | Take the 2-minute tour ×
I've been looking for a way to authenticate user by user and password passed in http header.
curl --user user1:pass1 http://localhost:6543/the_resource
The idea is to check if passed credentials allow user to view *the_resource* and if not return 401 - Forbidden.
I've found only examples of authentication policy where there has to be a login and logout view or this basic authentication policy which I don't know how to bind with Pyramid's ACL.
I will appreciate any help, how to start.
One more thing came to my mind. How to force this pup-up login window for basic authentication?
share|improve this question
add comment
2 Answers
In the end it became clear how to use authentication and authorization. Everything was actually written I just didn't catch the concept at once. I'll try to write how I got it working explaining in a noobish way, which I had to explain it to myself. I hope it will be useful to someone. Sources in the end may help to understand my writing ;) All comments are welcome. If I got something wrong, please correct me.
Most important is the basic authentication in which BasicAuthenticationPolicy must have methods that can be used later in pyramid application - like authenticated_userid(request). These methods use _get_basicauth_credentials() which pulls out login and password that were passed in http header. The actual checking if the login and password are correct happens in mycheck().
Now in __init__.py we must add BasicAuthenticationPolicy with method mycheck as an argument to our application configurator, so the pyramid can use it.
In a matter of authentication that is all. Now you should be able if and who was authenticated using authenticated_userid(request) (see views.py)
To use pyramid authorization to resources we need to add ACLAuthorizationPolicy to our configurator in __init__.py and add __acl__ to the resources. In most simple case to the root_factory (see this and this) ACL defines which group has what permission. If I'm not mistaken in (Allow, 'group:viewers', 'view') 'group:viewers' has to be what authentication method - mycheck() - returns.
The last step in authorization is add permission to certain view using a decorator (or in add_route). If we add the ACL permission - view - to a view_page then group:viewers is allowed to see that page (call view_page).
import binascii
from zope.interface import implements
from paste.httpheaders import AUTHORIZATION
from paste.httpheaders import WWW_AUTHENTICATE
from pyramid.interfaces import IAuthenticationPolicy
from pyramid.security import Everyone
from pyramid.security import Authenticated
import yaml
def mycheck(credentials, request):
login = credentials['login']
password = credentials['password']
USERS = {'user1':'pass1',
GROUPS = {'user1':['group:viewers'],
if login in USERS and USERS[login] == password:
return GROUPS.get(login, [])
return None
def _get_basicauth_credentials(request):
authorization = AUTHORIZATION(request.environ)
authmeth, auth = authorization.split(' ', 1)
except ValueError: # not enough values to unpack
return None
if authmeth.lower() == 'basic':
auth = auth.strip().decode('base64')
except binascii.Error: # can't decode
return None
login, password = auth.split(':', 1)
except ValueError: # not enough values to unpack
return None
return {'login':login, 'password':password}
return None
class BasicAuthenticationPolicy(object):
""" A :app:`Pyramid` :term:`authentication policy` which
obtains data from basic authentication headers.
Constructor Arguments
A callback passed the credentials and the request,
expected to return None if the userid doesn't exist or a sequence
Default: ``Realm``. The Basic Auth realm string.
def __init__(self, check, realm='Realm'):
self.check = check
self.realm = realm
def authenticated_userid(self, request):
credentials = _get_basicauth_credentials(request)
if credentials is None:
return None
userid = credentials['login']
if self.check(credentials, request) is not None: # is not None!
return userid
def effective_principals(self, request):
effective_principals = [Everyone]
credentials = _get_basicauth_credentials(request)
if credentials is None:
return effective_principals
userid = credentials['login']
groups = self.check(credentials, request)
if groups is None: # is None!
return effective_principals
return effective_principals
def unauthenticated_userid(self, request):
creds = self._get_credentials(request)
if creds is not None:
return creds['login']
return None
def remember(self, request, principal, **kw):
return []
def forget(self, request):
head = WWW_AUTHENTICATE.tuples('Basic realm="%s"' % self.realm)
return head
from pyramid.config import Configurator
from myproject.resources import Root
from myproject.basic_authentication import BasicAuthenticationPolicy, mycheck
from pyramid.authorization import ACLAuthorizationPolicy
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
config = Configurator(root_factory='myproject.models.RootFactory',
config.add_static_view('static', 'myproject:static', cache_max_age=3600)
config.add_route('view_page', '/view')
config.add_route('edit_page', '/edit')
app = config.make_wsgi_app()
return app
from pyramid.security import Allow
class RootFactory(object):
__acl__ = [ (Allow, 'group:viewers', 'view'),
(Allow, 'group:editors', 'edit') ]
def __init__(self, request):
from pyramid.security import authenticated_userid
from pyramid.view import view_config
#def my_view(request):
# return render_to_response('templates/simple.pt', {})
@view_config(route_name='view_page', renderer='templates/view.pt', permission='view')
def view_page(request):
return {}
def edit_page(request):
return {}
share|improve this answer
add comment
Well what you are asking for is Basic auth. You linked to the recipe, which you'll want to use. This handles identifying users and computing their principals. Principals are used by the ACL system, along with the permission specified on the view, to determine Allow/Deny access.
I think the trick is figuring out how to handle denying a user access to the resource, which is not enumerated in that recipe. You can do that by providing a custom "Forbidden View" that is invoked on a URL when the view denies access. At which point, Basic states that you provide a challenge to the client.
def forbidden_view(request):
resp = HTTPUnauthorized()
resp.www_authenticate = 'Basic realm="Secure Area"'
return resp
That's untested, but gives you the general idea of how to use a forbidden view. This will challenge the client, and then they are free to make another request (hopefully with credentials) that gets turned into principals that are mapped to the permissions you care about.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33586 | Take the 2-minute tour ×
See the struct I used bellow. I wish to solve this problem in a portable way.
The code I used for finding the absolute address of the struct was: (char*)data - sizeof(struct block); (where data is the address to the data in the struct block). It did not work on this struct.
I made a test program seen bellow where the last assert fails.
If I change unsigned int free:1; to unsigned int free; both prints will print 12 and thus sizeof has given me the expected result.
Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct block {
size_t size;
struct block* next;
unsigned int free:1;
char data[];
int main(void)
struct block* avail;
struct block* b;
avail = malloc(sizeof(struct block) + 10);
printf("%zu \n", sizeof(struct block)); // prints 12
printf("%zu\n", avail->data - (char*)&avail->size); //prints 9
b = (struct block*)((char*)avail->data - 9);
assert(b == avail);
b = (struct block*)((char*)avail->data - sizeof(struct block));
assert(b == avail);
return 0;
EDIT: seems like I found the answer here on stack overflow:
how to get struct's start address from its member's address
It gives me correct absolute address.
share|improve this question
possible duplicate of how to get struct's start address from its member's address – RedX Jul 2 '12 at 12:49
add comment
2 Answers
The only guarantees you have regarding the layout (and size) of
struct block {
size_t size;
struct block* next;
unsigned int free:1;
char data[];
are that the addresses of the members (resp. the unit containign the bit-field) are increasing in the order of their listing, the members are suitably aligned for their types, and there's no padding at the start of the struct, so a pointer to the struct, suitably converted yields a pointer to its first member. The compiler is free to insert more padding between the members than needed for alignment.
However, usually, the padding inserted is only what is needed for alignment. Also the size and alignment requirements of size_t and struct block* are in most implementations the same, both 4 bytes on a 32 bit system and 8 bytes on a 64 bit system. Then the size of struct block is a multiple of k = sizeof(size_t), and the first k bytes are occupied by the size member, the next k bytes by the next pointer.
After that comes an unsigned bit-field of width 1. Such a small bit-field fits into any unit of storage, thus the implementation is free to choose a unit of storage of any size for it. Natural choices would be
• one byte, since it's the smallest possible unit,
• sizeof(int) bytes, since " A ‘‘plain’’ int object has the natural size suggested by the architecture of the execution environment".
Now, if the unit to contain the bit-field is chosen to have the size of one byte, as was the case for your implementation (and mine), the data member is typically placed directly after that, at an offset of 2*k+1 bytes, since the alignment of char is 1. If the unit for the bit-field is chosen to be int-sized, the offset of data will most likely be 2*k + sizeof(int), which on 32-bit systems is probably equal to sizeof(struct block), but not on 64-bit systems.
You can with very high probability bring the implementation to make
offsetof(struct block, data) == sizeof(struct block)
by inserting an unnamed bit-field of appropriate width (CHAR_BIT * sizeof(size_t) - 1) between free and data, but the only way that is portable and guaranteed to work is
struct block *b_addr = (struct block*)((char*)(avail->data) - offsetof(struct block, data));
as stated in Greg Hewgill's answer to the linked question.
share|improve this answer
add comment
sizeof(struct block) - sizeof(char*) should give you the size of the struct block, not including the data field. So, if you have a pointer to data, you should reach the beginning of the structure.
b = (struct block*)((char*)avail->data - (sizeof(struct block) - sizeof(char*));
assert(b == avail);
I have not tested it, though.
share|improve this answer
Flexible array members are not pointers, and do not count toward the base size of the structure, so this would yield an incorrect result. – Justin Spahr-Summers Jul 2 '12 at 18:11
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33587 | Take the 2-minute tour ×
I'm trying to save records in a database. Many of the column values will be taken from a http request to an api.
I have a text field and some check boxes along with the session_id in the form which will be persisted. this is posted from another controller (form_tag('results#store'))to an action called store in the results controller.
Store action:
def store
query = query_preprocesser(params[:query]) # this is in a helper
## example of resArray ##
#resArray = [[{:engine => "bing, :results => [{:Description => "abc", :Title => "def"}, {:Description => "ghi", :Title => "jkl"}]}, {etc},{etc} ],[{:eng...}]]
resArray = getResults(query) # Also a helper method returning an array of up to 3 arrays
resArray.each do |engine|
db_name = engine[:engine]
engine[:results].each do |set|
res = Result.new(
:session_id => params[:session_id],
:db_name => db_name,
:query => query,
:rank => set[:Rank],
:description => set[:Description],
:title => set[:Title],
:url => set[:Url] )
res.each do |res|
#Result.new(:session_id => params[:session_id], :db_name => "Bing", :query => "Whats the story", :query_rank => 1, :title => "The Title", :description => "descript", :url => "www.google.ie",:query_number => 1)
respond_to do |format|
format.html { redirect_to pages_path }
format.json { head :no_content }
My routes are resources :results
Server logs:
[2012-07-10 23:30:48] INFO WEBrick 1.3.1
[2012-07-10 23:30:48] INFO ruby 1.9.3 (2012-04-20) [x86_64-linux]
[2012-07-10 23:30:48] INFO WEBrick::HTTPServer#start: pid=15584 port=3000
Started POST "/results" for at 2012-07-10 23:31:36 +0100
Connecting to database specified by database.yml
Processing by ResultsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"/nTJOF5Ab+XnL+jxRBHnTJz45YRVmgbf55bmn5/iz8E=", "query"=>"search term", "button"=>"", "searchType"=>"Seperate", "bing"=>"1", "session_id"=>"e08c13a99f21a91520fcc393e0860c94"}
(0.2ms) begin transaction
(0.2ms) rollback transaction
Rendered results/_form.html.erb (13.9ms)
Rendered results/new.html.erb within layouts/application (23.6ms)
Completed 200 OK in 213ms (Views: 78.4ms | ActiveRecord: 2.9ms)
<%= form_tag('results#store') do %>
Rake routes:
store POST /pages(.:format) results#store
results GET /results(.:format) results#index
POST /results(.:format) results#create
new_result GET /results/new(.:format) results#new
edit_result GET /results/:id/edit(.:format) results#edit
result GET /results/:id(.:format) results#show
PUT /results/:id(.:format) results#update
DELETE /results/:id(.:format) results#destroy
store POST /pages(.:format) results#store
pages GET /pages(.:format) pages#index
I keep getting redirected to the new action in Results controller. The helper methods aren't even being executed. I'm a past master at over complicating things, can anyone help unravel this for me?
share|improve this question
Describe a little more how you get here. What url do you visit first? Post the server logs for the entire journey (start url, form submission, redirect to new). – Dean Brundage Jul 10 '12 at 22:21
I start from the pages#index, that's where the form is. – Nultyi Jul 10 '12 at 22:40
I'm being redirected from the create action because non of the parameters are reaching the action and they are validated in the model. I still can't understand why the form is being posted to the create action when I have specified the store action... – Nultyi Jul 10 '12 at 23:35
add comment
1 Answer
up vote 0 down vote accepted
Do you have a route set up for the store action? If you do then you should use the url helper for it in your form tag:
form_tag( results_store_url )
share|improve this answer
Top man Dean :) Its works with store_url. I've been tinkering with the routes for the past hour+ and it's all come together! I clearly need to look harder at routing. :| What I don't understand is the HTML says http://localhost:3000/pages for action with store_url - guess I'll find out why when I read more about routes. Thanks again Dean! – Nultyi Jul 11 '12 at 0:05
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33588 | Take the 2-minute tour ×
When I Build my app, it compiles without any problems or errors. But when I run it I see this message in console:
Here is my Appdelegate's method which I believe might be causing this(based on other posts Ive seen on SO)
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
PhotosViewController *viewController = [[PhotosViewController alloc] initWithNibName:nil bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
[self.window addSubview:self.navigationController.view];
[self.window makeKeyAndVisible];
return YES;
Is this something that I need to be worried about? My app runs in the simulator even though this message shows up.
Any suggestions on what I should do to get rid of it? What can I do to debug this?
BTW, I have seen other questions on SO with the similar error message, however, none of the scenarios apply to mine so I have posted this question. Its not a duplicate :)
share|improve this question
add comment
1 Answer
up vote 3 down vote accepted
Instead of:
[self.window addSubview:self.navigationController.view];
self.window.rootViewController = self.navigationController;
You can find more details in the UIWindow documentation
share|improve this answer
Thanks This worked for me. I donot see the error message anymore – banditKing Sep 10 '12 at 3:24
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33589 | Take the 2-minute tour ×
I have a problem that I can not get my head around. I have created a sticky nav which when the page is scrolled, it becomes fixed at the top. It should then return to its normal position if the user scrolls back up. I have this working perfectly on my localhost, but when I upload it online, the sticky nav just keeps jumping straight to the top as soon as you even scroll a little bit of the page, and it never returns to its normal position. This is just an issue in web
Could anyone please help with this? My example is: http://debourg.ch/dev/syselcloud/design4/
The jQuery concerned is:
var yOffset = $("#local-nav-wrapper").offset().top;
$(window).scroll(function() {
if ($(window).scrollTop() > yOffset) {
'top': 0,
'bottom': 'auto',
'position': 'fixed'
} else {
'top': 'auto',
'bottom': 0,
'position': 'absolute'
The CSS concerned is:
#local-nav-wrapper {
position: absolute;
bottom: 0;
width: 100%;
padding: 10px 0;
z-index: 6000;
share|improve this question
the nav works fine on my screen, MAC FF 11 – Huangism Oct 9 '12 at 12:46
yea it's just webkit browsers that seem to pose the issue. – user1280853 Oct 9 '12 at 14:04
just tried on mac chrome and it works as well – Huangism Oct 9 '12 at 17:03
add comment
1 Answer
If you work in IE try and replace $(window).scrollTop() with document.documentElement.scrollTop or window.scroll(0,0). Maybe it helps.
share|improve this answer
It didn't work at all when I tried this, anymore suggestions? Many thanks – user1280853 Oct 9 '12 at 14:05
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33590 | Take the 2-minute tour ×
Have two mysql databases in two servers, I have to share user information tables on both databases,I am using the both database for different projects, In both projects the user information need to be updated, So that update of user information should reflect in others, Please Suggest good methods to synchronize, so that in secure way no data get loosed.
Thanks in advance
share|improve this question
You can synchronize tables in two different databases with a help of Date Comparison tool in dbForge Studio for MySQL. You can run it in command line mode. – Devart Oct 15 '12 at 6:29
add comment
1 Answer
up vote 0 down vote accepted
Normally, mysql's replication support Master -> Slave model. User can only read from Slave to avoid data conflict.
But some solution support master-master model. you can read this url for more details. http://www.howtoforge.com/mysql_master_master_replication
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33591 | Take the 2-minute tour ×
I am using Doxygen and GraphViz Dot to generate some collaboration diagrams for a C# project. The problem is generic collections (like List<>) are not recognised by Doxygen. Does anyone have a solution to this?
I found this comment that doesn't seem very hopeful, but was wondering if there are any work-arounds.
share|improve this question
Using Doxygen 1.8.2 (latest release as of right now), generics look fine to me. Are you using an older version or is there something else that isn't working right? – Patrick Quirk Nov 24 '12 at 19:54
I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". – John Saunders Nov 30 '12 at 5:35
Did you remove Doxygen from the title? – Dave Hillier Dec 23 '12 at 0:30
add comment
2 Answers
According to Doxygen's changelog, generics in C# were not being indexed prior to version (released October 6). I don't see a corresponding bug for it, though looking at previous releases they've been supported for some time now.
As my comment above states, I don't see any issues using the current release (1.8.2). If that's the version you're using, please specifically mention what isn't working.
share|improve this answer
add comment
there are Issues with Generics and Some thirdPartyControls. I had same Problem. If List<> not supoorted, you can Convert List to Corresponding Array of Objects. Array will support in any Controls and Products.
Just see the example.
Need To convert DataTreeNodeCollection (List) SubNodes into DataTreeNode[]
DataTreeNode[] subNodesArray = new DataTreeNode[SubNodes.size()];
foreach (DataTreeNode node in SubNodes)
subNodesArray[count] = node;
Here I converted List to Array.
share|improve this answer
hi bradmarxmoosepi, Please let me know, if you have any doubts. – Akshay Joy Nov 30 '12 at 5:31
Or you could use SubNodes.ToArray() – Christoffer Nov 30 '12 at 5:51
Hi Christoffer, List<> is .Net 2.0 feature. So that's why Used this code. that also one way. – Akshay Joy Nov 30 '12 at 6:17
@Akshay Suggesting not using generics at all just to get around an apparent doxygen limitation is not a good answer. – Patrick Quirk Feb 15 '13 at 4:06
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33592 | Take the 2-minute tour ×
I have the following code
var d = new Date();
Object.prototype.toString(d); //outputs "[object Object]"
Object.prototype.toString.apply(d); //outputs "[object Date]"
Why is this difference and what's going on?
d.toString() // outputs "Tue Nov 06 2012 ..."
So from where does the Date in "[object Date]" comes from. Is it the native code of the browser that do the trick?
share|improve this question
add comment
3 Answers
converts Object.prototype to string and ignores its argument. In
d gets passed as this to the ToString method (as if d.toString() with toString referring to Object.prototype.toString was called), which is what the method respects.
See Function#apply and Object#toString
share|improve this answer
But d.toString() is giving entirely different result. right? – suhair Nov 6 '12 at 6:49
Yes, because in that case you are calling Date.prototype.toString not Object.prototype.toString (i.e. Date instances inherit a different toString method). – RobG Nov 6 '12 at 6:59
add comment
Another explanation is that Object.prototype.toString operates on its this object. A function's this is set by how you call it so when you do:
the toString function's this is the Object.prototype object. When you call it as:
its this is the object referenced by d (a Date object).
share|improve this answer
add comment
The parameter is ignored in the first call. You are calling the toString method on the Object.prototype object, basically the same as:
{}.toString(); //outputs "[object Object]"
In the second call you are calling the toString method for Object but applying the Date object as its context. The method returns the type of the object as a string, compared the toString method of the Date object which would instead return the value of the Date object as a string.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33593 | Take the 2-minute tour ×
I have a map view which shows users location. The user location is shown as centre of mapview. But when the mapview is zoomed i have to show the user location as centre. But currently it doesn't show that. The user location moves away from the centre. How to show the user location in the centre position even if the map is zoomed. I have used KVO notification but when zoomed the function zoom out the map and plot users location in the centre. But i dont want to zoom it out. Any help is appreciated. Sorry for my bad english.
share|improve this question
add comment
1 Answer
up vote 1 down vote accepted
I'm not quite sure i understand what you're trying to do but you could try using the
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated delegate method of MKMapView.
In there you could play with the span value and check whether the map has been zoomed or not. Then you could center the map to your user's current location.
Or you could use the
delegate method to center the map before the region is changed.
share|improve this answer
Thanks that was really helpful – Kiron Nov 12 '12 at 11:13
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33594 | Take the 2-minute tour ×
If only the named arguments of a S4 generic function are defined in a method, substitute() works as expected:
> setGeneric("fS4", function(x, ...) standardGeneric("fS4"))
> setMethod("fS4", signature("numeric"),
+ function(x, ...) deparse(substitute(x))
+ )
[1] "fS4"
> fS4(iris[,1])
[1] "iris[, 1]"
However, if one adds an extra named argument to the method's definition, substitute() ceases to correctly return the argument as it was passed:
+ function(x, y, ...) deparse(substitute(x))
+ )
[1] "fS4"
> fS4(iris[,1])
[1] "x"
Any clues on why this happens and, most importantly, how it can be worked around?
share|improve this question
add comment
1 Answer
up vote 2 down vote accepted
Take a look at
showMethods(fS4, includeDef=TRUE)
which shows
Function: fS4 (package .GlobalEnv)
function (x, ...)
.local <- function (x, y, ...)
.local(x, ...)
The way that S4 implements methods with signatures that differ from the generic is by creating a '.local' function with the modified signature, inside a function with the generic signature. substitute then evaluates in an incorrect environment. The underlying problem is not related to S4
> f = function(x) deparse(substitute(x))
> g = function(y) f(y)
> f(1)
[1] "1"
> g(1)
[1] "y"
> h = function(...) f(...)
> h(1)
[1] "1"
and any attempts to evaluate in the the 'right' environment will be thwarted by arbitrary constructs provided by users.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33595 | Take the 2-minute tour ×
I'm developing an app using ActionbarSherlock for backwards compatibility, and I'm currently having problems with the Spinner I add to the ActionBar.
I'm using ActionBar.NAVIGATION_MODE_TABS and each tab is a Fragment with it's own inflated menu.
I have no problem inflating and populating the menus or Spinners, but the problem is that the Spinner is not expanding when a user clicks it. However, when the user slides to another fragment the Spinner expands (and is shown in the wrong fragment), and when sliding back again the Spinner works as expected in the correct fragment.
This problem only occurs on devices <4.0.x (haven't tried 3.x). When testing on >4.0.x it works as expected.
I have tried debugging and going through callback methods, but I can't figure out why this happens. Can it be a bug in older versions of Android, or is it because menus and such are handled differently? (shouldn't though since I'm using ActionbarSherlock).
Does anyone have an idea of why this is happening?
I noticed that the problem occurs to the fragments/tabs that are not added first to the ViewPager, no matter what action item is in the menu. The first tab, i.e. the one that is active once the Activity starts, never has this problem.
Is it just me who is missing something, or is this how it's supposed to be?
share|improve this question
Did you find any solution to your problem? I think I have a similar one. – Izydorr May 29 '13 at 10:10
add comment
2 Answers
Try this, It might help you
For spinner
android:scrollbars="none" />
In style.xml you apply this
<style name="your_style_name">
<item name="android:dropDownWidth">fill_parent</item>
<item name="android:background">@drawable/spinner_background</item>
<item name="android:popupBackground">@drawable/spinner_dropdown_background</item>
<item name="android:divider">@color/gray_darkest</item>
<item name="android:alignmentMode">alignBounds</item>
<item name="android:dividerHeight">2dp</item>
<item name="android:scrollbars">none</item>
<item name="android:scrollbarAlwaysDrawVerticalTrack">false</item>
<item name="android:scrollbarTrackVertical">@android:color/transparent</item>
<item name="android:dropDownSelector">@android:color/holo_dark</item>
<item name="android:requiresFadingEdge">none</item>
share|improve this answer
thanks for your answer, but the problem still occurs. see my updated post – Rob Nov 25 '12 at 0:42
I think you have problem in backgorund image, slice it again. Then you should slightly adjust the background image of the spinner, It should not touch the edge of the screen – ADR Nov 25 '12 at 0:43
i'm not sure what you mean by slicing the background image, but as i wrote in the update, the problem doesn't only involve Spinners but all menu items that are not in the active fragment when the activity starts – Rob Nov 25 '12 at 1:01
your spinner's and dropdown item's edges should not touch the left and right edge of the screen. Then you will get correct output – ADR Nov 25 '12 at 1:54
previously i got the same probs, I solved by adjusting left and right edge of the spinner and drop down item view – ADR Nov 25 '12 at 1:54
add comment
I had a very similar problem. In my case the Activity was extending another one and the "parent" activity was returning false in onPrepareOptionsMenu() function. This was causing wrong behaviour on Android 2.x, on Android 4 all was OK. When I changed the code to return true all is fixed. Another very strange thing I noticed was that the non-working ActionItem icons where darker then the good ones (in another Activity).
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33596 | Take the 2-minute tour ×
I'm trying to iterate trough a dictionary while dynamically changing its size, by adding elements in Javascript. The dictionary is initialized with 1 element. Pseudo code should look like this:
dict = {1:1};
i = 0;
for key in dict{
dict[i] = i+1;
if i==10{break;}
I would be more than glad if anyone could come up with a working solution.
share|improve this question
what are you trying to achieve by this? – Christian Westman Nov 29 '12 at 18:44
If you're growing your dictionary, a for-loop-iterator over the dictionary object isn't going to help you much. – Cory Nov 29 '12 at 18:45
I'm trying to make a dijkstra algorithm which was implemented in python: code.activestate.com/recipes/… it uses a priorityDict, but also works with orderedDict(). So now i'm looking for a similar solution but in javascript – box Nov 29 '12 at 18:49
@box: Several JS implementations for Dijkstra's algorithm are already available. Are you doing this just as an exercise? Otherwise: bitbucket.org/wyatt/dijkstra.js/src/fb6c30a3cebd/… – Cory Nov 29 '12 at 18:51
Yes i searched for other solutions, but this one in python looked really elegant and easy to understand. Thanks for the link anyways! – box Nov 29 '12 at 18:54
add comment
1 Answer
Dictionary keys (object properties) shouldn't be integers, but this will grow your "dictionary" to have 10 elements (it will only add nine because it will skip when i == 1:
var dict = { 1: 1 };
if (!dict.hasOwnProperty(i)) {
dict[i] = i + 1;
share|improve this answer
Thanks, maybe i haven't described it accurately but I actually don't know if the number in the end will be 10, so it's changing constantly. – box Nov 29 '12 at 18:51
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33597 | Take the 2-minute tour ×
I'm trying to write a program in C that converts a captured Raw 16kHz PCM 16-bit file to a 16-bit WAV.
I've read some posts and people recommended using libsox. Installed it and now i'm really struggling with understanding the man-page.
So far (by reading the example in the source dist) I've figured out that the structs:
• sox_format_t
• sox_signalinfo_t
can probably be used to describe the data I'm inputting. I also know how much info i'm processing (time) if that is somehow necessary?
Some guidance is appreciated!
share|improve this question
If the only output format you want is WAV, I'd skip learning any third party APIs and write it myself. The file format for WAV is really very simple. – simonc Dec 14 '12 at 15:32
Seems worth a shot. I'll give it a try! – Mazze Dec 17 '12 at 9:01
add comment
2 Answers
up vote 1 down vote accepted
I would recommend to write WAV header and data manually, it is really very simple for PCM : https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
share|improve this answer
add comment
Well, It worked out as the question is answered. However I'll post the code here so that people can analyze it or just use it in their own projects.
The link provided by both "simonc" and "Nickolay O." was used. Search the web for more info on the individual fields.
struct wavfile
char id[4]; // should always contain "RIFF"
int totallength; // total file length minus 8
char wavefmt[8]; // should be "WAVEfmt "
int format; // 16 for PCM format
short pcm; // 1 for PCM format
short channels; // channels
int frequency; // sampling frequency, 16000 in this case
int bytes_per_second;
short bytes_by_capture;
short bits_per_sample;
char data[4]; // should always contain "data"
int bytes_in_data;
//Writes a header to a file that has been opened (take heed that the correct flags
//must've been used. Binary mode required, then you should choose whether you want to
//append or overwrite current file
void write_wav_header(char* name, int samples, int channels){
struct wavfile filler;
FILE *pFile;
strcpy(filler.id, "RIFF");
filler.totallength = (samples * channels) + sizeof(struct wavfile) - 8; //81956
strcpy(filler.wavefmt, "WAVEfmt ");
filler.format = 16;
filler.pcm = 1;
filler.channels = channels;
filler.frequency = 16000;
filler.bits_per_sample = 16;
filler.bytes_per_second = filler.channels * filler.frequency * filler.bits_per_sample/8;
filler.bytes_by_capture = filler.channels*filler.bits_per_sample/8;
filler.bytes_in_data = samples * filler.channels * filler.bits_per_sample/8;
strcpy(filler.data, "data");
pFile = fopen(name, "wb");
fwrite(&filler, 1, sizeof(filler), pFile);
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33598 | Take the 2-minute tour ×
I'm building a custom component for Talend Open Studio to access a source of data from an application (JIRA) that has a wrapper to get all its data. It exposes an API full of very volatile getters for all its data structure. Since Talend Open Studio supports primitive type only, i usually need to chain several call to get a primitive data (ie. Project.getProjectDetail().getOwner().getName())
But these API often vary and i don't want to change my code every time. So i decided to use an enumeration of methods: when a new field is exposed, i need only to add an element to the enumeration. Something like that:
(i cut most elements to be concise)
public enum JiraProjectField {
KEY(new String[]{"getKey"}),
COMPONENTS_NUM(new String[]{"getComponents", "size"}),
private Method[] m;
private ArrayList<Class<?>> r;
private JiraProjectField(String[] methods) {
this.r = new ArrayList<Class<?>>(methods.length);
Class<?> initClass = Project.class;
try {
m[i] = initClass.getMethod(methods[0], (Class<?>)null);
initClass = m[i].getReturnType();
} catch (SecurityException e) {
throw new ExceptionInInitializerError(e.toString());
} catch (NoSuchMethodException e) {
throw new ExceptionInInitializerError(e.toString());
But I always get a NoSuchMethodException, even if i'm sure the method with that name exists. Is there something i don't know?
share|improve this question
It's not clear what enums have to do this. Are you saying this code works outside an enum? It would really help if you'd give a short but complete example of this failing. – Jon Skeet Jan 15 '13 at 23:24
What is the signature of the method? – assylias Jan 15 '13 at 23:24
Sure it's a public method in a public class? – Tom Hawtin - tackline Jan 15 '13 at 23:26
"Is there something i don't know?" Thomas Edison was heard to say "We don't know a millionth of 1% about anything.". So I expect the answer to that is. Yes. – Andrew Thompson Jan 15 '13 at 23:26
I don't know even an estimate of how much I don't. ;) – Peter Lawrey Jan 15 '13 at 23:45
show 3 more comments
1 Answer
up vote 3 down vote accepted
I am not sure why you are not using varargs more but you can try
m[i] = initClass.getMethod(methods[i]);
share|improve this answer
Ah yes, it getMethod(methods[0], new Class<?>[] { null }); which actually looks like unspecified behaviour. – Tom Hawtin - tackline Jan 16 '13 at 0:03
+1, it was much more easier than i supposed. The problem was with that cast Class<?>; remove the cast resolved the issue. However I'm wondering if i could find a better design (an array of method instead of an array of string? a varargs prototype? nothing like that?) – Gabriele B Jan 16 '13 at 8:16
You will be able to in Java 8 as it has first class method objects. i.e. you can refer to a method and access it without explicit use of reflection. – Peter Lawrey Jan 16 '13 at 13:26
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33599 | Take the 2-minute tour ×
I am trying to set a cookie with value unkown#4?Wn5pZ1JwQnlLEGRJAgB4WQU%3D in Servlet response.
But when I set the cookie in browser it is returned with quotes surrounding it like this:
Why is this happening? We are using Jetty as application server.
I will put code which I have written
String cookieValue = "unkown#4?Wn5pZ1JwQnlLEGRJAgB4WQU%3D";
Cookie zedoCookie = new Cookie("cookiename", cookieValue);
zedoCookie.setMaxAge(31536000); // this is one year duration.
Can someone put some light on this?
I have already had a look at this. But it does not seem to address my issue.
share|improve this question
add comment
2 Answers
Read the javadoc once again (emphasis mine):
With Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs, commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may not behave the same way on all browsers.
So the answer which you found applies to you as well. URL-encode the value.
Cookie zedoCookie = new Cookie("cookiename", URLEncoder.encode(cookieValue, "UTF-8"));
And upon retrieving, URL-decode it.
String cookieValue = URLDecoder.decode(zedoCookie.getValue(), "UTF-8");
share|improve this answer
question mark has not caused a problem yet but yes, from the time we are getting equals sign we are facing this issue. But in any case we need to make sure that we set the cookie appropriately. We have no control over the cookie content we get. – Sam Jan 31 '13 at 12:58
Just URL encode/decode it. I don't see how that part is a problem to you. – BalusC Jan 31 '13 at 12:59
I tried encode and decode option but still it is putting double quotes. – Sam Jan 31 '13 at 14:43
add comment
It seems like Jetty treats the following characters as not allowed in Cookies: "\\n\r\t\f\b%+ ;= (HttpFields -> __COOKIE_DELIM). If one of these characters is contained in the value of the cookie, then the value will be enclosed in double quotes in the HTTP-Header. URL-Encoding does not solve the Problem, since then you will still have the % character inside. To me it seems like a bug. I posted a question to the Jetty mailing list. There is also another post on the mailing list, which explains why the cookie version is raised in Jetty version 9.
share|improve this answer
+1 Thanks for this. I had convert '+' -> '-', '/' -> '.', and '=' -> '_' to get my base64 cookie to be stored without spaces. – Gray Feb 17 at 0:59
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33600 | Take the 2-minute tour ×
Given the following code, do i need to remove the observer at any point? I feel like i do..
App.Views.MyView = Ember.View.extend({
init: function ()
var self = this;
// Add observer
self.addObserver('App.Path.To.ItemsObject', self, self._itemsObserver);
return this._super();
_itemsObserver: function(){
//Do something
share|improve this question
add comment
1 Answer
up vote 1 down vote accepted
Yes you have to. You can use the events of willInsertElement and willDestroyElement for this task. See Doc of Ember.View
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33601 | Take the 2-minute tour ×
The title is self explanatory. I have seen a question earlier but that didn't helped me as much.
I reviewed the Boostrap API but couldn't find my answer.
share|improve this question
Your question says nothing. The title says something. – epascarello Feb 27 '13 at 13:45
@epascarello Yes right :) – user1765876 Feb 27 '13 at 13:48
add comment
4 Answers
up vote 31 down vote accepted
It is an HTML5 data attribute that automatically hooks up the element to the type of widget it is.
Some Examples:
Go through the JavaScript docs and search for data-toggle and you will see it used in the code examples.
One working example:
<div class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown trigger</a>
<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
share|improve this answer
It is just an HTML attribute which is used with selectors, not HTML5 specific. – Umur Kontacı Jul 11 '13 at 14:57
@UmurKontacı data-* was introduced in the HTML5 spec. – epascarello Jul 11 '13 at 15:05
I am not sure but it looks like the link of JavaScript docs is changed to getbootstrap.com/2.3.2/javascript.html. Please verify it. – hims056 Sep 5 '13 at 14:08
I guess 'JavaScript docs' link has broken. Anyone can provide updated one? – user2243747 Dec 26 '13 at 10:00
Updated link to Bootstrap JavaScript docs: getbootstrap.com/javascript – steps Jan 10 at 10:41
add comment
Any attribute that starts with data- is the prefix for custom attributes used for some specific purpose (that purpose depends on the application). It was added as a semantic remedy to people's heavy use of rel and other attributes for purposes other than their original intended purposes (rel was often used to hold data for things like advanced tooltips).
In the case of Bootstrap, I'm not familiar with its inner workings, but judging from the name, I'd guess it's a hook to allow toggling of the visibility or perhaps a mode of the element it's attached to (such as the collapsable side bar on Octopress.org).
html5doctor has a good article on the data- attribute.
Cycle 2 is another example of extensive use of the data- attribute.
share|improve this answer
That html5doctor link is a great read. Very informative, thank you! – Dave Voyles Nov 6 '13 at 19:06
add comment
The presence of this data-attribute tells Bootstrap to switch between visual or a logical states of another element on user interaction.
It is used to show modals, tab content, tooltips and popover menus as well as setting a pressed-state for a toggle-button. It is used in multiple ways without a clear documentation.
share|improve this answer
add comment
It is a Bootstrap defined HTML5 data attribute.It binds a button to an event.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33602 | Take the 2-minute tour ×
I need to do some operations on a matrix of values that take at most one byte (values form 0 to 20 most likely). Since the matrix is rather large I figured I'd do these operations on the GPU using OpenCL and storing the matrix as an image. The thing is that I failed to find any hints to whether OpenCL has support for single channel images... and I wouldn't want to pass around more data than I actually use.
Is there any support for single channel images?
share|improve this question
add comment
2 Answers
up vote 1 down vote accepted
As mentioned in the Previous Answer use CL_INTENSITY and CL_LUMINANCE.
It is expected that the latency of addressing calculations is hidden better for Image objects, but texture cache is not kept coherent with respect to image writes, so any image read to an address that has been written to via an image write in the same kernel call returns undefined data.So developers prefer to use regular buffers only.
share|improve this answer
Since not even the asker upvoted your post, I did. – Dudeson Mar 20 '13 at 10:17
add comment
There is CL_INTENSITY and CL_LUMINANCE. But if you don't need image related functions (as I would assume if you want to manipulate matrices) you are better off with a regular memory buffer.
share|improve this answer
OP didn't specify what he's doing with the data. Moreover, caching assumptions depend on the actual hardware and are not required by the specification. And if available, accesses to global memory can be cached via local shared memory. – matthias Mar 19 '13 at 8:59
maybe you can answer this question then stackoverflow.com/questions/15322206/… – user2088790 Mar 19 '13 at 9:18
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33603 | Take the 2-minute tour ×
I have the following code :
$results = $Q->get_posts($args);
foreach ($results as $r) {
print $r['trackArtist'];
This is the output :
My question is, if trackArtist is an array, why can't I run the implode function like this :
$artistString = implode(" , ", $r['trackArtist']);
Yes, it is a string indeed, but from the other side it leaves as an array so I assumed it arrives as an array here also. There must be some processing done in the back.
Any idea how I can extract the information, for example from : ["DUKY","LOQUACE"]
to get :
Thanks for your time
share|improve this question
This seems not to be an array but maybe an object? – Zeal Apr 4 '13 at 14:28
Why do you think that trackArtist is array? – hjpotter92 Apr 4 '13 at 14:28
Try var_dump($r['trackArtist']); instead of print(); to check if it is actually an array. – Gerald Schneider Apr 4 '13 at 14:28
What makes you think trackArtist is an array? – Mark Baker Apr 4 '13 at 14:28
echo "<pre>"; print_r($results); echo "</pre>"; whats the Output ? – Fawad Ghafoor Apr 4 '13 at 14:29
show 1 more comment
3 Answers
up vote 1 down vote accepted
It's probably a JSON string. You can do this to get the desired result:
$a = json_decode($r['trackArtist']); // turns your string into an array
$artistString = implode(', ', $a); // now you can use implode
share|improve this answer
Thank you !! It works ! – Gabriel Gray Apr 4 '13 at 15:03
You're welcome. – Mischa Apr 4 '13 at 15:03
add comment
It looks like it's not actually an array; it's the string '["DUKY","LOQUACE"]' An array would be printed as Array. You can confirm this with:
share|improve this answer
add comment
To me content of $r['trackArtist'] is NOT an array. Just regular string or object. Instead of print use print_r() or var_dump() to figure this out and then adjust your code to work correctly with the type of object it really is.
share|improve this answer
I guess he meant $r['trackArtist'] is an array, not 'trackArtist'. – Mido Apr 4 '13 at 14:42
yep. I refered to that. Edited – Marcin Orlowski Apr 4 '13 at 14:44
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33604 | Take the 2-minute tour ×
In single.php, I have the following items that I manage (create, update, hide) with jquery/ajax:
• a <select> tag in which I return all website categories.
• a second <select> tag in which I return post titles depending on the selected category in first <select> tag.
• a <div> tag which contains a content based on the selected post in second <select>. This content is divided into tabs. On click on a tab, I display via ajax a meta value of the custom field related to this tab for the specific post selected in second <select> . In addition, I am making a jquery pagination system for each tab whenever the meta value is long.
All jquery/ ajax actions are working like a charm respecting all rules of DOM updating and scripts reloading after triggering actions on updated DOM.
In sum, I have 4 parameters while navigating in single.php:
• current category of post (returned by php).
• current post id (returned automatically since we are in single.php).
• current tab.
• current page inside tab.
The problem is that I am actually including history.js to my website so that I can manage the history stack and the clicks on browser back-forward buttons.
Actually, the only URL structure I am having is:
As you know, Wordpress allows navigating between posts by only changing p parameter, so this url structure is maintained during all navigation. And inside each post page, I can do further navigation via AJAX, keeping the same post permalink in adress bar, which is not good for history management, SEO, bookmarking.....
How can I add the other 2 last parameters (current tab, current page) in an efficient way so that my URLs become like:
Doing so, I think I can perform conditionnal tests inside History.Adapter.bind(window, 'statechange', function() {} so that I run history actions based on the values of the 3 parameters (current post_id, current_tab and current_page).
Do you have an idea or a better approach for doing such?
Making my website full jquery-ajaxified, respecting history and using wordpress is an issue that I am digging to resolve for a long time. Your help is really appreciated.
share|improve this question
add comment
Your Answer
Browse other questions tagged or ask your own question. |
global_01_local_0_shard_00000017_processed.jsonl/33605 | Take the 2-minute tour ×
I'm doing my PhD research in A.I. and I've gotten to the part where I have to start using CUDA libraries for my testing platform. I've played with CUDA before, and I have a basic understanding of how GPGPU works, etc, but I am troubled by the float precision.
Looking at GTX680 I see FP64: 1/24 FP32, whereas Tesla has full FP64 at 1.31 TFLOPS. I understand very well that one is a gaming card, while the other is a professional card.
The reason I am asking is simple: I cannot afford a Tesla, but I may be able to get two GTX680. While the main target is to have as many CUDA cores and memory, float precision may become a problem.
My questions are:
1. How much of a compromise is the small float precision in Gaming GPU's?
2. Isn't 1/24 of a 32bit float precision too small? Especially compared to previous Fermi of 1/8 FP32
3. Is there a risk of wrong computation results due to the smaller float precision? I.e in SVM, VSM, Matrix operations, Deep Belief Networks, etc, could I have issues with the results of the algorithms due to the smaller floating point, or does it simply mean that operations will take longer/use more memory?
Thanks !
share|improve this question
These opinion-soliciting questions are in general not a good fit for stackoverflow. Before your question gets closed let me state my opinion: If you can afford two GTX 680, you can also afford a GTX Titan where you get native FP64 speed (1/3 FP32 just as on Tesla). That saves you the pain of multi-GPU programming (unless that is what you want to learn). And it even comes close to the FP32 speed of two GTX 680 and has the other goodies of compute capability 3.5 like up to 255 registers per thread. – tera Apr 16 '13 at 1:54
@tera Thanks, that makes much more sense. I was looking at the 1/3 F32 of titan after I posted. And no, I don't want to get into multi-GPU programming, just importing cuda libraries. – Alex Apr 16 '13 at 1:59
add comment
1 Answer
up vote 6 down vote accepted
These are very subjective questions.
It's not entirely clear that you understand the difference between C or C++ float and double datatypes. FP32 vs. FP64 refers to float and double in C or C++. The numbers of 1/8 and 1/24 that you refer to are not affecting precision but they are affecting throughput. All of the GPUs you mention have some FP64 double-precision capability, so the differences don't come down to capability so much as performance.
It's very important for you to understand whether the codes you care about depend on double-precision floating point or not. It's not enough to say things like "matrix operations" to understand whether FP32 (float) or FP64 (double) matters.
If your codes depend on FP64 double, then those performance ratios (1/8, 1/24, etc.) will be relevant. But your codes should still run, perhaps more slowly.
You're also using some terms in a fashion that may lead to confusion. Tesla refers to the NVIDIA GPGPU family of compute products. It would be better to refer to a specific member of the Tesla family. Since you mention 1.31 TFlops FP, you are referring to Tesla K20X. Note that K20X also has a ratio between FP64 throughput and FP32 throughput (i.e. it can be even faster than 1.31 TFlops on FP32 codes).
If your algorithms depend on double they will still run on any of the products you mention, and the accuracy of the results should be the same regardless of the product, however the performance will be lower, depnding on the product. If your algorithms depend on float, they will run faster on any given product than double, assuming floating point throughput is the limiting factor.
You may also want to consider the GeForce GTX Titan. It has double-precision floating point performance that is roughly on par with Tesla K20/K20x.
share|improve this answer
Thank you, you just verified what I was starting to understand. The lower FP in GTX family affects the rate at which double precision is processed, correct? Also, yes, I am using Sparse Matrices of doubles, and that is the primary reason I am concerned about float precision. From both your answer and the comment above, it seems like GTX Titan may be the best compromise between the two. – Alex Apr 16 '13 at 2:16
Yes, for most members of the GeForce family, the double-precision throughput is significantly lower than various members of the Tesla family. GTX Titan is the exception. Since the principal target of GeForce is consumer graphics and gaming, which do not depend on FP64 at all, the lower FP64 throughput there does not matter. K10 on the Tesla side is also an exception in the other direction, as it has relatively low FP64 throughput. – Robert Crovella Apr 16 '13 at 2:21
Depending on the nature of the sparse matrix processing, the code may becomes bound by memory throughput before it become bound by DP throughput, even with the lower DP throughput of a gaming GPU. It depends on the ratio of FLOPS / bytes. – njuffa Apr 16 '13 at 4:56
@njuffa Are you referring to the device memory? – Alex Apr 16 '13 at 13:37
Yes, the memory on the graphics card. I should have probably be clearer and said that sparse matrix code may be limited by the throughput of global memory, rather than the throughput of the floating-point units in the GPU. – njuffa Apr 17 '13 at 9:31
show 2 more comments
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33606 | Take the 2-minute tour ×
when I moved my files to a new machine and when Im trying to commit changes I get the following window with no options to choose:
enter image description here
Any ideas?
share|improve this question
See here : stackoverflow.com/questions/1679099/… – user2403748 May 21 '13 at 1:41
add comment
Your Answer
Browse other questions tagged or ask your own question. |
global_01_local_0_shard_00000017_processed.jsonl/33607 | Take the 2-minute tour ×
How can I send the POST data from my form to two different pages depending on which post button is clicked?
My "Export" button sends the POST data to 'export.php', but the "Graphique" button must send the POST data to the 'graphique.php' page.
Here is my code:
<form name="TCAgregat" class="TCAgregat" action="export.php" method="post">
<input type="hidden" name="daco" value="<?php echo $DConso; ?>"></input>
<input type="hidden" name="CNS" value="<?php echo $CNewCentres; ?>"></input>
<input type=submit border="0" class="EXP" name="exp" value="EXPORT" />
<input type=submit border="0" class="DCB" name="dcb" value="GRAPHIQUE" />
How can I achieve this?
share|improve this question
Put them in separate forms? – user1508519 May 3 '13 at 9:41
Or use javascript or acnhor tags with query strings – asprin May 3 '13 at 9:41
use ajax here.. – Yogesh Suthar May 3 '13 at 9:41
Change form action on button click. – dfsq May 3 '13 at 9:41
You can use JavaScript, to evaluate which button was pressed and changed the "action" page accordingly, before submitting. – Orel Eraki May 3 '13 at 9:44
show 2 more comments
4 Answers
up vote 2 down vote accepted
Change form action on button click:
$("form").on("click", ":submit", function(e) {
$(e.delegateTarget).attr('action', $(this).data('action'));
<input type=submit data-action="export.php" value="EXPORT" />
<input type=submit data-action="graphics.php" value="GRAPHIQUE" />
share|improve this answer
That is it Thank you very much – achillix May 3 '13 at 9:59
add comment
Since you've tagged it with jQuery, here is a solution:
var but = $(this).val();
var action = '';
if(but == 'EXPORT')
action = 'export.php';
else if(but == 'GRAPHIQUE')
action = 'graphique.php';
$('form').attr('action', action);
share|improve this answer
add comment
Use JavaScript to rewrite the action of the form, then submit().
share|improve this answer
If you're going to do it this way (which I wouldn't recommend as it introduces an unnecessary dependency on JS), then calling submit() is redundant. Just don't cancel the default action of the form in the first place. – Quentin May 3 '13 at 9:44
More of a comment than an answer. Should have at least given an example. – asprin May 3 '13 at 9:50
add comment
Say action="handler.php" and then write handler.php something along the lines of:
if (isset($_POST['exp'])) {
} elseif (isset($_POST['dcb'])) {
} else {
// Default state / error handling
share|improve this answer
just a point. what if he wants to send the data to both the files and not just one? – itachi May 3 '13 at 9:46
Then he can include both of them in the same branch of the if statement. Nothing in the question remotely suggests that he might want to though. – Quentin May 3 '13 at 9:47
he google translated it probably. but the 1st line How can send the same POST data totwo different pages to me it seemes like he is trying to post on two different page at the same time.... just saying. – itachi May 3 '13 at 9:52
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33608 | Take the 2-minute tour ×
I'm trying to use Jersey with Jackson in Android, but I got the following error:
Could not find class 'javax.xml.stream.XMLInputFactory', referenced from method org.glassfish.jersey.message.internal.MessagingBinders$MessageBodyProviders.configure
Here is my code:
public static List<Task> getAllTasks() {
WebTarget target = client.target(TARGET).path(ALL_TASKS_RESOURCE)
.queryParam("lang", "en");
List<Task> tasks = target.request(MediaType.APPLICATION_JSON_TYPE)
.get().readEntity(new GenericType<List<Task>>() {});
return tasks;
I found out that StAX XML parser is not a part of Android, but there are some alternatives. I just don't understand why Jersey wants to stream XML, and not just fetch it from the server and let Jackson to map it to POJO?
share|improve this question
add comment
Your Answer
Browse other questions tagged or ask your own question. |
global_01_local_0_shard_00000017_processed.jsonl/33609 | Take the 2-minute tour ×
I have a Cocoa program that is editing hundreds (sometimes thousands) of third-party files and I want to create a log-type output for the end user to see (although I don't need things like timestamps). Currently I am simply appending strings to the outlet:
@property (unsafe_unretained) IBOutlet NSTextView *finalText;
self.finalText.string = [self.finalText.string stringByAppendingFormat:@"Final results:\n"];
but this is extremely inefficient. When I run that code on 700 files with the above code (all of the commenting) turned off it takes 4 seconds to execute, with the above code turned on it takes 40 seconds to create the necessary 8,000 lines of output. Oh, and did I mention that Xcode says that my memory usage spikes to over 2GB during the processing? Yikes!
I understand that what I am doing is inefficient but I don't know the best way to be efficient. What is the best way to create 8,000 lines of text that the end-user can see at the end? Would something like Lumberjack be the best solution?
share|improve this question
Need to see more code to comment on the efficiency. You may just be blocking if you're doing everything on the main thread. – uchuugaka Jun 30 '13 at 23:56
How about creating a string, and when it reaches a certain size, you write it to a file, then provide the user with a filename to look at? – 7stud Jun 30 '13 at 23:56
I saw someone suggest on another question to use textStorage but I need to use formats (adding variables to the output) and I don't see a way to use formats with textStorage items. – Matthew Kelling Jul 1 '13 at 0:07
Make a string using stringWithFormat, then make an attributed string out of that and append it. Be sure to clean up the autoreleased temporary objects though. – Catfish_Man Jul 1 '13 at 2:14
Go download Hex fiend (source available) and study how it does I/O. The answers below are only likely to work by coincidence and, even then, may not meet your performance needs. This is a tricky area, btw, but also a very interesting one. The key is to reduce I/O, be it memory or, especially, disk. Part of that is avoiding autorelease pools, a part is using the I/O capabilities of the system efficiently. – bbum Jul 1 '13 at 3:07
show 1 more comment
3 Answers
up vote 0 down vote accepted
[self.textView.textStorage appendAttributedString: ... ]
That will do much less work. Also, wrap that in @autoreleasepool to clean up the temporary objects promptly.
share|improve this answer
Thanks! I ended up creating some textStorage variables that I dumped into the textView at the end of the code. Now there is no noticeable impact on time or memory usage when I create the needed output! – Matthew Kelling Jul 4 '13 at 7:15
add comment
Lumberjack is great for logging. Also, you should use NSMutableString to avoid creating copies of same string again and again.
share|improve this answer
I had Lumberjack working but I didn't know how to read back in the .log files (how to find it on the user's HD). Also the .log file includes the timestamp and such, is there a way to not include that? – Matthew Kelling Jul 1 '13 at 0:15
add comment
You should use this:
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
That will take one or two milliseconds with a 300GB file, and will only load the entire file into RAM if there is enough RAM available. If there isn't enough RAM available it will only load the parts of the file you actually read and also heuristically/predictively read parts the operating system thinks you are going to read.
NSString is a convenience wrapper around CFString. If you drop down to the lower level CFString API you will be able to write your code so that it uses less RAM (for example, by partially decoding large files). Partially reading a string from a file is complicated, you will need to learn how UTF-8 works and make sure you don't cut the data half way through a UTF-8 sequence. I would try to avoid CFString if you can get acceptible performance with NSString.
Also, do you have a for or while loop iterating through all of the files? Make sure you have an "autorelease" pool in your loop:
NSArray *urls = <# An array of file URLs #>;
for (NSURL *url in urls) {
@autoreleasepool {
NSError *error;
NSString *fileContents = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding error:&error];
/* Process the string, creating and autoreleasing more objects. */
(from http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html#//apple_ref/doc/uid/20000047-SW2)
share|improve this answer
Thanks, will take a look at that. To be clear the information that I am sending to the end user is not directly tied to what is in the files, IE: I am reading a file, doing something to the file, then telling the user what I did to the file. What is in the file is not being shown to the user. – Matthew Kelling Jul 1 '13 at 0:51
Are you sure about that? The docs give no suggestion that -initWithContentsOfURL: will check the amount of RAM available, and it don't expect it to – Mike Abdullah Jul 5 '13 at 15:36
Yes, I'm sure - I have tested it. When I init an NSData object with a file that does't fit in RAM, it takes a fraction of a millisecond to create the object (it would take a few minutes if reading the entire file). I can access amy part of the file immediately. If the file fits in RAM (maybe it's only 8GB and my system has 12GB) then my app will use that much. It is being mapped as virtual memory/swap and the kernel tries to keep those files in RAM but chucks them out (based on least recently used areas of the file) if the RAM is needed for anything else. – Abhi Beckert Jul 5 '13 at 22:18
I wonder why I was downvoted? My answer is the result of years of experience/experimentation to find the best way to do what the question asks. – Abhi Beckert Jul 5 '13 at 22:25
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33610 | Take the 2-minute tour ×
I'm getting this error when my Heroku app starts up:
invalid connection option "fallback_application_name"
Any idea what could be causing that?
share|improve this question
possible duplicate of Setting PostgreSQL application_name on Heroku – Daniel Vérité Jul 16 '13 at 17:53
seems odd to me. i'm not doing anything special and heroku is OOTB and works on my other apps. i don't desire to set the application name to anything useful, i just dont want my app to crash – wachutu Jul 16 '13 at 18:19
add comment
1 Answer
It seems to be a problem with heroku + postgres > 0.14
Here's the comment in my Gemfile that explains the details:
# Warning, if you remove the version number and end up with postgres > 0.14, expect this:
# #/app/vendor/bundle/ruby/2.0.0/gems/activerecord-3.2.13/lib/active_record/connection_adapters/postgresql_adapter.rb:1216:in `initialize': invalid connection option "fallback_application_name" (PG::Error)
# when trying to get app running on Heroku
gem 'pg', '=0.14.1'
share|improve this answer
I have had the same issue with pg 0.15.1, ruby 1.9.3 and 9.1, 9.2 and 9.3 versions os postgresql. Fixing the gem version to 0.14.1 and postgresql to 9.1 and now everything is working again. – Carlos Jul 17 '13 at 10:04
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33611 | Take the 2-minute tour ×
I am trying to find a module that can help to ask a question to end an authentication. for example when I connect in ssh, the module ask me to resolve a equation or to answer to a question.
share|improve this question
no one knows! :s – user2354740 Aug 28 '13 at 20:27
solved, i wrote it myself. – user2354740 Aug 28 '13 at 20:29
add comment
Your Answer
Browse other questions tagged or ask your own question. |
global_01_local_0_shard_00000017_processed.jsonl/33612 | Take the 2-minute tour ×
I am new to elasticsearch and am trying to understand how to setup elastic search in our environment - my requirements are fairly basic:
1. Environment is multi-tenant
2. Simple setup is three datacenters, each datacenter needs to be a redundant copy - so we can fail two datacenters and there will still be one standing.
3. We will scale up each datacenter as needed, users can access elastic search from each of the three data centers.
4. search will be used for files, emails, IMs, calls etc.
My questions are:
1. does this topology / setup lend itself to elasticsearch natively? If so, how?
2. How do I know how many shards I need? Do I just overallocate for fun?
3. I assume I should have one index per tenant? And I should have just one cluster? Why would I want more?
4. I have spent hours trying to find info on this, if you might accuse me of prematurely posting - please let me know where there is a good topological overview
share|improve this question
add comment
Your Answer
Browse other questions tagged or ask your own question. |
global_01_local_0_shard_00000017_processed.jsonl/33613 | Take the 2-minute tour ×
I'm looking through a very large hydrodynamics code in c which has, often, some very poor variables choices. Including a global variable named just 'g'. Similarly, there's a file with a variable named 'geom' and lots of other variables which contain the substring 'geom' (e.g. geometry, geomAL, geom_arb, etc.).
Is there any way to search for variables that exactly match a regex, instead of partially?
For example: searching for 'geom' does not match 'geomAL'. Obviously emacs doesn't a priori know where a variable starts or ends, but could this be constructed as a function for c-mode?
share|improve this question
add comment
4 Answers
up vote 5 down vote accepted
The Emacs regular expression engine (C-M-s <regexp>) has various operands for this sort of thing, such as the word boundary \< and \> zero-width assertions. So \<geom\> would match geom alone and (depending on your mode's syntax table) perhaps also the prefix in geom_something. Try \<geom\>[^_] if you need to exclude the underscore suffix.
share|improve this answer
Sorry folks, I edited this answer instead of my own by accident. Is there a way to cancel edits? – mvw Aug 30 '13 at 13:52
@mvw: It was rejected by the reviewers. You can also rollback an edit by clicking on the "edited" link and looking for the rollback link in the header of the previous edit before the unwanted one. – tripleee Aug 30 '13 at 14:04
I personally prefer the \b operand, which I find a little easier to type then, < or >. – Bruce Connor Aug 30 '13 at 20:38
@BruceConnor Thanks! That's indeed a little more pleasant – zhermes Aug 31 '13 at 14:04
add comment
You can use C-u C-s \_<g\_> which will search for the symbol g using a regular expression search with symbol-boundary markers. Or in a recent enough Emacs you can do M-s _ g which will do essentially the same (M-s is the "search prefix key" in which M-s _ is isearch-forward-symbol).
share|improve this answer
add comment
http://www.emacswiki.org/emacs/RegularExpression has pretty much everything you need if you want to use emacs regexps.
share|improve this answer
add comment
Have you tried out the Emacs TAGS system? It should be able to parse the vars out and it might offer exact lookups. See here: http://www.emacswiki.org/emacs/EmacsTags
Generate the tags table with the etags helper:
etags *.c
Look for a tag with
M-. your-var-name
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33614 | Take the 2-minute tour ×
I'm trying to define a macro that generates an anonymous function taking one argument named it, for succinctness, so that instead of
(λ (it) body)
I can write
(λλ body)
(In other words, (λλ body) transforms to (λ (it) body))
(define-syntax-parameter it #f)
(define-syntax λλ
(syntax-rules ()
((_ body)
(λ (x) (syntax-parameterize ((it x)) body)))))
(λλ (< it 0)) ; For testing
I get operators.rkt:13:28: ?: literal data is not allowed; no #%datum syntax transformer is bound in the transformer environment in: #f at (define-syntax-parameter if #f), but as far as I can tell, this is exactly like the example given in racket's doc for how to use define-syntax-parameter. I can suppress the error by replacing #f with a function (I used member, but not for any real reason), but after doing that, I get operators.rkt:17:38: x: identifier used out of context in: x. What am I doing wrong?
share|improve this question
add comment
2 Answers
You left out the syntax-id-rules part in the example. It's the part that specifies that it should expand to x. Alternatively, you can use make-rename-transformer:
#lang racket
(require racket/stxparam)
(define-syntax-parameter it #f)
(define-syntax λλ
(syntax-rules ()
((_ body)
(λ (x) (syntax-parameterize ([it (make-rename-transformer #'x)]) body)))))
((λλ (< it 0)) 5)
((λλ (< it 0)) -5)
share|improve this answer
To clarify this further, the thing that the syntax parameter is "bound to" lives at the syntax world -- so you don't want to use x since that's a runtime thing, instead you want to use #'x. But you really want to create a kind of a macro that expands to #'x, and therefore the syntax-id-rules or the more convenient make-rename-transformer shorthand. – Eli Barzilay Sep 20 '13 at 2:07
add comment
Syntax parameters are not the only way to implement the macro you have in mind. A simpler (IMO) way is to just use datum->syntax to inject the identifier it:
(define-syntax (λλ stx)
(syntax-case stx ()
((_ body ...)
(with-syntax ((it (datum->syntax stx 'it)))
#'(λ (it) body ...)))))
To use your example:
(define my-negative? (λλ (< it 0)))
(my-negative? -1) ;; => #t
share|improve this answer
Actually, I believe this is a fine use of syntax-parameterize. See Barzilay et al.'s "Keeping it Clean" paper. – stchang Sep 19 '13 at 17:42
Fair enough, I'll soften my wording a bit. I still think it's overkill when datum->syntax will do, but your answer is good (+1). – Chris Jester-Young Sep 19 '13 at 17:47
I think the key is that you can get non-hygiene in syntax-rules and not have to switch to the heavier syntax-case. – stchang Sep 19 '13 at 17:48
@stchang That is actually a very good point, and I'll remember that next time before I start telling people "no, you can't break hygiene in syntax-rules". :-P – Chris Jester-Young Sep 19 '13 at 17:54
argh. ...sorry, but as someone who invested so much effort on explaining why it's a bad idea, it looks like I'm morally obliged to downvote you on this one (for the first time...). The main real (and highlevel) problem with datum->syntax is that it looks like it works, only it can bite you later horribly. It's especially effective at getting bugs that are bad enough to make people go back to the "simple world of defmacro". – Eli Barzilay Sep 20 '13 at 2:03
show 1 more comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33615 | Take the 2-minute tour ×
I'm having a problem with ejb load balancing inside glassfish 3 cluster.
I have one ear project witch contains EJB module and WEB module. All my EJB's are stateless and remote in EJB module. In WEB module I have one servlet which suppose to lookup for ejb and print on which instance in cluster he get ejb.
I'm calling EJB from servlet like this:
Properties props = System.getProperties(); props.setProperty("com.sun.appserv.iiop.endpoints", ",,,"); InitialContext ic = new InitialContext();
EJBRemote ejb = (EJBRemote) ic.lookup("java:global/app-name-ear/app-ejbs/EJB!com.tt.EJBRemote");
Problem is that my request always ends up on first instance of 4 possible.
How I can achieve load balancing in my case? Do I need stand alone client (web-app in separate project)? How glassfish cluster knows that there are another instances where my servlet can lookup for EJB?
share|improve this question
Try to enable Per-Request Load Balancig, and let me know if this works. – Gabriel Aramburu Oct 25 '13 at 21:21
Hi, Gabriel. Thanks for response. I have try to enable PRLB but I've got the same situation. Every request ends up on same instance. – user2120041 Oct 28 '13 at 10:36
It seems to be that there is a WS bug. Possible bug report. – Gabriel Aramburu Oct 28 '13 at 20:55
Thanks Gabriel. I didn't know about this bug. Is it a good idea to implement my own load balancer (round robin)? Any hint or example is welcome. – user2120041 Oct 29 '13 at 8:14
I think still there is a chance. Try to share the same EJB reference among all request. I mean, the first request will lookup the Stub and store it in Session, the next ones instead of lookup a new stub will use the one previously polled; this way the stub's state will be maintained among requests. (It's hard to believe that proxy load balancing doesn't work in WS.) – Gabriel Aramburu Oct 29 '13 at 14:25
add comment
Your Answer
Browse other questions tagged or ask your own question. |
global_01_local_0_shard_00000017_processed.jsonl/33616 | Take the 2-minute tour ×
So I'm working on designing an OS, and I'm working on designing (not coding yet) the kernel. This is going to be for an x86 operating system, and my target is for more modern computers, so RAM can be considered to be at least 256M or more.
My question is this: What is a good size to make the stack for each thread run on the system? Or better yet, should I try to design the system in such a way that the stack can be extended automatically if the max length is reached?
I think if I remember correctly that a page in RAM is 4k (4096 bytes) and that just doesn't seem like a lot to me. I can definitely see times, especially when using lots of recursion, that I would want to have more than 1000 ints in RAM at once. Now, the real solution would be to have the program doing this to use malloc and manage its own memory resources a bit, but really I would like to know the user opinion on this.
Is 4k big enough for a stack with modern PC programs? Should the stack be bigger than that? Should the stack be auto-expanding to accomodate any (reasonable) size? I'm interested in this both from a practical developer's standpoint, and a security standpoint.
Or, on the flip side, is 4k to big for a stack? Considering normal program execution (especially from the point of view of classes in C++) I notice that good code tends to malloc/new the data it needs when classes are created, to minimize the data being thrown around in a function call.
What might also be important here, and I haven't even gotten into this, is the size of the processor's cache memory. Ideally, I think the stack would reside in the cache to speed things up, and quite frankly I'm not sure if I need to achieve this, or if the processor can handle it for me? I was just planning on using regular boring old RAM for testing purposes.
I can't decide, so I ask you.
share|improve this question
add comment
5 Answers
up vote 7 down vote accepted
Stack size depends on what your threads are doing. My advice:
• make the stack size a parameter at thread creation time (different threads will do different things, and hence will need different stack sizes)
• provide a reasonable default for those who don't want to be bothered with specifying a stack size (4K appeals to the control freak in me, as it will cause the stack-profligate to, er, get the signal pretty quickly)
• consider how you will detect and deal with stack overflow. Detection can be tricky. You can put guard pages--empty--at the ends of your stack, and that will generally work. But you are relying on the behavior of the Bad Thread not to leap over that moat and start polluting what lays beyond. Generally that won't happen...but then, that's what makes the really tough bugs tough. An airtight mechanism involves hacking your compiler to generate stack checking code. As for dealing with a stack overflow, you will need a dedicated stack somewhere else on which the offending thread (or its guardian angel, whoever you decide that is--you're the OS designer, after all) will run.
• I would strongly recommend marking the ends of your stack with a distinctive pattern, so that when your threads run over the ends (and they always do), you can at least go in post-mortem and see that something did in fact run off its stack. A page of 0xDEADBEEF or something like that is handy.
By the way, x86 page sizes are generally 4k, but they do not have to be. You can go with a 64k size or even larger. The usual reason for larger pages is to avoid TLB misses. Again, I would make it a kernel configuration or run-time parameter.
share|improve this answer
I never thought about making it something to configure at compile time. I also seem to like 4k, the control freak tells me that if you really need to use more than that much memory, you should be doing it with malloc. ^_^ That said, there are crazy AI programmers out there that love their recursion. – Nicholas Flynt Oct 13 '08 at 5:23
if you are allocating many of the same-size thing over and over again, you should consider a fixed-block allocator. It can be much more efficient than the general-purpose malloc. – bog Oct 13 '08 at 8:14
add comment
I'll throw my two cents in to get the ball rolling:
• I'm not sure what a "typical" stack size would be. I would guess maybe 8 KB per thread, and if a thread exceeds this amount, just throw an exception. However, according to this, Windows has a default reserved stack size of 1MB per thread, but it isn't committed all at once (pages are committed as they are needed). Additionally, you can request a different stack size for a given EXE at compile-time with a compiler directive. Not sure what Linux does, but I've seen references to 4 KB stacks (although I think this can be changed when you compile the kernel and I'm not sure what the default stack size is...)
• This ties in with the first point. You probably want a fixed limit on how much stack each thread can get. Thus, you probably don't want to automatically allocate more stack space every time a thread exceeds its current stack space, because a buggy program that gets stuck in an infinite recursion is going to eat up all available memory.
share|improve this answer
add comment
If you are using virtual memory, you do want to make the stack growable. Forcing static allocation of stack sized, like is common in user-level threading like Qthreads and Windows Fibers is a mess. Hard to use, easy to crash. All modern OSes do grow the stack dynamically, I think usually by having a write-protected guard page or two below the current stack pointer. Writes there then tell the OS that the stack has stepped below its allocated space, and you allocate a new guard page below that and make the page that got hit writable. As long as no single function allocates more than a page of data, this works fine. Or you can use two or four guard pages to allow larger stack frames.
If you want a way to control stack size and your goal is a really controlled and efficient environment, but do not care about programming in the same style as Linux etc., go for a single-shot execution model where a task is started each time a relevant event is detected, runs to completion, and then stores any persistent data in its task data structure. In this way, all threads can share a single stack. Used in many slim real-time operating systems for automotive control and similar.
share|improve this answer
I can see two flaws here. The main one is allowing the system to overflow the stack on its own. If I do that all it takes is a single recursive infinite loop and blamo, the stack for 1 process suddenly consumes the entire PC... As for the one shot deal, this is a multi-tasking OS, so no beans there. – Nicholas Flynt Oct 13 '08 at 7:08
add comment
Search for KERNEL_STACK_SIZE in linux kernel source code and you will find that it is very much architecture dependent - PAGE_SIZE, or 2*PAGE_SIZE etc (below is just some results - many intermediate output are deleted).
# define KERNEL_STACK_SIZE_ORDER 3
# define KERNEL_STACK_SIZE_ORDER 2
# define KERNEL_STACK_SIZE_ORDER 1
# define KERNEL_STACK_SIZE_ORDER 0
u64 mca_stack[KERNEL_STACK_SIZE/8];
u64 init_stack[KERNEL_STACK_SIZE/8];
# define KERNEL_STACK_SIZE 0x2000
share|improve this answer
add comment
Why not make the stack size a configurable item, either stored with the program or specified when a process creates another process?
There are any number of ways you can make this configurable.
There's a guideline that states "0, 1 or n", meaning you should allow zero, one or any number (limited by other constraints such as memory) of an object - this applies to sizes of objects as well.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33617 | Take the 2-minute tour ×
I am using the excellent instafeed.js plugin and it works great. I would though like to swap the {{id}} tag within my template function for a counter that gives each line <li> a number from 1 to X. I am sure this is simple but other examples I have found online don't seem to do the job. Can anyone point me in the right direction? Thanks
<script type="text/javascript">
$(document).ready(function() {
var userFeed = new Instafeed({
get: 'user',
userId: xx,
accessToken: 'xx',
resolution: 'standard_resolution',
link: 'false',
limit: '7',
template: '<li data-slidr="{{id}}" class="five columns alpha omega" style="min-height: 278x; overflow: hidden;"><img src="{{image}}" class="scale-with-grid" /></li>'
share|improve this question
add comment
Your Answer
Browse other questions tagged or ask your own question. |
global_01_local_0_shard_00000017_processed.jsonl/33618 | Take the 2-minute tour ×
I have 2 tables product_history having 3 columns
1. id
2. product_id
3. admin_id
And another table(product_data) is to store data like..
1. admin name
2. product name
3. product description
4. product number .... etc.
Now I want to write a Mysql Trigger like. when record insert in product_history table I need to fetch all products and admin related information from product table and admin table and insert those records in product_data table.
How can I do this?
Basically I want to use select query with in Trigger body, but that select query can return multiple records. Is it possible?
share|improve this question
add comment
1 Answer
I think that you can retrive this information without need to insert data in another table, you can have: admin_id in your product_data table (and your admin_name, but would be redundat).
With your current idea, in your current product_data you should have a product_id field to related with your other table.
share|improve this answer
but I knowingly need to insert that records in product_data table. Its my requirement. – Abhijeet Dange Dec 20 '13 at 4:18
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33619 | Take the 2-minute tour ×
For our current J2EE project based on JBoss, we need to interface with a remote system using message driven beans and a JCA resource adapter provided as a RAR file by a third party. I would like to package and deploy the entire project as an EAR file to our JBoss server. Most notably, the RAR file should be embedded within the EAR file and not be deployed globally.
All of this is working fine so far, but I'm not particularly happy with the way the RAR file is referenced. The jboss.xml packaged with the MDB for example, currently looks like this:
While this is generally working fine, it will break when the EAR file is renamed to "test2.ear". Is there a way to reference the embedded RAR file without hard-coding the containing archive's name?
Edit: Almost two months later, I still haven't found a real answer to this question. Asking around, all I got were those two helpful suggestions: "Use Maven properties and filtering", and "Don't include the RAR within the EAR." I strongly suspect that currently there is no way to handle this properly in JBoss. So I'll give up on it and just accept the only answer I got here.
share|improve this question
add comment
1 Answer
up vote 2 down vote accepted
are you using maven to build? If so, you can set a maven property that names the ear file and use that name to set values in resources files using a placeholder
e.g xxx
then use
just make sure you set the resources that will have the placeholders
something like this:
share|improve this answer
Thanks for your answer! I must admit that in the meantime, I cross-posted this here: community.jboss.org/message/529160 The most useful answer I got so far was quite similar to what you are suggesting. I am using maven, and I have settled for using resource filtering. But it still doesn't feel quite right, more like a work-around. – cg. Mar 9 '10 at 9:34
Accepted the only answer I got here now. See my edits above. – cg. Apr 9 '10 at 12:25
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33620 | Take the 2-minute tour ×
I need to break apart a string that always looks like this:
something -- something_else.
I need to put "something_else" in another input field. Currently, this string example is being added to an HTML table row on the fly like this:
I figure "split" is the way to go, but there is very little documentation that I can find.
share|improve this question
So what exactly should be put/appended in/to which element? – Felix Kling Mar 31 '10 at 19:18
Just curious, what did you search for that you didn't find any documentation? I searched on Google for both "javascript split" and "jquery split" and the first result in both cases was the location I linked to. – Charles Boyung Mar 31 '10 at 19:23
And I am sorry but I cannot see how your code example is related to your split() problem. Give us more information :) – Felix Kling Mar 31 '10 at 19:26
I was mistakenly thinking it was a jQuery solution when in fact it's actually a javascript thing. I also saw that documentation but dismissed it too quickly – Matt Mar 31 '10 at 19:30
You need to remember that jQuery IS javascript - unless you are doing something with selectors (and a few other things that start with $.) you are just doing javascript, not jQuery. – Charles Boyung Mar 31 '10 at 19:35
show 1 more comment
4 Answers
up vote 228 down vote accepted
Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.
If you use .split() on a string, then you get an array back with the substrings:
var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"
If this value is in some field you could also do:
tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));
share|improve this answer
add comment
If it is the basic JavaScript split function, look at documentation, JavaScript split() Method (W3Schools).
Basically, you just do this:
var array = myString.split(' -- ')
Then your two values are stored in the array - you can get the values like this:
var firstValue = array[0];
var secondValue = array[1];
share|improve this answer
+1, however... I realize that JS type names are case-sensitive but still, could you please change the name of the array variable of Array type to something else, not to confuse JS newbs? Cheers! – TildalWave Jan 28 '13 at 22:15
add comment
Look in JavaScript split() Method
"something -- something_else".split(" -- ")
share|improve this answer
add comment
var str;
var sid = new Array();
str = "your_string";
sid = (str.split("_"));
share|improve this answer
var sid = new Array() is useless, it just adds to amount of time the code needs to run. – epascarello May 11 '12 at 14:39
ok,what's the best of new array()? – Dev.H May 12 '12 at 13:23
You are treating JavaScript like it is Java or C#. JavaScript does not need typed variables and the split turns it into an Array. – epascarello May 12 '12 at 16:12
i think when i tring to do that did'nt work with me ,but i will try again ,thanks – Dev.H May 13 '12 at 11:22
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33621 | Take the 2-minute tour ×
Our app servers (weblogic) all use log4j to log to the same file on a network share. On top of this we have all web apps in a managed server logging errors to a common error.log. I can't imagine this is a good idea but wanted to hear from some pros. I know that each web app has its own classloader, so any thread synchronization only occurs within the app. So what happens when multiple processes start converging on a single log file? Can we expect interspersed log statements? Performance problems? What about multiple web apps logging to a common log file? The environment is Solaris.
share|improve this question
Have you experienced any actual log corruption? I would be surprised if the answer is no, but otherwise I can't imagine why you are asking the question. – Yishai Apr 7 '10 at 21:52
No log corruption yet, that I'm aware of. I'm asking because I couldn't believe they had set it up this way and wanted some feedback to confirm my suspicions. – Andrew Apr 7 '10 at 22:06
I should have clarified that a single log file is not a requirement; it was more design by coincidence. A few have mentioned the proper technique for a single log file is to use a network log service, or the application's server log service for per server logging. – Andrew Apr 8 '10 at 14:43
add comment
7 Answers
up vote 3 down vote accepted
This is generaly bad idea to have not synchronized write access to a file and certainly bad programming practice. The only case it might work is an append to a file on local machine - everybody just adds lines at the end of file.
But, since your file is on the network share, it will probably quickly turn into garbage. You didn't tell which distributed filesystem you are using, but for NFS you can find following explanation on open(2) man page:
Of course this is C, but since Java is implemented in C it cannot do any better than that (at least not with regard to system calls:-)).
share|improve this answer
I believe it is NFS but they don't let me near the servers. So what about multiple web apps in same server logging to the same file? That would be one process. – Andrew Apr 7 '10 at 22:10
One process, many threads this is still the same. Also, aren't different web apps launched in separate processes? Anyway, this has a chance to work as at the beginning of my answer. But it is a bad idea to depend on that. – pajton Apr 7 '10 at 22:15
All web apps of a server run in the same process. Ok, so it would be safe on the Unix level, but could still get interspersed logging. – Andrew Apr 7 '10 at 22:20
Interspersed for sure and might work. It would be best to test it in your environment. If it works for a certain period of time it will probably work. – pajton Apr 7 '10 at 22:22
add comment
In prudent mode logback will safely handle multiple JVMs possibly on different hosts writing to the same network-shared file. It can even deal with temporary network failures. Performance should be quite acceptable for few nodes, say 4 or less. For 5 or more nodes all logging heavily you may notice a performance hit.
share|improve this answer
add comment
We have a requirement where we need to produce a single file from all the managed server running the same application . we developed a java logging server which opens ups a port and listen for log event. we used the log4j socket appender to write log event to the same port and created a single file.
share|improve this answer
add comment
We use org.apache.log4j.net.SyslogAppender to log to a single machine using syslog, and it has worked well for us. I would recommend looking into that as an alternative.
share|improve this answer
Good suggestion. I imagine the calls are asynchronous so not much performance penalty – Andrew Apr 7 '10 at 22:11
add comment
This looks like a really bad idea (corrupt logs, uncertainty of the source of a given log entry are two reasons that come to mind). If you are using Log4j in Weblogic like this, I suggest doing it by-the-book. This will allow you to use one file for the whole app server without any issues.
The suggestion of syncronizing the log writing makes no sense to me, as you would be basically blocking all applications in the app server when they write a log. If logging is frequent, that will slow everything down significantly.
As for multiple app servers, you need to use something other than file based logging if you want them all consolidated. There are a few ways to do this, one is to log to different files and have a different process combine them, but the better option is probably to use a network based logging repository, using Log4j's SocketAppender or some other method (nathan mentions SyslogAppender which is great if you want a Syslog) to ensure that the file access does not get corrupted.
share|improve this answer
add comment
Best case I would imagine you have a potential performance problem with sync access to the log file resource. Worst case would be some of the scenarios you mention.
I would ask two Qs: a) what was the desired goal with this config and b) can you find a better technical solution to achieve the goal.
My guess is that you have a sysadmin who wants to get a "single log file for the system." The file is thrown on the network share to make it easy to get to. The better answer for the goal might be multiple files, local to each system and something like http://www.splunk.com/ for a nice monitor.
share|improve this answer
add comment
If at all possible use a different file for each instance. This will give the best result with the least effort.
The logback alternative to log4j has a prudent mode to its log writer which explicitly jump through hoops to ensure that new things are written at the end of file. I don't think that will work on network shares then.
If you MUST have a central logging location, then consider setting up a server accepting log events and writing them to the appropriate files. This will ensure it is only a single process actually accessing the file system, and will let the JVM help all it can in terms of synchronization etc.
share|improve this answer
Logback's prudent mode works on network shares. For a few server nodes, say 4 or less, it will work quite nicely. – Ceki Apr 8 '10 at 21:10
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33622 | Take the 2-minute tour ×
I generate htm files dynamically using php and .htaccess. I read somewhere that I should remove Etags for files of type text/html? Is that correct? I am wondering if I use etags and If i don't change the content, I could save some bandwidth. I would appreciate if you guys could tell me if I can use etags for htm files.
share|improve this question
add comment
2 Answers
As far as i know the Etag is an http header is generated by the HTTP server used by the cache system.
The idea:
• You ask to stackoverflow.com the image logo.png
• stackoverflow.com will answer to you with a HTTP 304 (content not modified, etag: XXXXXX)
• Your browser before ask the image again will check the cache for a resource called: logo.png, from the website: stackoverflow, with the etag: XXXXXXX
• If the browser find it, it will load the image from the cache, without downloading
• If it can't find it, it will ask again to the web server to download it.
so... for what propose you want use the ETags ?
If you want understand more about the ETags could be interesting download HttpFox for firefox.
Apache have his own cache system and it's used when you download or require any "static" download, like html files and images.
If you want do it on dynamic context you must implement it by yourself.
share|improve this answer
add comment
Etags can be usefull speeding up your website, even with dynamic content (like php scripts). Especially on mobile connections this is important, since connection speed is slower. I use ETag headers on some mobile websites like this:
Hint: You must not include curent time or other often changing content in the page, because this prevents it from beeing cached by the client (the browser).
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33623 | Take the 2-minute tour ×
I'm using Eclipse with the Android SDK. I installed The SDK platform Android 1.6, API 4 using Android SDK and AVD manager, but I can't find the corresponding documentation in the list of the available packages (there's only the doc for the API 7). Where can I find it?
share|improve this question
add comment
3 Answers
up vote 2 down vote accepted
The documentation for API 7 includes the documentation for all previous versions. It's just an offline copy of the Android Developer website. Just as you can see there, next to every method and class in the 'reference' section there's a note saying "Since API x", telling you when it became available.
By the way, and this is my personal opinion only, but there isn't much point in developing for v1.6. As you can see from the official statistics, one third of devices are still running v1.5. It's better to use the trick described here about settings the minimum SDK version to 3, yet targetting SDK 4 to allow you to support multiple screens but ensure compatibility with all versions.
share|improve this answer
Ok, thanks for the tip. – jul Apr 29 '10 at 12:24
This doesn't answer the question. The documentation is changed from one version to another and I would to see the old version. – kilaka Aug 29 '12 at 11:37
add comment
Well in the documentation, you see "Since API level x". If whatever was not available yet in Android 1.6, you'll know. You'll also know if certain things are deprecated.
share|improve this answer
add comment
It seems Google have added an option to see the old documentation. Don't know since when. Anyhow, thank you Google.
When choosing an old API level, the non-available API is grayed out.
See example below for http://developer.android.com/reference/android/provider/ContactsContract.ContactsColumns.html
enter image description here
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33624 | Take the 2-minute tour ×
How do I create a batch file timer to execute / call another batch through out the day Maybe on given times to run but not to run on weekends ? Must run on system times can also be .cmd to run on xp server 2003
share|improve this question
add comment
6 Answers
For the timer part of your script i highly reccomend using:
echo Waiting For One Hour...
echo (Put some Other Processes Here)
pause >nul
This script waits for 1 hour (3600 seconds) and then continues on with the script and the user cannot press any buttons to bypass the timer (besides CTRL+C).
You can use
Timeout /t 3600 /nobreak >nul
If you don't want to see a countdown on the screen.
share|improve this answer
Nice. I just found this searching for a simple batch file timer solution - works great, thanks! EDIT: I am using this together with a goto-"loop" to create a simple script which periodically updates my SVN working copy. – alexander.biskop Feb 27 '12 at 15:51
add comment
I would use the scheduler (control panel) rather than a cmd line or other application.
Control Panel -> Scheduled tasks
share|improve this answer
schtasks can be used from the command line to manipulate "Scheduled Tasks" – Ken Gentle Nov 18 '08 at 17:29
The at command also does this. – Blorgbeard Jan 29 '09 at 20:10
add comment
The AT command would do that but that's what the Scheduled Tasks gui is for. Enter "help at" in a cmd window for details.
share|improve this answer
add comment
Below is a batch file that will wait for 1 minute, check the day, and then perform an action. It uses PING.EXE, but requires no files that aren't included with Windows.
ECHO Waiting for 1 minute...
PING -n 60>nul
IF %DATE:~0,3%==Mon CALL SomeOtherFile.cmd
IF %DATE:~0,3%==Tue CALL SomeOtherFile.cmd
IF %DATE:~0,3%==Wed CALL SomeOtherFile.cmd
IF %DATE:~0,3%==Thu CALL WootSomeOtherFile.cmd
IF %DATE:~0,3%==Fri CALL SomeOtherFile.cmd
IF %DATE:~0,3%==Sat ECHO Saturday...nothing to do.
IF %DATE:~0,3%==Sun ECHO Sunday...nothing to do.
It could be improved upon in many ways, but it might get you started.
share|improve this answer
add comment
I did it by writing a little C# app that just wakes up to launch periodic tasks -- don't know if it is doable from a batch file without downloading extensions to support a sleep command. (For my purposes the Windows scheduler didn't work because the apps launched had no graphics context available.)
share|improve this answer
why is a graphics context needed to launch from the scheduler? I don't understand why that makes any difference. – Tim May 8 '09 at 17:49
In my case I needed to launch an application to run automated tests which did lots of graphics (medical imaging). So they wouldn't run without a graphics context. – Jeff Kotula May 8 '09 at 20:48
add comment
You could also do this>
@echo off
set a=60
set /a a-1
if a GTR 1 (
echo %a% minutes remaining...
timeout /t 60 /nobreak >nul
goto a
) else if a LSS 1 goto finished
Or something like that.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33625 | Take the 2-minute tour ×
Hi guys i got the following syntax error at the following line when i run my program in jython:
except Exception as detail:
SyntaxError: mismatched input 'as' expecting COLON
but on python its ok? What's wrong? I'm trying to use the stanford pos tagger api (java) in my python program.are there other ways?
share|improve this question
+1 for finally marking the right answer as "answered" – Blauohr Jun 12 '10 at 11:26
add comment
1 Answer
up vote 6 down vote accepted
I guess it isn't supported by Jython yet, or you don't use the latest version. Try this:
except Exception, detail:
share|improve this answer
thanks for the prompt reply, it works! btw if i switch to jython from python, how do i use the custom libraries like nltk i've installed on python to work on jython... – goh Jun 11 '10 at 7:41
@goh: Consider opening a separate question for that. – Ignacio Vazquez-Abrams Jun 11 '10 at 8:20
@goh: ... and maybe mark this question as answered. – zovision Jun 11 '10 at 8:46
@zovision, thanks for reminder. Slipped my mind. – goh Jun 11 '10 at 9:27
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33626 | Take the 2-minute tour ×
This is one of my first try with Map Reduce on AWS in its Management Console. Hi have uploaded on AWS S3 my runnable jar developed on Hadoop 0.18, and it works on my local machine. As described on documentation, I have passed the S3 paths for input and output as argument of the jar: all right, but the problem is the third argument that is another path (as string) to a file that I need to load while the job is in execution. That file resides on S3 bucket too, but it seems that my jar doesn't recognize the path and I got a FileNotFound Exception while it tries to load it. That is strange because this is a path exactly like the other two...
Anyone have any idea?
Thank you
share|improve this question
add comment
2 Answers
This is a problem with AWS, please check Lesson 2 at http://meghsoft.com/blog/. See if you can use FileSystem.get(uri, conf) to obtain a file system supporting your path.
Hope this helps.
share|improve this answer
Sonal, thank you for your suggestion. I think this should be the right way. Moreover, I found that a FileInputStream instead a string path can be enough for my needs: I tried with classifierPath = args[2]; FileSystem inputFS = FileSystem.get(URI.create(classifierPath),conf); ObjectInputStream objectClassifierStream = new ObjectInputStream(inputFS.open(new Path(classifierPath))); loadedClassifier = CRFClassifier.getClassifier(objectClassifierStream); but I'm still having problem when I load objectClassifierStream: exception "Bad Header". Maybe I made a mistake in my code? Thank you. – zero51 Jun 15 '10 at 5:53
add comment
up vote 0 down vote accepted
thank you for your suggestion. In the end the solution was using the DistributedCache.
Loading the file before to run the job I can access inside the Map Class everithing I need by overriding the confiure method and taking the file from the distributed cache (already loaded with the file).
Thank you,
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33627 | Take the 2-minute tour ×
I want to write a master-slave application in Erlang. I am thinking at the following things I need from the architecture:
• the slaves shouldn't die when the master dies, but rather try to reconnect to it while the master is down
• the master should automatically start the remote nodes if they don't connect automatically or they are down (probably the supervisor behaviour in OTP)
Is there a OTP oriented behaviour to do this? I know I can start remote nodes with slave:start_link() and I can monitor nodes with erlang:monitor(), but I don't know how this can be incorporated in a gen_server behaviour.
share|improve this question
The functions erlang:monitor_node/2 and erlang:monitor_node/3 are also available. – Roberto Aloi Jul 2 '10 at 17:07
Did you see the distributed applications section? erlang.org/doc/design_principles/distributed_applications.html – Zed Jul 3 '10 at 9:21
We need some clear terminology here. Do you want to distribute your application over multiple erlang VMs (that is run multiple node()'s) or do you want to build a fault tolerant tree of processes? It is not entirely clear from your question. – I GIVE CRAP ANSWERS Dec 6 '10 at 15:07
add comment
2 Answers
I agree with the comments about using erlang:monitor_node and the use of distributed applications.
You cannot just use the slave module to accomplish that, it clearly states "All slave nodes which are started by a master will terminate automatically when the master terminates".
There is currently no OTP behaviour to do it either. Supervision trees are hierarchical ; it seems like you are looking for something where there is a hierarchy in terms of application logic, but spawning is done an a peer-to-peer basis (or an individual basis, depending upon your point of view).
If you were to use multiple Erlang VMs then you should carefully consider how many you run, as a large number of them may cause performance issues due to the OS swapping OS processes in and out. A rule of thumb for best performance is to aim for having no more than one OS process (i.e. one Erlang VM) per CPU core.
share|improve this answer
add comment
If you're interested in studying other implementations, Basho's riak_core framework has a pretty good take on decentralized distributed applications.
riak_core_node_watcher.erl has most of the interesting node observation code in it.
Search and you'll find there are quite a few talks and presentations about the framework.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33628 | Take the 2-minute tour ×
Before I begin, my reason for not using OAuth is I believe it is not really something we should be using on this project, we're targeting a platform that will be packaged and resold to companies, which connect to their own set of uses that we really don't want to have accounts that we are not %100 in control of, we don't want it to be a shared-login with other services, and we don't want to force people into getting a google/yahoo/openID/aol/facebook/blogger/wordpress/whatever account.
Now then, What I would like is the best way to let users re-set a password.
I hate the concept of secret-questions: What school did you goto? Well, lets check your facebook page. What was your first-grade teacher? Lets just ask them casually.
I hate using one-time-passwords via email: Since when is email secure? Your boss reads it. Your sending out spam emails to me every day. It went into your junk-bin. It's not sent encrypted.
I don't want to use a password to reset a password either. This just doesn't make sense.
I'm really out of ideas here for the best way to do this, so I figure I would ask the community.
share|improve this question
add comment
5 Answers
up vote 9 down vote accepted
Your problem is that you need to outsource trust. If the user forgets their password, you no longer have a direct way to trust them, so you have to use an outside source to reestablish your relationship.
If you think email is insecure (which it is, actually), you could try telephone. Give them a call with the temporary password. Or a fax. Or snail mail, or an SMS, etc.
This is as secure as the phone lines/postal carriers over which the reset travels, and in most areas, telephone intercepts or tampering with the mail is strictly punished by the law.
If that's no good, consider issuing users an OTP token, or smartcard, or something.
share|improve this answer
By telephone is also a reasonable method - you need to collect the phone number from them when you first register the user or have a trusted way to look it up when you need it. – Von Aug 20 '10 at 15:18
It may be worthwhile to note that the organization I'm first to deploy at maintains about 7000 user accounts, which is probably a slightly higher than median average for other organizations. – Incognito Aug 20 '10 at 15:21
@user257493: If they have that many users, they have support staff. If the users are within the company, a face-to-face ID check might be a viable option. – Borealid Aug 20 '10 at 15:23
The company will have between 5 and 20 people, all of which are doing the lines of business already without time to play help desk please reset my password. Nor are they trained to deal with a Mallory calling pretending she's Alice. – Incognito Aug 20 '10 at 15:28
add comment
Barring being able to vet the person in person, I think you've listed all the reasonable options I've seen. In my opinion the one-time-password via email is the superior option as people tend to at least want to keep their email private. I personally hate secret questions - too big of a chance of the answers being public (see Sarah Palin email incident). If you are going to do secret questions, at least let the user choose their own questions.
share|improve this answer
Here's my other problem with secret questions. I always input something else (like my fist against the keyboard a few times) because I don't like the idea of a simple back door into my account – Incognito Aug 20 '10 at 15:14
I always generate purely random answers for secret questions (the same way I generate pass phrases actually). – Von Aug 20 '10 at 15:18
The point of secret questions seems to be missed by the people implementing them. The questions need to be more personal and are not public knowledge. E.g. Who was your first crush? What is your shoe size? What was your first car? – It Grunt Aug 20 '10 at 15:21
I have a big problem with questions that can so easily be socially engineered from me, I really don't want to act like a psycotic shut-in afraid to tell people my first girlfriend's name was Michelle because they could use that knowledge to break into my accounts. – Incognito Aug 20 '10 at 15:24
@It Grunt: If you give the answer to one site, it's not a secret anymore. Benjamin Franklin said "the only way three people can keep a secret is if two of them are dead". These questions are a flawed idea. – Borealid Aug 20 '10 at 15:25
show 1 more comment
I think this requires a difficult implementation but sending new password to user's mobile phone as a text message may be an alternative solution. Mobile phones are much more secure than personal inbox.
Then, users are asked to enter their mobile phone numbers. Users that doesn't want that functionality are provided new passwords by email.
share|improve this answer
add comment
Make users select a secret image (or images). Or make user upload their own image.
This works better than secret questions. Secret questions have two common problems:
1. user gives an answer that can be easily obtained by others.
2. user knows about first problem and instead of a real answer gives a random answer, later on forgetting themselves what it was.
By making user to select secret image(s) or better yet upload their own images. It'll be easier for user to recall it later when recovering the password, since it's easier to make visual associations.
When recovering the password present user with several choices to pick the right image.
share|improve this answer
That's a massive inconvenience and prone to some of the same problems as secret questions. – Incognito Aug 28 '10 at 15:41
add comment
So you actually want the user to prove that he is who he claims he is, without revealing information about himself (assuming you can get ANY information with social hacking)
There are 3 ways for authentication: Something you are (biometrics), Something you have (dongle for example) and Something you know (password,response...). 2 or 3-way authentication is much more secure than 1-way.
Password reset/recovery, by definition reduces the security of the authentication procedure, because its now not A, but (A or B). (A= password, B=recover-password)
Therefore, even if your authentication procedure is 1-way (password), your recovery processes should be a 2-way authentication.
Let's see what are your options for the password recovery process:
1. Something you are (SysAdmin that recognize you - usually not good for 5000 workers organization, Voice-print - too expensive to implement, ...)
2. Something you have (e-mail account, phone number, ...)
3. Something you know (personal details)
Notice that corporate-ID tag with picture is a 2-way authentication (both something you are and something you have).
I think the best procedure is for the employee to physically go to the IT department, show his picture ID, and ask for a password reset.
If this is infeasible (too far - a remote branch for example), try to use a deligator who is recognized and can be trusted over the phone, so the employee will have to show the ID-tag to a local deligator.
If you can't use the 'Something you are' - you're left with something you have (e-mail, phone-number,your own PC) and something you know (personal details...). You can't escape it.
share|improve this answer
There is no social hacking, the users are giving me information about where they live, travel documents, and other things just to use the system. – Incognito Aug 29 '10 at 16:04
"What was your first-grade teacher? Lets just ask them casually" - This is social hacking. – Lior Kogan Aug 30 '10 at 7:50
Ah I mis-understood. I thought you meant how facebook draws connections between products you might like based on other things, or runs face-recognition software. I do have access to a lot of sensitive data that ID thieves would love, but I'm unsure if I want to use that as verification/secrets. – Incognito Aug 30 '10 at 14:39
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33629 | Take the 2-minute tour ×
I want to extract 'James\, Brown' from the string below but I don't always know what the name will be. The comma is causing me some difficuly so what would you suggest to extract James\, Brown?
OU=James\, Brown,OU=Test,DC=Internal,DC=Net
share|improve this question
Too bad you can't get the API you're using to give you the output in a structured format. Parsing is tiresome. – Jay Bazuzi Dec 10 '08 at 16:08
add comment
9 Answers
Assuming you're running in Windows, use PInvoke with DsUnquoteRdnValueW. For code, see my answer to another question: http://stackoverflow.com/a/11091804/628981
share|improve this answer
add comment
Replace \, with your own preferred magic string (perhaps & #44;), split on remaining commas or search til the first comma, then replace your magic string with a single comma.
i.e. Something like:
string originalStr = @"OU=James\, Brown,OU=Test,DC=Internal,DC=Net";
string replacedStr = originalStr.Replace("\,", ",");
string name = replacedStr.Substring(0, replacedStr.IndexOf(","));
Console.WriteLine(name.Replace(",", ","));
share|improve this answer
add comment
That looks suspiciously like an LDAP or Active Directory distinguished name formatted according to RFC 2253/4514.
Unless you're working with well known names and/or are okay with a fragile hackaround (like the regex solutions) - then you should start by reading the spec.
If you, like me, generally hate implementing code according to RFCs - then hope this guy did a better job following the spec than you would. At least he claims to be 2253 compliant.
share|improve this answer
add comment
I'd start off with a regex to split up the groups:
Regex rx = new Regex(@"(?<!\\),");
String test = "OU=James\\, Brown,OU=Test,DC=Internal,DC=Net";
String[] segments = rx.Split(test);
But from there I would split up the parameters in the array by splitting them up manually, so that you don't have to use a regex that depends on more than the separator character used. Since this looks like an LDAP query, it might not matter if you always look at params[0], but there is a chance that the name might be set as "CN=". You can cover both cases by just reading the query like this:
String name = segments[0].Split('=', 2)[1];
share|improve this answer
add comment
You can use a regex:
Match m = Regex.Match(input, "^OU=(.*?),OU=.*$");
share|improve this answer
add comment
If the slash is always there, I would look at potentially using RegEx to do the match, you can use a match group for the last and first names.
That RegEx will match names that include characters only, you will need to refine it a bit for better matching for the non-standard names. Here is a RegEx tester to help you along the way if you go this route.
share|improve this answer
add comment
If the format is always the same:
string line = GetStringFromWherever();
int start = line.IndexOf("=") + 1;//+1 to get start of name
int end = line.IndexOf("OU=",start) -1; //-1 to remove comma
string name = line.Substring(start, end - start);
Forgive if syntax is not quite right - from memory. Obviously this is not very robust and fails if the format ever changes.
share|improve this answer
Actually, the second parameter of SubString is length, not endIndex. In your example it SHOULD be name = line.SubString(start, end - start). I've always hated that about Substring, which is the reason why I've created extension methods that DO allow startIndex and endIndex. – BFree Dec 10 '08 at 15:41
xan - I edited to correct syntax, since I am in front of a machine with Snippetcompiler installed. :) – ZombieSheep Dec 10 '08 at 15:45
add comment
A regex is likely your best approach
static string ParseName(string arg) {
var regex = new Regex(@"^OU=([a-zA-Z\\]+\,\s+[a-zA-Z\\]+)\,.*$");
var match = regex.Match(arg);
return match.Groups[1].Value;
share|improve this answer
A good approach, but one of which I have an irrational fear. :) – ZombieSheep Dec 10 '08 at 15:46
Overcome your fear :) – samjudson Dec 10 '08 at 15:48
But in order to do that, I must admit that my fear is wrong, and as a Yorkshireman, I am never wrong. ;-) – ZombieSheep Dec 10 '08 at 15:49
You're assuming every name has a comma in it which might be wrong (and probably is). – VVS Dec 10 '08 at 16:20
@David, questioner didn't mention it one way or the other so all I can go on is what they put in the question. I could also wonder if @'s are allowed in the name. Or perhaps 3 name vs. 2. But once again unless the asker puts it in their question assumptions are necessary. – JaredPar Dec 10 '08 at 16:23
show 2 more comments
A quite brittle way to do this might be...
string[] splitUp = name.Split("=".ToCharArray(),3);
string namePart = splitUp[1].Replace(",OU","");
I wouldn't necessarily advocate this method, but I've just come back from a departmental Christmas lyunch and my brain is not fully engaged yet.
share|improve this answer
Hi, my name is "Foo,OUBar" but you can call me "FooBar" ;-) – VVS Dec 10 '08 at 16:26
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33630 | Take the 2-minute tour ×
I created a custom post type and activated page-attributes in the options. It works just fine (It allowed me to set parent and order), however the template drop down just doesn't appear? It works fine with regular pages.
share|improve this question
Isn't template drop down just for pages? – Steven Sep 11 '10 at 16:26
add comment
1 Answer
Custom Post Types currently don't support the template features. Only 'pages' do.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33631 | Take the 2-minute tour ×
I'm currently using matplotlib to plot a measurement against 2 or 3 other measurements (sometimes categorical) on the x-axis. Currently, I am grouping the data on the x-axis into tuples and sorting them before plotting... the result looks something like the left image below. What I would like to do is to plot the data with multiple x-axes as you see in the right image. The grouping of the "treatment" x-axis labels would be icing on the cake.
alt text
share|improve this question
add comment
2 Answers
up vote 14 down vote accepted
First off, cool question! It's definitely possible with matplotlib >= 1.0.0. (The new spines functionality allows it)
It requires a fair bit of voodoo, though... My example is far from perfect, but hopefully it makes some sense:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
def main():
nx = 10
x = np.linspace(0, 2*np.pi, 10)
y = 2 * np.sin(x)
groups = [('GroupA', (x[0], x[nx//3])),
('GroupB', (x[-2*nx//3], x[2*nx//3])),
('GroupC', (x[-nx//3], x[-1]))]
fig = plt.figure()
ax = fig.add_subplot(111)
# Give ourselves a bit more room at the bottom
ax.plot(x,y, 'k^')
# Drop the bottom spine by 40 pts
ax.spines['bottom'].set_position(('outward', 40))
# Make a second bottom spine in the position of the original bottom spine
# Annotate the groups
for name, xspan in groups:
annotate_group(name, xspan)
plt.title('Experimental Data')
def annotate_group(name, xspan, ax=None):
"""Annotates a span of the x-axis"""
def annotate(ax, name, left, right, y, pad):
arrow = ax.annotate(name,
xy=(left, y), xycoords='data',
xytext=(right, y-pad), textcoords='data',
annotation_clip=False, verticalalignment='top',
horizontalalignment='center', linespacing=2.0,
arrowprops=dict(arrowstyle='-', shrinkA=0, shrinkB=0,
return arrow
if ax is None:
ax = plt.gca()
ymin = ax.get_ylim()[0]
ypad = 0.01 * np.ptp(ax.get_ylim())
xcenter = np.mean(xspan)
left_arrow = annotate(ax, name, xspan[0], xcenter, ymin, ypad)
right_arrow = annotate(ax, name, xspan[1], xcenter, ymin, ypad)
return left_arrow, right_arrow
def make_second_bottom_spine(ax=None, label=None, offset=0, labeloffset=20):
"""Makes a second bottom spine"""
if ax is None:
ax = plt.gca()
second_bottom = mpl.spines.Spine(ax, 'bottom', ax.spines['bottom']._path)
second_bottom.set_position(('outward', offset))
ax.spines['second_bottom'] = second_bottom
if label is not None:
# Make a new xlabel
xy=(0.5, 0), xycoords='axes fraction',
xytext=(0, -labeloffset), textcoords='offset points',
verticalalignment='top', horizontalalignment='center')
if __name__ == '__main__':
Two bottom spines in a matplotlib plot
share|improve this answer
I'm unfamiliar with this voodoo - care to show how to generalize this to more categorical axes? I thought creating a third bottom spine with some offset would make it visible, but that's not working for me - it's still stacked right on top of the second. (I can open a new question if that's perferable) – Thomas Feb 9 '11 at 18:28
nm I've got it now - if you like though I would still love to see your (cleaner) implementation of it. – Thomas Feb 9 '11 at 18:50
add comment
Joe's example is good. I'll throw mine in too. I was working on it a few hours ago, but then had to run off to a meeting. It steals from here.
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
## the following two functions override the default behavior or twiny()
def make_patch_spines_invisible(ax):
for sp in ax.spines.itervalues():
def make_spine_invisible(ax, direction):
if direction in ["right", "left"]:
elif direction in ["top", "bottom"]:
raise ValueError("Unknown Direction : %s" % (direction,))
data = (('A',0.01),('A',0.02),('B',0.10),('B',0.20)) # fake data
fig = plt.figure(1)
sb = fig.add_subplot(111)
sb.plot([i[1] for i in data],"*",markersize=10)
plt.subplots_adjust(bottom=0.17) # make room on bottom
par2 = sb.twiny() # create a second axes
par2.spines["bottom"].set_position(("axes", -.1)) # move it down
## override the default behavior for a twiny axis
make_spine_invisible(par2, "bottom")
par2.plot([i[1] for i in data],"*",markersize=10) #redraw to put twiny on same scale
par2.xaxis.set_ticklabels([i[0] for i in data])
alt text
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33632 | Take the 2-minute tour ×
Simple problem in Delphi. I've created a console application and I need to change the height of the console window to 80 lines, if it's less than 80 lines. This need to be done from code and is actually conditional within the code. (I.e. when an error occurs, it increases the size of the console so the whole (huge) error report is visible.)
Keep in mind that this is a console application! When it starts, it uses the default console, which I need to alter!
share|improve this question
add comment
1 Answer
up vote 6 down vote accepted
When calling SetConsoleWindowInfo() the values for Left and Top that are passed to the console need to at least be 1, not 0. Problem solved.
I now do this:
Rect: TSmallRect;
Coord: TCoord;
Rect.Left := 1;
Rect.Top := 1;
Rect.Right := 80;
Rect.Bottom := 60;
Coord.X := Rect.Right + 1 - Rect.Left;
Coord.y := Rect.Bottom + 1 - Rect.Top;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), Coord);
SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), True, Rect);
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33633 | Take the 2-minute tour ×
This is part of cachegrind output. This part of code has been executed for 1224 times. elmg1 is an array of unsigned long of size 16 x 20. My machine L1 cache size is 32KB, 64B cache line size and 8-way set associative.
1. for (i = 0; i < 20; i++) 78,336 2,448 2 50,184 0 0 1,224 0 0
2. {
3. telm01 = elmg1[i]; 146,880 0 0 73,440 0 0 24,480 0 0
4. telm31 = (telm01 << 3) ^ val1; 97,920 0 0 48,960 0 0 24,480 0 0
5. telm21 = (telm01 << 2) ^ (val1 >> 1); 146,880 1,224 1 48,960 0 0 24,480 0 0
6. telm11 = (telm01 << 1) ^ (val1 >> 2); 146,880 0 0 48,960 0 0 24,480 0 0
7. }
A. The reason I have put it here, is that in the 3rd line inside the for loop, I see a number of I1 misses (one L2 miss as well). It is somewhat confusing and I could not guess the reason why?
B. I am trying to optimize (time) a portion of code. The above is just a small snippet. I think in my program memory access a costing me a lot. Like in the above example elmg1 is an array of 16 x 20 size of unsigned longs. When I try to use it in code, there are always some misses, and in my program these variables occur a lot. Any suggestions?
C. I need to allocate and (sometimes initialize) these unsigned longs. Can you suggest which one should I prefer, calloc or array declaration and then explicit initialization. By the way will there be any difference in the way cache handles them?
share|improve this question
add comment
1 Answer
up vote 3 down vote accepted
Have you tried to unroll the loop?
1. I wouldn't worry about L1 misses right now. Also one L2 miss out of 1224 times is ok, the cpu has to load the values into the cache at some point.
2. What percentage of L2 misses does this code cost compared to the rest of the program?
3. Use calloc(), if the array size is always the same and you use constants for the size, then the compiler can optimize the zero'ing of the array. Also the only thing that would effect the cache lines usages is alignment, not how it was initizliated.
edit: The number where hard to read that way and read them wrong the first time.
lets make sure I am reading the numbers right for line 5:
Ir 146,880
I1mr 1,224
ILmr 1
Dr 48,960
D1mr 0
DLmr 0
Dw 24,480
D1mw 0
DLmw 0
The L1 Cache is split into two 32KByte caches one for code I1 and one of data D1. IL & DL are the L2 or L3 cache which is shared by both data and instructions.
The large number of I1mr is instruction misses not data misses, this means that the loop code is being ejected from the I1 instruction cache.
I1 misses at line 1 & 5 total 3672 which is 3 times 1224, so each time the loop is run you get 3 I1 cache misses with 64Byte cache lines that means you loop code size is between 128-192 bytes to cover 3 cache lines. So those I1 misses at line 5 is because that is where the loop code crosses the last cache line.
I would recommend using KCachegrind for viewing the results from cachegrind
Edit: More about cache lines.
That loop code doesn't look like it is being call 1224 times by itself, so that means there is more code that is pushing this code out of the I1 cache.
Your 32Kbyte I1 cache is divided into 512 cache lines (64bytes each). The "8-way set associative" part means that each memory address is mapped to only 8 out of those 512 cache lines. If the whole program you are profile was one continuous block of 32Kbytes of memory, then it would all fit into the I1 cache and none would be ejected. That is mostlikely not the case and there will be more then 8 64byte blocks of code contenting for the same 8 cache lines. Lets say that your whole program has 1Mbyte of code (this includes libraries), then each group of 8 cache lines will have about 32 (1Mbyte/32Kbyte) pieces of code contenting for those same 8 cache lines.
Read this lwn.net article for all the gory details about CPU caches
The compiler can't always detect which functions of the program will be hotspots (called many many times) and which will be codespots (i.e. error handler code, which almost never runs). GCC has function attributes hot/cold which will allow you to mark functions as hot/cold, this will allow the compiler to group the hot functions together in one block of memory to get better cache usage (i.e. cold code will not be pushing hotcode out of the caches).
Anyways those I1 misses are really not worth the time to worry about.
share|improve this answer
A. That's ok, but why there are cache misses at line 5, whereas there is less at line 3, 4. Do I need to specify the alignment thing myself, I read that malloc by default provides 8/16 byte alignment. – anup Nov 1 '10 at 8:57
yes, malloc should provides atleast 8byte alignment, but that is not the same as 64Byte cache alignment. Cache alignment is important only when you have an array of objects that are 64bytes each. If the array is not allocated cache aligned then accessing any one item in the array might cause two cache misses instead of one. But cache alignment isn't an issue in this case. – Neopallium Nov 1 '10 at 10:34
Thanks for your reply. But, one thing that I did not understand what these has to do with 3 cache lines? There should be more number of cache lines. – anup Nov 1 '10 at 10:52
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33634 | Take the 2-minute tour ×
I want to create function which I will call in next context:
update mytab set processed = myfunc(mytab.data) where processed = 0
In myfunc I want to modify other tables. How should I implement this func?
share|improve this question
add comment
3 Answers
up vote 0 down vote accepted
You shouldn't.
The only way to do it would be to cheat by opening a connection which is not the context connection and use that connection to modify the data. This would need your assembly to have EXTERNAL ACCESS permission, and is rather complicated, which is a sign that you should not do it. Use a stored procedure instead.
share|improve this answer
add comment
Usually, you would use stored procedures on the database side that can be called inside queries. You could alter the other tables there and then return the correct value for the "processed" field.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33635 | Take the 2-minute tour ×
i want to send with an api some POST data with a large information data from server a to server b. Into server b, i receive only a part of posts data even if with htaccess i increased POST size and other.
php_value upload_max_filesize 400M
php_value post_max_size 400M
php_value max_execution_time 500
php_value max_input_time 400
php_value memory_limit 400M
There is a limit of posts data sent with a curl? or.. anybody know how to solve this problem?
share|improve this question
add comment
3 Answers
max_input_vars might also be hindering your curl post, if you're sending numerous parameters through. It has happened to me before - you can't change the setting on runtime, but only through php.ini.
share|improve this answer
add comment
Sending data via POST does not have a limit except for the one you have set in your server (php_value post_max_size 400M);
you might want to check your timeout value, try increasing your current value:
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
This might be closing your connection in server A before the entire request is sent to the server B.
share|improve this answer
add comment
The limit is 241 characters.
share|improve this answer
And any solution to could send my datas with curl? – oriceon Dec 3 '10 at 10:29
there might be one, but there is none of i know actually – Thariama Dec 3 '10 at 10:36
maybe the limit can be influenced using other setting parameters, but i suggest you have a look if you are really able to transfer 241 characters or less/more (you will need to create a testcase for this and play around with the data you submit) – Thariama Dec 3 '10 at 10:38
How can a post allow 241 characters only? even get support more than 2000 characters – ajreal Dec 3 '10 at 12:25
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33636 | Take the 2-minute tour ×
I want to create a custom template engine like velocity or freemarker which will be used in struts 2 based application. Why I don't want to use any of the available template engines is because, I want to keep the HMTL fixed and editable by dreamweaver means no struts tags or JSTL. The values will be injected with Xpath or simple string replacement of values of existing HTML tags. I require:
plain HTML + some configuration (properties/xml) + data =>
HTML populated with data + some dynamically generated javascripts
share|improve this question
What is your question? – Steven Benitez Dec 7 '10 at 13:34
How do I write a template engine like freemarker? How to integrate my template engine with struts2? – samarjit samanta Dec 8 '10 at 1:17
add comment
1 Answer
up vote 2 down vote accepted
1) Define a package with the name of your result type and the class that will be called when an action returns that result type.
<result-type name="myResultType" class="com.awesome.MyResult"/>
.... actions and other things...
2) Implement the Struts 2 result type class:
package com.awesome;
public class MyResult extends StrutsResultSupport{
//1) read the the target file
//2) process/transform the target file
//3) write out the transformed file as the result
There is a good description of this in "Apache Struts 2 web application Development" by Dave Newton. I know the above class isn't implemented but I bet you can find what you need from here.
share|improve this answer
Thanks, I am using that now. For other, who wish to use this I can give you some pointers. Open up struts default look for interceptors implementing class FreemarkerResult.java and XSLTResult.java are two classes I read through and its fairly simple as to what they do. I would also recomment going through http://www.oracle.com/technetwork/java/filters-137243.html about java Filters especially if you want to modify the response. HttpResponseWrapper is required. One more thing exists PreResultListener, which can manipulate invocation object just before result is going to be evaluated. – samarjit samanta Dec 21 '10 at 8:16
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33637 | Take the 2-minute tour ×
All throughout the apple ios dev programming guide I get these weird symbols. Anyone know what they are? I'm just curious. They look like tiny little boxes with 4 numbers inside.
share|improve this question
I see nothing but quotes. – bmargulies Jan 8 '11 at 2:51
add comment
closed as too localized by Flexo, Bill the Lizard May 17 '12 at 15:04
2 Answers
It is typically a multibyte character which is not understood. The numbers read the unicode codepoint in hex. It may mean the encoding of the page is set to the wrong value, or that your browser can't handle it.
Try and see if another browser shows it differently.
share|improve this answer
add comment
It's a character that is not present in the font that is used to show the text. The digits in the little box is the character code.
They probably used typographic quoation marks (for example ˮ) instead of the regular quotation marks (").
share|improve this answer
add comment
|
global_01_local_0_shard_00000017_processed.jsonl/33638 | Take the 2-minute tour ×
UIImageView *campFireView=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,480)];
//UIImageView *campFireView =[[UIImageView alloc] initWithFrame:campFireView];
// load all the frames of our animation
campFireView.animationImages = [NSArray arrayWithObject:[UIImage imageNamed:@"Img_0.jpg"],
// all frames will execute in 1.75 seconds
campFireView.animationDuration = 1.75;
// repeat the annimation forever
campFireView.animationRepeatCount = 1000.0;
// start animating
[campFireView startAnimating];
// add the animation view to the main window
[self.view addSubview:campFireView];
[campFireView release];
the problem here is i want to set only one image so i have used arraywithobject but when i run this code it is giving me error that too many paramters for arrayWithObject. What is problem.Can anybody help me in solving this problem
share|improve this question
add comment
1 Answer
up vote 1 down vote accepted
arrayWithObject: takes only one parameter, so just remove the ,nil.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33639 | Take the 2-minute tour ×
Does anyone know why java.lang.Number does not implement Comparable? This means that you cannot sort Numbers with Collections.sort which seems to me a little strange.
Post discussion update:
Thanks for all the helpful responses. I ended up doing some more research about this topic.
The simplest explanation for why java.lang.Number does not implement Comparable is rooted in mutability concerns.
For a bit of review, java.lang.Number is the abstract super-type of AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, Float, Integer, Long and Short. On that list, AtomicInteger and AtomicLong to do not implement Comparable.
Digging around, I discovered that it is not a good practice to implement Comparable on mutable types because the objects can change during or after comparison rendering the result of the comparison useless. Both AtomicLong and AtomicInteger are mutable. The API designers had the forethought to not have Number implement Comparable because it would have constrained implementation of future subtypes. Indeed, AtomicLong and AtomicInteger were added in Java 1.5 long after java.lang.Number was initially implemented.
Apart from mutability, there are probably other considerations here too. A compareTo implementation in Number would have to promote all numeric values to BigDecimal because it is capable of accommodating all the Number sub-types. The implication of that promotion in terms of mathematics and performance is a bit unclear to me, but my intuition finds that solution kludgy.
share|improve this question
Just to mention it: Comparing two arbitrary numbers is a possibly endless operation. See stackoverflow.com/questions/12561485/… – SpaceTrucker Oct 24 '12 at 9:51
add comment
12 Answers
up vote 32 down vote accepted
It's worth mentioning that the following expression:
new Long(10).equals(new Integer(10))
is always false, which tends to trip everyone up at some point or another. So not only can you not compare arbitrary Numbers but you can't even determine if they're equal or not.
Also, with the real primitive types (float, double), determining if two values are equal is tricky and has to be done within an acceptable margin of error. Try code like:
double d1 = 1.0d;
double d2 = 0.0d;
d2 += 0.1d;
System.out.println(d2 - d1);
and you'll be left with some small difference.
So back to the issue of making Number Comparable. How would you implement it? Using something like doubleValue() wouldn't do it reliably. Remember the Number subtypes are:
• Byte;
• Short;
• Integer;
• Long;
• AtomicInteger;
• AtomicLong;
• Float;
• Double;
• BigInteger; and
• BigDecimal.
Could you code a reliable compareTo() method that doesn't devolve into a series of if instanceof statements? Number instances only have six methods available to them:
• byteValue();
• shortValue();
• intValue();
• longValue();
• floatValue(); and
• doubleValue().
So I guess Sun made the (reasonable) decision that Numbers were only Comparable to instances of themselves.
share|improve this answer
Thxs Cletus. IMHO there ought to be an intermediate numeric type like RealNumber (see above) encapsulating Float, Double, Long, Integer, Short). Otherwise, you have a lack of polymorphism ultimately resulting in code duplication for those types along with their corresponding unboxed primitive types. – Julien Chastang Jan 26 '09 at 21:34
add comment
For the answer, see Java bugparade bug 4414323. You can also find a discussion from comp.lang.java.programmer
To quote from the Sun response to the bug report from 2001:
All "numbers" are not comparable; comparable assumes a total ordering of numbers is possible. This is not even true of floating-point numbers; NaN (not a number) is neither less than, greater than, nor equal to any floating-point value, even itself. {Float, Double}.compare impose a total ordering different from the ordering of the floating-point "<" and "=" operators. Additionally, as currently implemented, the subclasses of Number are only comparable to other instances of the same class. There are other cases, like complex numbers, where no standard total ordering exists, although one could be defined. In short, whether or not a subclass of Number is comparable should be left as a decision for that subclass.
Note to whoever downvoted this: I'm not saying this is the proper answer that should make everyone happy. I'm just saying that this is Sun's answer. They currently define the "brand" so their answer is final whether we like it or not. That's why I linked to the further discussion.
share|improve this answer
Eddie: Thanks for the link. I agree with the bug report that says that Java needs a RealNumber type that would be a super class of all the numeric types with a corresponding primitive numeric types (e.g. Float, etc.). Working with numbers in Java remains difficult without one. – Julien Chastang Jan 26 '09 at 17:51
Here is another (somewhat unsatisfying) explanation: forums.sun.com/thread.jspa?threadID=5306968 – Julien Chastang Jan 26 '09 at 18:27
Any chance we can edit this answer with a quote directly from the article? It's short enough that it should fit here with no problems. – Outlaw Programmer Jan 26 '09 at 22:08
Good idea. Done. – Eddie Jan 26 '09 at 22:25
add comment
in order to implement comparable on number, you would have to write code for every subclass pair. Its easier instead to just allow subclasses to implement comparable.
share|improve this answer
add comment
Very probably because it would be rather inefficient to compare numbers - the only representation into which every Number can fit to allow such comparison would be BigDecimal.
Instead, non-atomic subclasses of Number implements Comparable itself.
Atomic ones are mutable, so can't implement an atomic comparison.
share|improve this answer
That's not it. It's that not all numbers are comparable to each other in a total ordering. – Eddie Jan 26 '09 at 17:41
Go on - all subclases of Number in java.lang are rationals; there is a total ordering of reals; what is the issue? – Pete Kirkham Jan 26 '09 at 17:54
NaN cannot be ordered with any other value. It is not less than and it is not greater than and it is not equal to any value, including itself. – Eddie Jan 26 '09 at 18:07
The existing implementations of comparable work around that already (IIRC by placing NaN below -Infinity). That would be an argument against Double or Float implementing Comparable too, but they do. – Pete Kirkham Jan 26 '09 at 20:27
Yeah it's a bit crazy to not allow comparing of every number ever just because of NaN. How cool would it be to be able to compare every Number, and how weird is it to people who use other languages that this is even an issue? :) – Robert Grant Oct 24 '13 at 14:49
show 1 more comment
Write your own Comparator
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class NumberComparator implements Comparator {
public int compare(Number number1, Number number2) {
if (((Object) number2).getClass().equals(((Object) number1).getClass())) {
// both numbers are instances of the same type!
if (number1 instanceof Comparable) {
// and they implement the Comparable interface
return ((Comparable) number1).compareTo(number2);
// for all different Number types, let's check there double values
if (number1.doubleValue() < number2.doubleValue())
return -1;
if (number1.doubleValue() > number2.doubleValue())
return 1;
return 0;
* DEMO: How to compare apples and oranges.
public static void main(String[] args) {
ArrayList listToSort = new ArrayList();
listToSort.add(new Long(10));
listToSort.add(new Integer(1));
listToSort.add(new Short((short) 14));
listToSort.add(new Byte((byte) 10));
listToSort.add(new Long(9));
listToSort.add(new AtomicLong(2));
listToSort.add(new Double(9.5));
listToSort.add(new Double(9.0));
listToSort.add(new Double(8.5));
listToSort.add(new AtomicInteger(2));
listToSort.add(new Long(11));
listToSort.add(new Float(9));
listToSort.add(new BigDecimal(3));
listToSort.add(new BigInteger("12"));
listToSort.add(new Long(8));
System.out.println("unsorted: " + listToSort);
Collections.sort(listToSort, new NumberComparator());
System.out.println("sorted: " + listToSort);
System.out.print("Classes: ");
for (Number number : listToSort) {
System.out.print(number.getClass().getSimpleName() + ", ");
share|improve this answer
This will not work correctly with some floating point numbers. Internal representation of floats may cause two floats A and B to be unequal by a very small margin when they should be equal. – christophem Jul 13 '10 at 16:26
add comment
To try to solve the original problem (sort a list of numbers), an option is to declare the list of a generic type extending Number and implementing Comparable.
Something like:
<N extends Number & Comparable<N>> void processNumbers(List<N> numbers) {
System.out.println("Unsorted: " + numbers);
System.out.println(" Sorted: " + numbers);
// ...
void processIntegers() {
processNumbers(Arrays.asList(7, 2, 5));
void processDoubles() {
processNumbers(Arrays.asList(7.1, 2.4, 5.2));
share|improve this answer
add comment
there is no stardard comparison for Numbers of different types. However you can write your own Comparator and use it to create a TreeMap<Number, Object>, TreeSet<Number> or Collections.sort(List<Number>, Comparator) or Arrays.sort(Number[], Comparator);
share|improve this answer
add comment
You can use Transmorph to compare numbers using its NumberComparator class.
NumberComparator numberComparator = new NumberComparator();
assertTrue(numberComparator.compare(12, 24) < 0);
assertTrue(numberComparator.compare((byte) 12, (long) 24) < 0);
assertTrue(numberComparator.compare((byte) 12, 24.0) < 0);
assertTrue(numberComparator.compare(25.0, 24.0) > 0);
assertTrue(numberComparator.compare((double) 25.0, (float) 24.0) > 0);
assertTrue(numberComparator.compare(new BigDecimal(25.0), (float) 24.0) > 0);
share|improve this answer
add comment
why this would have been bad idea? :
abstract class ImutableNumber extends Number implements Comparable {
// do NOT implement compareTo method; allowed because class is abstract
class Integer extends ImutableNumber {
// implement compareTo here
class Long extends ImutableNumber {
// implement compareTo here
another option may have been to declare class Number implements Comparable, omit compareTo implementation, and implement it in some classes like Integer while throw UnsupportedException in others like AtomicInteger.
share|improve this answer
add comment
My guess is that by not implementing Comparable, it give more flexibility to implementing classes to implement it or not. All the common numbers (Integer, Long, Double, etc) do implement Comparable. You can still call Collections.sort as long as the elements themselves implement Comparable.
share|improve this answer
add comment
Looking at the class hierarchy. Wrapper classes like Long, Integer, etc, implement Comparable, i.e. an Integer is comparable to an integer, and a long is comparable to a long, but you can't mix them. At least with this generics paradigm. Which I guess answers your question 'why'.
share|improve this answer
add comment
byte (primitive) is a int (primitive). Primitives have only one value at a time.
Language design rules allows this.
int i = 255
// down cast primitive
(byte) i == -1
A Byte is not an Integer. Byte is a Number and an Integer is a Number. Number objects can have more than one value at the same time.
Integer iObject = new Integer(255);
System.out.println(iObject.intValue()); // 255
System.out.println(iObject.byteValue()); // -1
If a Byte is an Integer and an Integer is a Number, Which one value will you use in the compareTo(Number number1, Number number2) method?
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33640 | Take the 2-minute tour ×
I'm having a bit of confusion about how to render text in a pure AS3 project. There are classes like flash.text.StaticText but these are designer-only, you can't create them in code. I was half-expecting the Graphics class to have text-rendering options but alas, no.
Specifically I was going to add a label above each player's sprite with their name, health %, etc. So I expected to add a child text-element or draw text using Graphics in some way... it's read-only and should not support user-input, I just want to draw text on-screen.
share|improve this question
add comment
1 Answer
up vote 3 down vote accepted
You can use TextField class for this. Please check the reference. All fields and methods are self explanatory.
A possible example.
var myField:TextField = new TextField();
myField.text = "my text";
myField.x = 200;
myField.y = 200;
addChild(myField); // assuming you are in a container class
share|improve this answer
Don't forget selectable = false, it is commonly overlooked. – alxx Feb 4 '11 at 14:38
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33641 | Take the 2-minute tour ×
I'm not able to navigate down to the HashSets in my datastructure
I declared an array of Map[] and populated it with HashMap with K of Integer, and V of HashSet of String but was unable to add items to the HashSet.
I've trimmed the code down to illustrate ...
private Map[] myMaps = null;
myMaps = new Map[numRepeats];
myMaps[0] = new HashMap<Integer,HashSet<String>>();
myMaps[0].put(0, new HashSet<String>());
The popup in NetBeans shows I can get to java.util.Map with
but using the map.get(0) method I thought would return the HashSet
shows I've got to generic java.lang.object, not to the HashSet. Since I need to use the HashSet.add() method next this means I'm stuck. I would appreciate suggestions.
Thank you
share|improve this question
You have an array of maps of sets? You need some classes in there, or you're going to be tearing your hair out while debugging! – corsiKa Feb 20 '11 at 18:39
add comment
3 Answers
up vote 0 down vote accepted
When you define your map, you could define it with the full types involved, so:
private Map<Integer, HashSet<String>>[] myMaps = null;
Then, you wouldn't have to cast it back (assuming all your maps in myMaps will be of that type).
share|improve this answer
Thank you - assumption right, so I did this - it worked! (-: – bobox Feb 20 '11 at 19:08
add comment
Unfortunately, Java Generics make it rather tricky to have an array of a generic class. However, it is possible, and it will solve your problem in a typesafe way.
1st. declare your map like this
private Map<Integer,Set<String>>[] myMaps = null;
2nd. use a utility function to allocate
public static <T> T[] newMapArray( int size )
return (T[])java.lang.reflect.Array.newInstance(Map.class, size);
3rd. allocate myMaps like this
myMaps = newMapArray(numRepeats);
share|improve this answer
Thanks. umm, it's early days in Java for me and that looks a plateful. I'll study it and read around the suggestion. In the meantime I'm using Map<Integer, HashSet<String>>[] myMaps = null; (because I understand it).thanks – bobox Feb 20 '11 at 19:14
@bobox I certainly can understand why that looks intimidating. The nice thing about it is you can put it in some utility class and reuse it anywhere you like. Also, it hides the unchecked casts. – karoberts Feb 20 '11 at 19:53
add comment
You need to cast it to HashMap<Integer,HashSet<String>>.
share|improve this answer
Thanks, there's a consensus with Dante617 that this is the way fwd – bobox Feb 20 '11 at 19:09
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33642 | Take the 2-minute tour ×
Could someone please tell me if there is a way to capture extra joystick buttons? I mean buttons number 5,6,7,8 and so on.
I use this code to capture button down event :
procedure MMJOY1BUTTONDOWN (var LocMessage: TMMJoyStick); message MM_JOy1BUTTONDOWN;
But the problem is that it just captures the 4 standard buttons, not any extra buttons.
Thanks a lot
share|improve this question
add comment
1 Answer
up vote 5 down vote accepted
The Multimedia Joystick API does not support generating window messages for buttons 5+, you have to poll their status manually using joyGetPosEx(). Otherwise, you should use DirectInput from the DirectX API instead, as it replaces the older API.
Update: Alternatively, you can use the Raw Input API to receive event notifications directly from the joystick hardware. See CodeProject for more details:
Using the Raw Input API to Process Joystick Input
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33643 | Take the 2-minute tour ×
I've done a fair bit of research on this. I'm also pretty familiar with how to change just about every color in VS. I also found a neat site that has a theme maker on it. I don't think it's supported.
How do I make variables have their own color (strings, bools, ints, etc..) ?
I'm slowly getting used to it, but looking at oject.var.ToString(); and having it all show the same color is very frustrating/hard on my eyes. (example) In notepad++, I write my $variables in php and they show any color I want, separate from everything else. I really don't see why it can't be done. VS knows what everything is unless there's a syntax error or you haven't defined it yet/etc.. I know I can change the color on a broad scope that changes the colors on everything else too, so that doesn't help..
Thanks for any help!!
share|improve this question
ReSharper offers an extensive set of additional language constructs for which you can independently assign the color, including variables/fields/parameters/etc. – Kirk Woll Mar 12 '11 at 1:16
Really? That all shows up in the same color in your IDE? Have you tried playing with Options -> Environment -> Fonts and Colors? You won't get as fine of control as you could with ReSharper, but as extensions aren't supported in the Express version, this is about the best you can hope for. But what you've shown wouldn't be all the same color the way that I've set up VS. – Cody Gray Mar 12 '11 at 8:54
Yea, I played with just about every setting in Fonts and Colors. I fine tuned my own style and everything. It's just not natively supported. I can't afford to buy the full version of VS and ReSharper, so I'll have to make due with my current situation. What values have you changed to make objects/methods/variables have their own color? – PiZzL3 Mar 12 '11 at 16:16
Keywords, Identifiers, and all of the different "User Types". C#'s syntax highlighting is much better than what VS supports for C++. All of these schemes have modified the colors of methods and variable names. Interfaces, delegates, enums, value types, and more can all have their own unique colors. Yes, ReSharper may be great, but I'm cheap too so I haven't bought it either. – Cody Gray Mar 12 '11 at 18:27
@Cody Gray: I re-looked into those settings and variable, method, and object colors are all determined by the "Identifiers" color setting. This doesn't allow me to set them individually. I don't need to change Keywords or User Types/etc... As in my original example object.variable.method(); all shows the same color so matter what setting I change. This is incredibly difficult to read. Especially when things like this happen this.breakfast.today = reallyBigWaffleFactory.makeMeSomeWaffles(insertMoneyHere, waffleMix, addWater, milk, toppings).getPancakesInstead();. – PiZzL3 Mar 13 '11 at 4:26
add comment
2 Answers
up vote 0 down vote accepted
I am not 100% sure whether it has it, but ReSharper extends the color coding logic with new color classes. Other than that, it is a must have extension.
share|improve this answer
I made a similar comment, but I now realize the OP wants it for the express edition. I believe MS intentionally prevents plugins (such as ReSharper) in that edition. – Kirk Woll Mar 12 '11 at 1:20
I'm gonna download the demo to test it on express.. but man that looks really really really cool.... Is it worth that much cash? – PiZzL3 Mar 12 '11 at 1:46
Sadly it doesn't show up on the express version.. – PiZzL3 Mar 12 '11 at 4:14
Sadly indeed, the Express versions of Visual Studio do not support add-ins. You would need to get a full VS version, and yes, ReSharper is worth each penny paid. – Sebastian Zaklada Mar 12 '11 at 20:04
add comment
Visual Studio does not support this, unless you used some sort of plug-in or third party tool.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33644 | Take the 2-minute tour ×
Much has been written here about developing a workflow in R for statistical projects. The most popular workflow seems to be Josh Reich's LCFD model. With a main.R containing code:
so that a single source('main.R') runs the entire project.
Q: Is there a reason to prefer this workflow to one in which the line-by-line interpretive work done in load.R, clean.R, and do.R is replaced by functions which are called by main.R?
I can't find the link now, but I had read somewhere on SO that when programming in R one must get over their desire to write everything in terms of function calls---that R was MEANT to be written is this line-by-line interpretive form.
Q: Really? Why?
I've been frustrated with the LCFD approach and am going to probably write everything in terms of function calls. But before doing this, I'd like to hear from the good folks of SO as to whether this is a good idea or not.
EDIT: The project I'm working on right now is to (1) read in a set of financial data, (2) clean it (quite involved), (3) Estimate some quantity associated with the data using my estimator (4) Estimate that same quantity using traditional estimators (5) Report results. My programs should be written in such a way that it's a cinch to do the work (1) for different empirical data sets, (2) for simulation data, or (3) using different estimators. ALSO, it should follow literate programming and reproducible research guidelines so that it's simple for a newcomer to the code to run the program, understand what's going on, and how to tweak it.
share|improve this question
It might be helpful to explain what kind of work you are doing. For example, exploratory data analysis lends its self to a much different workflow than repetitive munging of daily data sets. – Sharpie Mar 20 '11 at 1:25
@Sharpie: I added some background on my current project in my edit. It's heavy on the munging and light on the exploration. – brianjd Mar 20 '11 at 21:30
Is there an example somewhere of how this workflow would work with functions? Most of those files are going to have multiple output variables. Do you just return a single big list? Might that not get fairly inefficient with lots of big, complex variables? – naught101 Apr 3 '13 at 1:36
add comment
6 Answers
up vote 12 down vote accepted
I don't think there is a single answer. The best thing to do is keep the relative merits in mind and then pick an approach for that situation.
1) functions. The advantage of not using functions is that all your variables are left in the workspace and you can examine them at the end. That may help you figure out what is going on if you have problems.
On the other hand, the advantage of well designed functions is that you can unit test them. That is you can test them apart from the rest of the code making them easier to test. Also when you use a function, modulo certain lower level constructs, you know that the results of one function won't affect the others unless they are passed out and this may limit the damage that one function's erroneous processing can do to another's. You can use the debug facility in R to debug your functions and being able to single step through them is an advantage.
2) LCFD. Regarding whether you should use a decomposition of load/clean/func/do regardless of whether its done via source or functions is a second question. The problem with this decomposition regardless of whether its done via source or functions is that you need to run one just to be able to test out the next so you can't really test them independently. From that viewpoint its not the ideal structure.
On the other hand, it does have the advantage that you may be able to replace the load step independently of the other steps if you want to try it on different data and can replace the other steps independently of the load and clean steps if you want to try different processing.
3) No. of Files There may be a third question implicit in what you are asking whether everything should be in one or multiple source files. The advantage of putting things in different source files is that you don't have to look at irrelevant items. In particular if you have routines that are not being used or not relevant to the current function you are looking at they won't interrupt the flow since you can arrange that they are in other files.
On the other hand, there may be an advantage in putting everything in one file from the viewpoint of (a) deployment, i.e. you can just send someone that single file, and (b) editing convenience as you can put the entire program in a single editor session which, for example, facilitates searching since you can search the entire program using the editor's functions as you don't have to determine which file a routine is in. Also successive undo commands will allow you to move backward across all units of your program and a single save will save the current state of all modules since there is only one. (c) speed, i.e. if you are working over a slow network it may be faster to keep a single file in your local machine and then just write it out occasionally rather than having to go back and forth to the slow remote.
Note: One other thing to think about is that using packages may be superior for your needs relative to sourcing files in the first place.
share|improve this answer
Very helpful comment. Hadn't even thought about the advantage of the function approach being able to use debug facility. You're right to answer the implicit question in "3)". I've been thinking about this as well. Ultimately, I'm trying to take great care in writing my code now so that I can eventually put everything into a package. – brianjd Mar 20 '11 at 21:43
add comment
I think that any temporary stuff created in source'd files won't get cleaned up. If I do:
and source that as a file, x hangs around although I don't need it. But if I do:
x = matrix(runif(big^2),big,big)
and instead of source, do z=ff(big) in my script, the x matrix goes out of scope and so gets cleaned up.
Functions enable neat little re-usable encapsulations and don't pollute outside themselves. In general, they don't have side-effects. Your line-by-line scripts could be using global variables and names tied to the data set in current use, which makes them unre-usable.
I sometimes work line-by-line, but as soon as I get more than about five lines I see that what I have really needs making into a proper reusable function, and more often than not I do end up re-using it.
share|improve this answer
Nodding my head the entire time I was reading your post. Exactly what I was thinking. In fact, with my current project I HAD developed some unwanted dependencies through global variables and needed to go back and debug. Not sure how this LCFD line-by-line programming paradigm has developed for statistical projects in R. It seems very misleading. – brianjd Mar 20 '11 at 21:35
I suspect its more like the way people work with SAS, which is probably harder to make more reusable and functional, being essentially a 1970s macro language.... – Spacedman Mar 21 '11 at 0:57
@brianjd: For me, separating the data input and cleanup steps from the analysis helps prevent these dependencies! Doing so makes it easy to always start an analysis with a clean workspace, and not have remnants from the input and cleanup hanging around. – Aaron Mar 21 '11 at 14:37
add comment
No one has mentioned an important consideration when writing functions: there's not much point in writing them unless you're repeating some action again and again. In some parts of an analysis, you'll being doing one-off operations, so there's not much point in writing a function for them. If you have to repeat something more than a few times, it's worth investing the time and effort to write a re-usable function.
share|improve this answer
On the contrary, Spacedman mentioned another benefit: clean up of temporary variables. Is there a way to do that without using functions? Or at least, a way that's neater than using non-reusuable functions? – naught101 Apr 3 '13 at 0:48
add comment
I use something very similar:
1. Base.r: pulls primary data, calls on other files (items 2 through 5)
2. Functions.r: loads functions
3. Plot Options.r: loads a number of general plot options I use frequently
4. Lists.r: loads lists, I have a lot of them because company names, statements and the like change over time
5. Recodes.r: most of the work is done in this file, essentially it's data cleaning and sorting
No analysis has been done up to this point. This is just for data cleaning and sorting.
At the end of Recodes.r I save the environment to be reloaded into my actual analysis.
save(list=ls(), file="Cleaned.Rdata")
With the cleaning done, functions and plot options ready, I start getting into my analysis. Again, I continue to break it up into smaller files that are focused into topics or themes, like: demographics, client requests, correlations, correspondence analysis, plots, ect. I almost always run the first 5 automatically to get my environment set up and then I run the others on a line by line basis to ensure accuracy and explore.
At the beginning of every file I load the cleaned data environment and prosper.
Object Nomenclature:
I don't use lists, but I do use a nomenclature for my objects.
df.YYYY # Data for a certain year
demo.describe.YYYY ## Demographic data for a certain year
po.describe ## Plot option
list.describe.YYYY ## lists
f.describe ## Functions
Using a friendly mnemonic to replace "describe" in the above.
I've been trying to get myself into the habit of using comment(x) which I've found incredibly useful. Comments in the code are helpful but oftentimes not enough.
Cleaning Up
Again, here, I always try to use the same object(s) for easy cleanup. tmp, tmp1, tmp2, tmp3 for example and ensuring to remove them at the end.
There has been some commentary in other posts about only writing a function for something if you're going to use it more than once. I'd like to adjust this to say, if you think there's a possibility that you may EVER use it again, you should throw it into a function. I can't even count the number of times I wished I wrote a function for a process I created on a line by line basis.
Also, BEFORE I change a function, I throw it into a file called Deprecated Functions.r, again, protecting against the "how the hell did I do that" effect.
share|improve this answer
add comment
I often divide up my code similarly to this (though I usually put Load and Clean in one file), but I never just source all the files to run the entire project; to me that defeats the purpose of dividing them up.
Like the comment from Sharpie, I think your workflow should depends a lot on the kind of work you're doing. I do mostly exploratory work, and in that context, keeping the data input (load and clean) separate from the analysis (functions and do), means that I don't have to reload and reclean when I come back the next day; I can instead save the data set after cleaning and then import it again.
I have little experience doing repetitive munging of daily data sets, but I imagine that I would find a different workflow helpful; as Hadley answers, if you're only doing something once (as I am when I load/clean my data), it may not be helpful to write a function. But if you're doing it over and over again (as it seems you would be) it might be much more helpful.
In short, I've found dividing up the code helpful for exploratory analyses, but would probably do something different for repetitive analyses, just like you're thinking about.
share|improve this answer
add comment
I've been pondering workflow tradeoffs for some time.
Here is what I do for any project involving data analysis:
1. Load and Clean: Create clean versions of the raw datasets for the project, as if I was building a local relational database. Thus, I structure the tables in 3n normal form where possible. I perform basic munging but I do not merge or filter tables at this step; again, I'm simply creating a normalized database for a given project. I put this step in its own file and I will save the objects to disk at the end using save.
2. Functions: I create a function script with functions for data filtering, merging and aggregation tasks. This is the most intellectually challenging part of the workflow as I'm forced to think about how to create proper abstractions so that the functions are reusable. The functions need to generalize so that I can flexibly merge and aggregate data from the load and clean step. As in the LCFD model, this script has no side effects as it only loads function definitions.
3. Function Tests: I create a separate script to test and optimize the performance of the functions defined in step 2. I clearly define what the output from the functions should be, so this step serves as a kind of documentation (think unit testing).
4. Main: I load the objects saved in step 1. If the tables are too big to fit in RAM, I can filter the tables with a SQL query, keeping with the database thinking. I then filter, merge and aggregate the tables by calling the functions defined in step 2. The tables are passed as arguments to the functions I defined. The output of the functions are data structures in a form suitable for plotting, modeling and analysis. Obviously, I may have a few extra line by line steps where it makes little sense to create a new function.
This workflow allows me to do lightning fast exploration at the Main.R step. This is because I have built clear, generalizable, and optimized functions. The main difference from the LCFD model is that I do not preform line-by-line filtering, merging or aggregating; I assume that I may want to filter, merge, or aggregate the data in different ways as part of exploration. Additionally, I don't want to pollute my global environment with lengthy line-by-line script; as Spacedman points out, functions help with this.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33645 | Take the 2-minute tour ×
This is probably really simple but I am absolutely stumped. While the CSS for the sidebar (#primary) doesn't have a margin specified, a margin-right: 605px; is being applied somehow to the #primary div.
To fix the problem, I played with some relative positioning inside the containing div, but this is causing positioning discrepancies between Firefox and Chrome.
You can find the site in question at elsbethroseboutique.com. I know it's in bad shape, it's a work in progress :)
The solutions I'm looking for are either how to address the positioning differences between the two browsers; or ideally, how to remove that margin.
Screenshots:(red line added for reference)
http://elsbethroseboutique.com/images/chrome_elsb.jpg http://elsbethroseboutique.com/images/firefox_elsb.jpg
share|improve this question
I couldn't really see a difference between the browsers (FF & Chrome). Are you able to upload a screen grab to outline the exact problem? – Dan Apr 5 '11 at 5:06
Yep, screenshots posted above. – Analyticus Apr 5 '11 at 7:24
Geeze, I suppose it's not that simple! – Analyticus Apr 6 '11 at 17:28
add comment
migrated from webmasters.stackexchange.com Apr 5 '11 at 3:09
This question came from our site for pro webmasters.
3 Answers
up vote 1 down vote accepted
This was a Chrome specific bug, where the developer tool told me there was a margin-right:605; when inspecting #primary. I think this was happening because there was no float property in place (although I can't understand why this was a problem if there were discrete values for height and width).
After floating #primary left, the problem appears to be solved and there is no longer a margin taking up the remaining space.
share|improve this answer
add comment
I don't see any discrepencies between Firefox and Chrome. Your code is quite the mess. What you need to do is identify the bloc of code you're having a problem with and post that. Even though I don't see the margin issue, often when I have a margin-right: problem that I can't find it turns out to be a margin-left: from another div. Hopefully that helps.
share|improve this answer
The #container element is a few pixels lower than the #primary element in chrome, but above the #primary in Firefox. If you use Chrome's inspect element (or firebug on Firefox), you can see there's a margin-right of 605 pixels being applied. This causes it to take up the entire width of the wrapper, and would force the container below it. The hack I used to fix it, was just to position it relative to the top of its containing div, but somehow this causes the discrepancy. – Analyticus Apr 5 '11 at 6:32
add comment
Get Firebug and you can click on the element and see any styles applied to it.
share|improve this answer
I just realized: this is only showing up in Chrome dev tools, not firebug. Very, very strange. Must be a browser thing. – Analyticus Apr 8 '11 at 18:17
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33646 | Take the 2-minute tour ×
Have you tried to use a MailboxProcessor of T from C#? Could you post sample code?
How do you start a new one, post messages to it, and how do you process them?
share|improve this question
add comment
2 Answers
up vote 11 down vote accepted
While you can use MailboxProcessor<T> directly from C# (using the C# async extension) as pointed out in my other answer, this isn't really a good thing to do - I wrote that mainly for curiosity.
The MailboxProcessor<T> type was designed to be used from F#, so it doesn't fit well with the C# programming model. You could probably implement similar API for C#, but it wouldn't be that nice (certainly not in C# 4.0). The TPL DataFlow library (CTP) provides similar design for the futrue version of C#.
Currently, the best thing to do is to implement the agent using MailboxProcessor<T> in F# and make it friendly to C# usage by using Task. This way, you can implement the core parts of agents in F# (using tail-recursion and async workflows) and then compose & use them from C#.
I know this may not directly answer your question, but I think it's worth giving an example - because this is really the only reasonable way to combine F# agents (MailboxProcessor) with C#. I wrote a simple "chat room" demo recently, so here is an example:
type internal ChatMessage =
| GetContent of AsyncReplyChannel<string>
| SendMessage of string
type ChatRoom() =
let agent = Agent.Start(fun agent ->
let rec loop messages = async {
// Pick next message from the mailbox
let! msg = agent.Receive()
match msg with
| SendMessage msg ->
// Add message to the list & continue
let msg = XElement(XName.Get("li"), msg)
return! loop (msg :: messages)
| GetContent reply ->
// Generate HTML with messages
let html = XElement(XName.Get("ul"), messages)
// Send it back as the reply
return! loop messages }
loop [] )
member x.SendMessage(msg) = agent.Post(SendMessage msg)
member x.AsyncGetContent() = agent.PostAndAsyncReply(GetContent)
member x.GetContent() = agent.PostAndReply(GetContent)
So far, this is just a standard F# agent. Now, the interesting bits are the following two methods that expose GetContent as an asynchronous method usable from C#. The method returns Task object, which can be used in the usual way from C#:
member x.GetContentAsync() =
member x.GetContentAsync(cancellationToken) =
( agent.PostAndAsyncReply(GetContent),
cancellationToken = cancellationToken )
This will be reasonably usable from C# 4.0 (using the standard methods such as Task.WaitAll etc.) and it will be even nicer in the next version of C# when you'll be able to use the C# await keyword to work with tasks.
share|improve this answer
Thank you for your detailed answer. I'll give it a shot! One piece is missing -- actual usage from C# 4.0. – GregC Apr 7 '11 at 21:29
add comment
This solution requires the C# "async CTP" but take a look at Agent/MailboxProcessor in C# using new async/await
share|improve this answer
Question is specifically geared towards C# 4.0, since I have my hands tied. I'd use F# in a heart-beat for this, but I can't just yet. Does Async CTP have a go-live license? – GregC Apr 7 '11 at 13:23
As Tomas P. points out, the crux of this problem would be in the tail-recursive call causing a StackOverflowException. I am looking for alternatives. – GregC Apr 7 '11 at 13:26
@GregC, no it doesn't have a go-live license. It's only a preview, as the name implies, you shouldn't use it in production – Thomas Levesque Apr 7 '11 at 13:29
it's hard to unlearn a powerful programming paradigm. Once you know it, you refuse to implement things the old simpleton way. – GregC Apr 7 '11 at 13:31
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33647 | Take the 2-minute tour ×
In my c++ program several child processes are started using fork and execv. I don't wait for them so they run in the background. When they finish running, I want to run a certain function. How can this be done?
share|improve this question
add comment
2 Answers
Listen for the SIGCHLD signal and call your function in the handler. Be careful what you call in the handler, you should only call async-signal-safe functions.
share|improve this answer
How do you know what those functions are? – node ninja Apr 28 '11 at 7:02
@z-buffer: There is a list at the end of this page: linux.die.net/man/2/signal – cnicutar Apr 28 '11 at 15:28
add comment
I'm guessing that you do want to wait for the processes to finish, but you want to run the processes in parallel rather than sequentially. If so, start each process as you do now, then use the waitpid() system call on each child pid. When every process has exited, every waitpid will have returned.
share|improve this answer
should waitpid use WNOHANG? – node ninja Apr 28 '11 at 7:01
Not if you want to wait for the subprocesses to finish. – Marcelo Cantos Apr 28 '11 at 8:12
I don't want the parent process to wait for the child. – node ninja Apr 28 '11 at 9:16
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33648 | Take the 2-minute tour ×
I'm facing a strange behaviour by IE9 dealing with a prototype script. Here I'm setting two different opacity styles depending on mouseover / out:
window.onload = function(){
var freccia1 = $($$('.next_button')[0]);
freccia1.setStyle({opacity: '0.20'});
freccia1.setStyle({filter: 'alpha(opacity=20)'});
var freccia2 = $($$('.previous_button')[0]);
freccia2.setStyle({opacity: '0.20'});
This is working fine in all browsers, including previous IE versions, nut not in IE9 which doesn't low the opacity..its console returns me:
Not possible to get the property 'setStyle' value: object null or undefined
does anyone know why ? thank you
share|improve this question
add comment
2 Answers
You didn't mention which version of prototype you are running. I ran into a similar problem that may be similar on one of my pages using prototype 1.5.0 (please don't judge). In 1.5.0 the setStyle and getStyle functions do a browser check for IE specifically when dealing with opacity/alpha(opacity).
In my case, setStyle calls getStyle('filter').replace(). Unfortunately getStyle('filter') returns null with IE9 so .replace throws an exception.
Some relevant notes from the IE team: http://blogs.msdn.com/b/ie/archive/2010/08/17/ie9-opacity-and-alpha.aspx
share|improve this answer
add comment
If you're going to use Prototype, you might as well use as much functionality as it offers since it takes browser compatibility into consideration so you don't have to.
Try this (untested):
document.observe('dom:loaded', function() {
[$$('.next_button')[0], $$('.previous_button')[0]].each(function(ele) {
opacity: '0.20',
filter: 'alpha(opacity=20)'
share|improve this answer
Thank you for helping, but your code returns me: "$(ele).setStyle is undefined"... – serytankian Jun 15 '11 at 8:04
@asnothingelse are you sure $$('.next_button')[0] and $$('.previous_button')[0] exist? – John Conde Jun 15 '11 at 13:21
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33649 | Take the 2-minute tour ×
So, I'm planning to use sqlite3 to update skype's main.db file.
I use sqlite3_open function to open the connection like this.
int rc = sqlite3_open(filepath,db);
I'm trying to do the filepath string dynamically, but a weird error is driving me crazy.
I have two strings szFile and szFilePath, szFile being a test string which will contain the actual path of the db file, and szFilePath is the same string only this time dynamically generated by a function.
The thing is just before the execution of sqlite3_open function, both strings as you see on the screenshot are identical, I even posted memory for you to see.
Look at pictures: Picture 1 Picture 2
Now, despite being completely identical, no matter how many times I run this code ONLY szFile works, with the other one giving me a "cannot open file path" error, and completely confusing me. Also, I don't no if this is normal, but by setting a breakpoint at the next if, I can see that szFilePath loses it's value (is filled with c hex values).
What could be wrong?
share|improve this question
add comment
3 Answers
up vote 2 down vote accepted
You're returning a char* that points to an array on the stack - as soon as you return from the function szGetFilePath, this pointer is quite possibly pointing to junk (it will definitely point to junk after a couple of levels of additional calls - when the values on the stack are overwritten).
You can either return a dynamically allocated array of char (i.e. malloced) from the function (and remember to free it later), or pass a pointer to a char array through to szGetFilePath and put the character data into this.
share|improve this answer
So how do I make it point to an array on the heap? – Panayiotis Jun 5 '11 at 18:12
@Panayiotis - answer modified to give you a couple of options. – Will A Jun 5 '11 at 18:16
Thanks a lot! Managed to get it working with the second option, although I would like to know how to do it with dynamic allocation as well. Would you be kind enough to give me a code example of how to do it with malloc? – Panayiotis Jun 5 '11 at 18:28
add comment
szGetFilePath is returning the reference of a local variable(szPathAppData). On returning from the function call, unwinding of the stack begins.
char* szGetFilePath( char* szAccountName )
char *szPathAppData = calloc(128,1) ; // Allocating memory on heap
// ....
return szPathAppData ;
// You need to free the resources acquired on heap by using free.
// free(szPathAppData) ;
share|improve this answer
Thanks a lot for the code! Just what I was looking for :) – Panayiotis Jun 5 '11 at 18:32
@Mahesh How will I free up the resources, if szPathAppDate does not exist outside the function scope? I'm getting some nasty heap exceptions as well. – Panayiotis Jun 5 '11 at 18:39
@Panayiotis - I am not sure I correctly understood you. You are just returning a pointer to the location on the heap. And you should be able to free via the variable that collects it. BTW, is the data pointed by szPathAppData null terminated ? (\0) – Mahesh Jun 5 '11 at 18:46
@Mahesh Yes, it is – Panayiotis Jun 5 '11 at 18:48
@Panayiotis - Could you please post the code with the modifications made ? ( pastebin.com ) – Mahesh Jun 5 '11 at 18:51
show 7 more comments
C isn't my strong point but are you perhaps not sending through a UTF-16 string to a function that accepts a UTF-8 string?
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33650 | Take the 2-minute tour ×
How can we increase the performance of an application. My application is written using Java, Hibernate, Servlets, Wsdl i have used for web services. I have executed some of the tests on linux machine, so that i can get proper TPS of the execution.
but still , i am not satisfied by the performance.
So for this, what all steps i should try to increase the performance.
adding to above, i have executed code coverage and used find bugs in the code prominently for each and every test and every service i have written.
Individual suggestions are invited.
share|improve this question
Well, if you are not satisfied with the performance, did you attempt to find out where it was unsatisfactory. I'm afraid that statement of yours came out like a rant. – Vineet Reynolds Jun 14 '11 at 10:50
What exactly did you do to measure the performance? Is there any specific performance issues you are trying to resolve? What exactly does your application do? – abalogh Jun 14 '11 at 10:52
add comment
3 Answers
up vote 3 down vote accepted
Profile your application, and remove all of your bottlenecks.
In addition, or better before, take a day or two and read as much from the Java Performance Tuning newsletters as you understand.
share|improve this answer
add comment
You should monitor your application with a tool like VisualVM, JProfiler etc. to determine the performance bottleneck(s). It is pointless to tune the application without knowing where the actual performance problems are located.
In a professional environment, I suggest dynaTrace that can show you performance bottlenecks along the execution path. The tool can show you exactly where the application spends its time.
share|improve this answer
I have used VisualVm to figure out, how much time is taken by each and every critical service and database hits. With those stats, i can say that i am somewhat happy with service but unhappy with database hits. – M.J. Jun 14 '11 at 11:12
At least you found out what to tune. Database tuning guides are avaiblable for all major databases. Sometimes creating a missing index is enought for a problem. – Daniel Jun 14 '11 at 13:02
For instance, http://stackoverflow.com/questions/2980359/web-page-database-query-optimization includes some proposals to decrease the hit number. In general, I would suggest caching as a good way to reduce the database hit number. – s106mo Jun 14 '11 at 19:34
add comment
Is the performance related to disk I/O or network I/O? In a high throughput system (from DB point of view) Hibernate might not be the best way to go. If you have a lot of writes I would recommend you use a different mechanism to write to database -- perhaps simply switching to simple JDBC might speed it up? Secondly, is it the case that your webservices are taking too long to get back with results? SOAP is not the fastest protocols really -- have you looked at something like REST maybe coupled with JSON ?
share|improve this answer
For servlet to service execution flow, i am using JSON only. I am using wsdl in case when other system is invoking some of my service. – M.J. Jun 14 '11 at 11:13
and have you measured the network trip for each request, JSON or WSDL? – Liv Jun 14 '11 at 11:14
network, as in JSON i have figured out, but how can we measure for WSDL? – M.J. Jun 14 '11 at 11:30
use some timers in your code and record the time it takes from the moment you make the call till your result comes back. – Liv Jun 14 '11 at 11:30
I should add -- you could use something like JETM for this: jetm.void.fm – Liv Jun 14 '11 at 11:32
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33651 | Take the 2-minute tour ×
I am wondering if there is a better way to write this:
void readtcp_c(unsigned char c)
volatile char *a;
volatile int *p;
volatile int *q;
a = (char *)APPLE_REG_A; // a = memory mapped address for REG A
*a = c + 128; // store c + 128 in REG A
p = (int *)APPLE_SUB; // p = address of 6502 sub
*p = TCP_WRITE; // store TCP entry point in address p
p = (int *)SOFTCARD; // p = address of softcard address
q = (int *)*p; // q = softcard address
*q = 0; // write 0 to softcard address
IANS, I have to read/write to specific addresses. 'a' is simply a write to a memory mapped register (6502). The next two lines are similar, except that I am writing the address of a 6502 entry point to be used later. The last 3 lines is where I have to write a 0 to the address stored in SOFTCARD. Writing to this address triggers the call to the aforementioned entry point.
It's the last 3 lines that I think can be shorter. Perhaps not. If the other pairs can be written as a single line that'd be great too. The code works and compiles (sdcc) without error or warning.
Update: I guess I could replace:
*q = 0; // write 0 to softcard address
p = (int *)*(int *)SOFTCARD;
*p = 0;
It compiles without warning and runs. But is it readable? Thanks again.
share|improve this question
Apple? 6502? Register A? Softcard? Please, for the love of all that's holy, please tell me you're joking :-) Is someone actually still using these machines? – paxdiablo Jun 25 '11 at 23:50
add comment
2 Answers
up vote 1 down vote accepted
This should do it. I just replaced the variables by their definition after adding volatile (and also a pair of parenthesis)
void readtcp_c(unsigned char c)
*((volatile char *)APPLE_REG_A) = c + 128;
*((volatile int *)APPLE_SUB) = TCP_WRITE;
*((volatile int *)*((volatile int *)SOFTCARD)) = 0;
The compiler is perfectly capable of generating good code from your first version though. I like your step-by-step code better.
share|improve this answer
+1 for volatile (compared to the other answer) – Seth Robertson Jun 25 '11 at 23:47
Thanks. Works perfect. – datajerk Jun 25 '11 at 23:51
add comment
You should be able to rewrite all the assignments as
*(char *)APPLE_REG_A = c + 128;
**(int **)SOFTCARD = 0;
share|improve this answer
The last line failed to compile. Thanks for the input. – datajerk Jun 25 '11 at 23:52
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33652 | Take the 2-minute tour ×
I have a wpf application where I extended the RichTextBox to provide some specific functions. Lets call that new class BetterTextBox.
Now, when I click in that TextBox TextBox.OnPreviewMouseLeftButtonUp is called and I am getting the CaretPosition:
protected override void OnPreviewMouseLeftButtonUp(MouseButtonEventArgs e)
PressedOffset = Document.ContentStart.GetOffsetToPosition(CaretPosition);
public static readonly DependencyProperty PressedOffsetProperty
= DependencyProperty.Register("PressedOffset", typeof(int),
new FrameworkPropertyMetadata()
DefaultValue = 0,
BindsTwoWayByDefault = true,
DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
public int PressedOffset
get { return (int)GetValue(PressedOffsetProperty); }
set { SetValue(PressedOffsetProperty, value); Console.WriteLine("klöjgf");}
<Window x:Name="MainWindow">
<BetterTextBox />
MainWindow has MainViewModel as DataContext. What I want to do is, when a MouseClick in BetterTextBox occurs, a function in MainViewModel should be called. How can I get out of my UserControl a call a function in the MainViewModel?
I tried something like this:
<Window x:Name="MainWindow">
<BetterTextBox PressedOffset="{Binding ElementName=MainWindow, Path=MyFunction"/>
public int MyFunction
set { callMyRealFunction(); }
But that doesn't work. There is also a way to register a CallbackFunction for PressedOffsetProperty, but I am not sure how to register there a function from the MainViewModel which is not static.
share|improve this question
add comment
2 Answers
Create another dependency property of type ICommand say 'TextClickCommand'. Create a command in your viewmodel and bind to TextClickCommand and execute this on MouseClick.
Edit: You can do it even the other way around create a IsTextSelected bool dependency property in textbox bind to this bool using a propery in view model and call your method in view model property setter.
share|improve this answer
Sry, I can't really follow you. Can you be more precisly? I am already doing your "Edit" without luck or not? I also googled for Commands and there is a bunch of results and I am getting lost. – KasF Jun 30 '11 at 7:57
add comment
up vote 0 down vote accepted
Just solved by doing
<BetterTextBox PressedOffset="{Binding Path=Parent.DataContext.SelectFromOffset,
RelativeSource={RelativeSource Self}}"/>
from WPF Usercontrol interaction with parent view / viewmodel
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33653 | Take the 2-minute tour ×
I've run into the following issue, which seems to be a pretty common one. The exception is Cannot update entity: [...] nested exception is java.sql.BatchUpdateException: ORA-24816: Expanded non LONG bind data supplied after actual LONG or LOB column. It looks like Oracle does not like binding large values (> 4000 chars) to parameters after a LOB or CLOB. Has anyone solved this issue?
share|improve this question
add comment
1 Answer
up vote 7 down vote accepted
This is: ORA-24816
*It's a limitation, and that LONG bind variables must come last in a statement. *
source: http://www.odi.ch/weblog/posting.php?posting=496
Solution: By renaming the fields in the hibernate model so that the clob column has a name that comes later than the varchar2 column when ordering alphabetically (I prefixed the clob field in the java class with a 'z'), everything works fine because then the clob parameter comes after the varchar parameter in the query hibernate builds.
share|improve this answer
I found that with XML-mapped entities I could change the order of the properties in the config to get the clobs to the end of the INSERT/UPDATE statement. E.g. <property name="shortField1"/><property name="shortField2"/><property name="reallyLongField" type="text"/> – Josh Johnson Sep 12 '12 at 12:40
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33654 | Take the 2-minute tour ×
I've noticed that many web sites are being designed under XHTML Transitional despite adhering to most modern web design practices. I thought transitional was meant as a temporary solution for porting over old markup that may require too much effort to redesign.
And many web sites don't even validate properly under Transitional. I try very hard to adhere to the strict standards under the belief that improper markup leads to much difficulty debugging when something doesn't work. However, it is a lot of work writing 100% valid code.
I'm curious as to whether or not it's worth putting in the effort to learn and write XHTML strict compliant markup.
EDIT: And if it is, why don't more people do it? It seems rather rare for me to stumble upon a proper XHTML strict web page.
share|improve this question
add comment
4 Answers
up vote 4 down vote accepted
Short answer: no.
I've never found Strict XHTML to be worth the effort.
The first problem with it is that it deprecated a number of HTML features which were actually useful, and for which there were no good alternative solutions. This was a particular problem if you needed backward compatibility with older browsers (which of course everyone does). The Transisional spec didn't deprecate these features, which is why people use it rather than Strict.
Features that were deprecated included the <center> tag (CSS alternatives were not cross-browser compatible at the time) and the target attribute for the <a> tag (which allows you to open a link in a new window, tab or frame; there still isn't any other way to do this, no-one stopped using it, and HTML5 has re-introduced it). There were quite a few other features along the same lines, but it's been a long time, and I can't remember them all.
Secondly, it was designed to cause the browser to fail if your markup had even the smallest error. This sounds great in theory, but was always doomed to failure. It was basically a reactionary step taken by the specification writers against the proliferation of poor-quality HTML code that was (and to some extent still is) a major issue for the web. But they forgot a key rule for designing client-server protocols, which is that the server should be strict about what it sends, but the client should be lenient. All successful client-server protocols follow this rule.
It is good to care about your markup being valid - in fact, it's very important, regardless of what (x)HTML dialect you're writing in - but you should be checking that in the development phase, not letting the end user's browser do your validation for you. If you're a good developer, you should know that your code is good before it gets anywhere near the user. And in fact, if that causes your site to completely break in front of the end user, then it's a disaster. With broken HTML, even if it's quite badly broken, the user can generally navigate and read the site sufficiently to be able to find contact details for you to report the error. With a browser that respects the strict XHTML doctype, a tiny markup error can cause your site to show nothing other than a standard browser error message. This is a very very poor user experience.
Finally, it didn't provide any new features. The one thing it did which older HTML versions didn't do was allow the document to be parsed as an XML document. This was good for validating that your document didn't have any errors, but didn't really achieve much else. You could also embed other XML formats into your document, using namespaces, but this was complex and didn't really achieve much new either.
XHTML was always an idealistic dream, and it is thankfully fading away now that HTML5 has taken over as the new-and-exciting-thing.
share|improve this answer
Could you give a few examples of useful deprecated features? It seemed to me that all features have a good XHTML compliant solution. – tskuzzy Jul 8 '11 at 13:34
@tskuzzy -- okay, I've edited the answer to include two features which prevented me from moving to XHTML Strict back in the day. – Spudley Jul 8 '11 at 13:42
add comment
I'd say Yes(ish).
Typically choosing the strict version would inicate what standards you should be adhering to going forward. i.e. deprecated attributes in xhtml strict (but allowed in transitional), would not appear in a later version of the standard.
Now my rule of thumb is kind of broken, with the movement from xhmtl to html5. As html5 doesn't have a strict version, but i'd say go for html5 (or even xhtml5) rather than xhtml strict.
But I'd say in general trying to stick to the most strictest version of anything keeps you focused on best practice ready for the next version i.e. things don't go backwards (in theory).
share|improve this answer
add comment
I used to write all XHTML strict, but that is because I cared about my markup being semantically correct. Unfortunately, most web developers either (a) don't care about semantically correct code or (b) are unaware there is even a problem.
Really, if you want to write in Strict, just write your page and then run it through the validator. It's going to tell you what's wrong and what you need to fix. You'll learn as you go along what things you should or shouldn't do. Looking at the official spec can help tremendously.
On another note, I'd also recommend moving to HTML5. HTML5 doesn't have types like "strict" and "transitional". If you want to write by stricter rules, you can. If you want to write by loser rules, you can. I also feel it's cleaner all around and I enjoy writing HTML5 much more than XHTML. Again, running your site through the validator is going to give you insight to stuff that you're doing that is incorrect.
As for what more people are starting to do, I would say there is a big push to HTML5. And not only because it's the new and cool thing to do, but because it fixes a lot of nuisances and annoyances that have existed in XHTML and HTML4.
So, my recommendation would be to head in that direction.
share|improve this answer
I absolutely agree that it's important to write valid markup, but XHTML Strict was never the solution to that because it put the validation in front of the user, with horrible error messages if it's even slightly wrong: that kind of testing should be done long before it gets anywhere near the user. – Spudley Jul 8 '11 at 13:45
add comment
I've been writing strict markup for a few years and there are no noticeable benefits that I can see.
I would much rather use the HTML5 <!DOCTYPE html> simply because it's cleaner and degrades well in IE.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33655 | Take the 2-minute tour ×
I've been experimenting with an unobtrusive Knockout data-binding jQuery plugin. Follow the link here.
I cannot seem to figure out how to keep the "data-bind" attribute out of a template, though. I can't decide whether or not it should even be done, either. I just have a hunch.
Example template:
<script id="storeTemplate" type="text/x-jquery-tmpl">
<div class="storeTitle" data-bind="click: select">${storeTitle}</div>
I'm thinking that it might be a good idea to pull data-bind="click: select" out of there. Does anyone have an idea as to how to do that? I've tried $(".storeTitle").dataBind( { click: "select" } ); A jQuery selector only selects objects that have already been created in the DOM, yet the elements we want to edit are not part of the DOM yet. Also, I would like to avoid applying bindings more than once.
share|improve this question
I just checked the code and I don't see any reason why the plugin won't work in the template. You need to do it the same way using $(".storeTitle").dataBind( { click: "select" } ); – nEEbz Jul 12 '11 at 21:43
I'm not quite sure what you mean. I tried the line above before (just tried it again, too) and it didn't work for me. I looked through the plugin too and it only selects objects that have already been created in the DOM, as jQuery normally does. I'm going to update my question a bit. – BDawg Jul 14 '11 at 18:57
add comment
1 Answer
up vote 0 down vote accepted
It seems I just sort of answered my own question. Considering that the elements in the template are actually sitting in the DOM (just in string form) I could just modify the string and add the data-bind="click: select". Rather than doing string manipulation, a coworker suggested I just temporarily insert the template text as innerHTML to add it to the DOM, modify it using the plugin, insert the modified version back into the template as text and apply bindings.
share|improve this answer
Just make sure that you test it in IE :) IE seems to be a little finicky about editing the text of an existing script element. Otherwise, I was going to suggest something like: jsfiddle.net/rniemeyer/5dkMg where you load them into a jQuery object and don't actually insert them into the DOM. – RP Niemeyer Jul 15 '11 at 20:17
@RP Niemeyer - Thanks a lot for this tip! I just noticed that the code I made doesn't work in IE<9. – BDawg Jul 18 '11 at 17:30
I found that IE<9 do not support modifying innerHTML of elements either. I got around it by just deleting and recreating the elements. Also, they remove double quotes from attributes in the innerHTML, which doesn't help if you want to modify it and create another element from it. I had to play with regular expressions for a while to work around that one – BDawg Jul 19 '11 at 18:09
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33656 | Take the 2-minute tour ×
My task is to populate another select list based on what is choosen from one select list, querying populating data from database.
I think it goes something like:
2. On select list onChange method a query like select id, description from table where child_id=_id_ is executed.
3. Child select list is populated based on that query. Maybe the result of query is returned in a controller method?
share|improve this question
add comment
1 Answer
up vote 3 down vote accepted
I would like to recommend you to use Google, because simple search will provide you the answer.
This code sample will show you the way how to do it:
$.getJSON("/getSubCategories?id="+$(this).val(), function(j){
var options = '';
Now the Server side:
@RequestMapping(method = RequestMethod.GET, value = "/getSubCategories")
public String handleRequest( @RequestParam("id") int id) {) {
now build your json string as optionValue and OptionDisplay.
String json = service.getSubCategories(id);
return json;
share|improve this answer
What keywords did you use? I tried google.. – mjgirl Jul 25 '11 at 8:51
How to build the json String ??? – Abhishek Singh Oct 9 '13 at 10:57
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33657 | Take the 2-minute tour ×
If I want to redirect a user in PHP, all I've ever known to do was use the header('Location:' http://www.example.com) but I've been reading that this isn't the best way to redirect a user from page to page internally. What are some other options you can redirect a user?
Example: at the bottom it says:
Something Important to Remember
...I don’t recommend, for example, using header() to bounce your users around to different pages; there are better methods that reduce the number of page loads and give the user a more fluid experience...
share|improve this question
you can also redirect from client side: window.url = 'newUrl'; – ThatGuy Aug 1 '11 at 15:50
add comment
5 Answers
up vote 1 down vote accepted
The snippet you provided is referring to issues where page1.php might execute some code followed by header('Lodation: http://www.example.com/page2.php'); and where page2.php then executes some code followed by header('Location: http://www.example.com/page3.php'); etc. This is very bad for user experience, and not very good for managing code either.
In cases where you genuinely need to redirect a user (301 redirect is probably the most common), using header is perfectly acceptable.
share|improve this answer
I don't quite understand the difference in what your saying. Do you mean don't have 2 redirects in a row? – Howdy_McGee Aug 1 '11 at 16:21
@Howdy_McGee, multiple redirects, or redirects when an include would be more appropriate are issues. It is quite common for beginners to create a php page to do a very specific task, and then instead of using include, trying to use header to pass the user on to another page. I typically avoid headers unless I decide that I need to send a browser a particular header. If a page has moved permanently, use the 301 redirect header and the new location, if a resource wasn't found, send out a 404 header, and possibly populate the page with a sitemap. – zzzzBov Aug 1 '11 at 17:28
I see, I try to avoid using 'includes' unless i'm including a header.php or footer.php because from my understanding it loads everything inside the 'includes' even php which would mess with load time. I understand what your saying though with the 301 and 404. I think javascript is my base option when redirecting to a custom error page though like the poster above stated. – Howdy_McGee Aug 1 '11 at 17:33
@Howdy_McGee, includes are the best way to make PHP modular. They're very quick. If you're making an entire library, you should be putting classes and functions into their own scripts, or at least boxing them into groups of similar functions. If you're mixing display logic with business logic, then you should read up on the MVC (Model View Controller) paradigm, because mixing view with controller is a bad idea. – zzzzBov Aug 1 '11 at 18:12
add comment
It isn't bad. However you could add 301 response code to make it more better, it is also better for Google to determine he should not visit that "old" site anymore.
Header( "HTTP/1.1 301 Moved Permanently" );
share|improve this answer
Well what if it is just a simple "do some code then redirect" instead of a permanent redirect? – Howdy_McGee Aug 1 '11 at 16:23
so use it before this header and after that put there this code (2nd line) – genesis Aug 1 '11 at 16:41
add comment
This is the accepted method for PHP-based redirection. If you can accomplish the redirect prior to PHP script execution, then you should - through .htaccess or server-level aliasing.
Check out the manual on header: http://php.net/manual/en/function.header.php
share|improve this answer
add comment
It's always sensible to avoid using header() internally because sometimes headers are already called. JavaScript redirects are absolutely fine and are used systematically in a lot of web applications. Browsers and search engines don't discriminate against or dislike JavaScript redirects. A simple example:
<?php echo '<script type="text/javascript">window.location.href="index.php"</script>'; ?>
Or using a variable:
<?php echo '<script type="text/javascript">window.location.href="' . $page . '"</script>'; ?>
share|improve this answer
Well if this is true it seems like the best answer unless somebody wants to argue it. – Howdy_McGee Aug 1 '11 at 16:50
JavaScript redirects are the worst way to do redirects. You ought to know whether headers have been called or not based on whether you've used a header call or whether you've sent any output with echo or similar. If you've partially sent output to the user, why would you want to then direct them away from that data? Additionally, any user without JavaScript enabled will not be able to follow the redirect. I would also like to see verification about SEO for JS redirects. – zzzzBov Aug 1 '11 at 18:10
In complicated web apps (especially those with partial views) you don't always know whether the script has previously used a header() function or not. This is why I said it's usually sensible to avoid all potential errors by using JavaScript. The OP said he wanted to redirect a user - he didn't mention anything about maintaining the use of data, variables or existing PHP functions. And the percentage of users with JavaScript enabled is something ridiculous like 2% (or so Verisign argues - bit.ly/nZ75ql). You can always echo out a noscript tag. – hohner Aug 1 '11 at 18:16
@Jamie, "you don't always know whether the script has previously used a header() function or not" WTF are you talking about?! Of course you can tell whether headers have been sent. – zzzzBov Aug 1 '11 at 20:21
add comment
Just use
share|improve this answer
It does not explain why or if it's bad – genesis Aug 1 '11 at 15:50
Nothing bad about it. It's just the accepted method for PHP. – Mark Aug 1 '11 at 15:52
This is what i'm trying to avoid... – Howdy_McGee Aug 1 '11 at 15:53
What I think that the writer of the examples tries to say is that what he wrote are just examples just like he said. In most of the cases in the example it isn't necessary to do a redirect. – Mark Aug 1 '11 at 15:57
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33658 | Take the 2-minute tour ×
I'd like to configure the EditorFor template for every datatime objects in any of my models.
I'm getting this error:
\EditorTemplates\DateTime.cshtml(1): error CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'TextBox' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
Here's the entire code that's inside of the EditorTemplate called, DateTime.cshtml places in the EditorTemplates folder.
Any ideas?
Here's what I call in my View:
<div class="editor-label">
@Html.LabelFor(model => model.DateOfBirth)
<div class="editor-field">
@Html.EditorFor(model => model.DateOfBirth)
@Html.ValidationMessageFor(model => model.DateOfBirth)
And this is the custom EditorTemplate I made:
@Html.TextBox("", Model, new { @class = "date-selector" });
Basically, for every datetime object in my models, I want to add the class "date-selector" to that html element. This is for jQueryUI purposes.
What am I doing wrong?
share|improve this question
It seems I just had to cast Model to (DateTime)Model. – Only Bolivian Here Aug 21 '11 at 19:36
add comment
3 Answers
up vote 3 down vote accepted
You can create an extension method as below:
public static MvcHtmlString CalenderTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
return htmlHelper.TextBoxFor(expression, "{0:M/dd/yyyy}", new { @class = "datepicker text" });
Then use in view as below:
@Html.CalenderTextBoxFor(model => model.Employee.HireDate)
share|improve this answer
add comment
You need to define the model type of the editortemplate. Add "@model DateTime" to the top of the cshtml file:
@model DateTime
share|improve this answer
Much cleaner than my solution of casting the dynamic object. Thanks! :) – Only Bolivian Here Aug 22 '11 at 13:18
add comment
I know this is an older question, but I had the same frustrating issue and I didn't want to create an EditorTemplate that applied to all DateTime values (there were times in my UI where I wanted to display the time and not a JQueryUI drop-down calendar). In my research, the root issues I came across were:
• The standard TextBoxFor helper allowed me to apply a custom class of "date-picker" to render the unobtrusive JQueryUI calender, but TextBoxFor wouldn't format a DateTime without the time, therefore causing the calendar rendering to fail.
• The standard EditorFor would display the DateTime as a formatted string (when decorated with the proper attributes such as [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")], but it wouldn't allow me to apply the custom "date-picker" class.
Therefore, I expanded upon @Ashraf's answer and created custom HtmlHelper class that has the following benifits:
• The method automatically converts the DateTime into the ShortDateString needed by the JQuery calendar (JQuery will fail if the time is present).
• By default, the helper will apply the required htmlAttributes to display a JQuery calendar, but they can be overridden if needs be.
• If the date is null, MVC will put a date of 1/1/0001 as a value. This method replaces that with an empty string.
I post this here in hopes that it might help someone else at some point. Any suggestions on changes needed are welcome.
public static MvcHtmlString CalenderTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
var mvcHtmlString = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression, htmlAttributes ?? new { @class = "text-box single-line date-picker" });
var xDoc = XDocument.Parse(mvcHtmlString.ToHtmlString());
var xElement = xDoc.Element("input");
if (xElement != null)
var valueAttribute = xElement.Attribute("value");
if (valueAttribute != null)
valueAttribute.Value = DateTime.Parse(valueAttribute.Value).ToShortDateString();
if (valueAttribute.Value == "1/1/0001")
valueAttribute.Value = string.Empty;
return new MvcHtmlString(xDoc.ToString());
And for those that want to know the JQuery syntax that looks for objects with the date-picker class decoration to then render the calendar, here it is:
$(document).ready(function () {
$('.date-picker').datepicker({ inline: true, maxDate: 0, changeMonth: true, changeYear: true });
$('.date-picker').datepicker('option', 'showAnim', 'slideDown');
Hopefully this helps someone in the future that has this need.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33659 | Take the 2-minute tour ×
I have a service application created with Delphi, and managed to install it from another Delphi application using elevated privileges.
The service is set to log on as the Local System account (which is default when creating a service application in Delphi).
I have another Delphi application in which an ordinary user is supposed to be able to start or stop the above service.
My question is: Is this allowed by Windows? When I try to start the service using code in Delphi, it just fails with 'Code 5. Access is denied.' How can I prevent this error from occurring? I want to be able to have the normal user running the application (not in Administrator mode and thus not with elevated privileges) to start / stop the service. Is it possible and if so how? Below is my code:
function ServiceStart(sMachine, sService: string): boolean;
schm, schs: SC_Handle;
ss: TServiceStatus;
psTemp: PChar;
dwChkP: DWord; // check point
ss.dwCurrentState := 0;
// connect to the service control manager
schm := OpenSCManager(PChar(sMachine), nil, SC_MANAGER_CONNECT);
// if successful...
if (schm <> 0) then
// open a handle to the specified service
// we want to start the service and query service
// status
schs := OpenService(schm, PChar(sService), SERVICE_START or SERVICE_QUERY_STATUS);
// if successful...
if (schs <> 0) then
psTemp := nil;
if (StartService(schs, 0, psTemp)) then
// check status
if (QueryServiceStatus(schs, ss)) then
while (SERVICE_RUNNING <> ss.dwCurrentState) do
// dwCheckPoint contains a value that the
// service increments periodically to
// report its progress during a
// lengthy operation. Save current value
dwChkP := ss.dwCheckPoint;
// wait a bit before checking status again
// dwWaitHint is the estimated amount of
// time the calling program should wait
// before calling QueryServiceStatus()
// again. Idle events should be
// handled here...
if not QueryServiceStatus(schs, ss) then
// couldn't check status break from the
// loop
if ss.dwCheckPoint < dwChkP then
// QueryServiceStatus didn't increment
// dwCheckPoint as it should have.
// Avoid an infinite loop by breaking
if MessageDlg('Start Service failed. Do you want remove it?',
mtWarning, [mbYes, mbNo], 0) = mrYes then
// close service handle
end else RaiseLastOSError;
// close service control manager handle
// Return TRUE if the service status is running
Result := SERVICE_RUNNING = ss.dwCurrentState;
share|improve this question
add comment
3 Answers
up vote 7 down vote accepted
By default you need to have admin privileges to start, stop, install and delete services.
You will have to arrange for your service to expose its own Active property, distinct from what Windows terms as running. Arrange that it is running in Windows terms all the time, but inert when its Active property is false.
You'll have to implement a control mechanism for your user app. I've done this with named pipes but the are other IPC methods available.
share|improve this answer
The user that is running the application has Administrator privilege on Windows 7, yet the function call to start the service fails. It only works if the application was started with 'Run as Administrator'. Why is this? – Steve F Aug 24 '11 at 10:44
Because it needs elevation. You should properly tell the user, see msdn.microsoft.com/en-us/library/aa511445.aspx, and then perform the elavation. – user160694 Aug 24 '11 at 10:50
Ok understood. Thanks. Can you just confirm one last thing? When I run the Services Control panel from Run dialog with services.msc or when I right click My Computer and click on Manage - does it run elevated even though it does not give a prompt? – Steve F Aug 24 '11 at 10:55
My Computer -> Manage shows the elevation shield, the whole Computer Management console is run elevated. "Services" doesn't display the shield, but I guess that's a MS mistake, it should. In Windows 7 not every elevation requires a confirmation (in Vista it does, and it's a nightmare :) – user160694 Aug 24 '11 at 11:04
@idsandon ha, I always dial up the UAC settings so that I know exactly which operations need elevation – David Heffernan Aug 24 '11 at 11:16
show 1 more comment
Services hava ACLs as other Windows objects. In a domain permissions to start/stop services may be assigned to users using group policies (under Computer Configuration -> Polices -> Windows Settings -> Security Settings -> System Services). AFAIK this node does not appear in gpedit.msc for a local system. sc.exe could be used to set a service security descriptor, but it requires some knowledge of SDDL (Security Descriptor Definition Language, this may help you). Don't know if a template is available to allow gpedit to handle that - it's a bit uncommon a standalone system for which the user has no admin account.
share|improve this answer
Can you grant start/stop rights on individual services? – David Heffernan Aug 24 '11 at 10:14
Yes. See the link in my answer. – Mad Hatter Aug 24 '11 at 10:17
add comment
There are several ways to achieve this:
1. Give permissions to the service
This must be done in elevated mode, for example when creating the service.
Beware that Windows access control model is hard to work with. Maybe JEDI Windows Security Library can help you.
Permissions can be granted to individual users, to user groups or to predefined user groups, such as authenticated users.
To do this you need to create an access control list for the service. Services hace several access rights, and for this purpose you need to include SERVICE_START and SERVICE_STOP in the acl.
The acl is applied using SetSecurityDescriptorDacl and SetServiceObjectSecurity api functions. Here is an example in C of how to use them.
The user or group must be specified filling the Trustee variable of the EXPLICIT_ACCESS structure with the desired SID. Here is another example in C showing how to do it.
Note: Microsoft has an utility called SubInACL that can be used to query and set all kind of acls, though I guess it is not redistributable. Here is a mini-tutorial on how to use it.
2. Use a guardian service
You can have another service that respond to commands and controls the main service. This guardian should be running as LocalSystem. LocalSystem has SERVICE_START and SERVICE_STOP privileges, so it's no needed to set any acl for the guardian.
The guardian also allows you to autoupdate the main service, by simply stopping, updating and restarting it.
Beware that LocalSystem is some kind of local administrator, so it is a security risk to use it, as explained here.
3. Implement activate/deactive commands in the service
As David Heffernan says, it is no needed to start and stop the service, as similar behavior can be achieved by exposing commands that instructs it to internally deactivate and activate independently of what windows thinks.
share|improve this answer
You don't need a Guardian service. You can send the commands direct to the real service and get it to behave accordingly without actually starting and stopping. And isn't it bad practice to use LocalSystem? – David Heffernan Aug 24 '11 at 10:25
@David: The OP explicitly asked for start and stop the service, so I answer to that, though as you say a similar behavior can be obtained with commands to the real service, except if you want to update the service exe. LocalSystem is some kind of local administrator, so you are right in that it can be risky to use it. – JRL Aug 24 '11 at 10:54
I actually think your answer is the most comprehensive, my comment was just meant to add a couple of hopefully useful angles – David Heffernan Aug 24 '11 at 11:26
@David: Thanks. I am sorry that I can't post code implementing alternative #1. I've coded it in the past, but I have not access to it and is rather complex to write. – JRL Aug 24 '11 at 11:46
@ldsandon: No. Alternatives #1 and #2 are mine. Later I add #3 to include David's one. – JRL Aug 24 '11 at 12:36
show 6 more comments
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33660 | Take the 2-minute tour ×
I have written a program (using Borland C++ builder) that works fine with normal default windows settings. But certain users have changed their systems to have a bigger font than normal (as in, they changed the windows theme or changed system settings to have the font bigger for bad eyesight, etc). This makes a lot of my text and fields wrap out of visibility. I remember having to conquer this issue years ago, but I can't seem to find any information on how to do it anymore -- not even where to start.
So the question is: Does anyone know how I can account for changing system fonts in my forms? Preferably, I'd love to just keep MY font size the same in-program size regardless of what the system wants, but I don't believe that's an option.
share|improve this question
add comment
1 Answer
up vote 2 down vote accepted
Set each form's Scaled property to true. Each form will be resized according to the font scaling prevailing on the machine which shows the form.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33661 | Take the 2-minute tour ×
I encode a picture following the link How to encode series of images into H264 using x264 API? (C/C++), but every time x264_encoder_encode(encoder, &nals, &i_nals, &pic_in, &pic_out) returns 0.
share|improve this question
A bit vague to be answered; I suggest enabling logs in ffmpeg and checking; BTW, doesn't a return value of 0 indicate success? – vine'th Sep 6 '11 at 3:59
add comment
1 Answer
What does x264_encoder_delayed_frames return? According to KillianDS's edit at the bottom, x264_encoder_encode may return 0 if there are delayed frames.
When you use other parameters there will be delayed frames, this is not the case with my parameters (mostly due to the nolatency option). If this is the case, frame_size will sometimes be zero and you'll have to call x264_encoder_encode as long as the function x264_encoder_delayed_frames does not return 0. But for this functionality you should take a deeper peek into x264.c and x264.h .
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33662 | Take the 2-minute tour ×
Is there a similar function as CharInSet in Delphi Prism? If not, how would you do it?
I looked online and on StackOverflow, but they speak in terms of Delphi not Delphi Prism for .NET.
I also found out that the include method for setting an element to a set is not available either.
what are the replacements, if any, for these method?
share|improve this question
add comment
1 Answer
up vote 3 down vote accepted
Use the in operator to test membership. Use the + operator in place of Include. A method like Include could not exist in Prism since sets are immutable in Prism.
See here for full details.
share|improve this answer
@ David - Oh good. I have been doing exactly what you said in your answer. I was just wondering if there were any other options. Thanks. – Thayananthan Narayanan Sep 8 '11 at 19:02
Heh, in Delphi, CharInSet() is actually the replacement for in, since Delphi sets can only contain ordinal values up to and including 255. – Rudy Velthuis Sep 9 '11 at 11:36
@Rudy Indeed so. Looks like Prism gets it right. – David Heffernan Sep 9 '11 at 11:41
Prism is on .NET, and there, "characters" were always Unicode. I have no idea how in Prism, Pascal-like sets are realized, but I bet not the same way as in Pascal. – Rudy Velthuis Sep 9 '11 at 12:23
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33663 | Take the 2-minute tour ×
I am trying to post on my friend's wall using PHP SDK of FB. The code publishes the post on my wall only and also not visible to others.
Here is the code
'link' => 'www.google.com',
'message' => 'message','description' => "I am bond",
'to' => array('id' => 'friend_id','name' => 'friend_name'),
'actions' => array('name' => 'Re-share',
'link' =>'http://apps.facebook.com/my_app/'),
'privacy' => array('value' => 'EVERYONE')));
This code publishes on my wall rather than the friend's wall. Also the post is only visible to me and not to any one else.
Any kind of help would be highly appreciable.
Thanks in advance
share|improve this question
add comment
3 Answers
up vote 4 down vote accepted
That's you.
That's your friend.
Specifically the first sentence under "Publishing" where it shows you exactly how to do what you're asking.
share|improve this answer
Thanks for the reply, but I am not able to post the links. Moreover its not visible to the friend and only i can see the post – devsri Sep 18 '11 at 9:38
add comment
To post on a friends wall do an HTTP POST to /freindID/feed instead of /me/feed (which will post to your wall). Also, remove the 'to' parameter.
share|improve this answer
add comment
$friends = $facebook->api('me/friends');
print_r("Number of friends: ". count($friends['data']));
foreach ($friends['data'] as $key=>$friendList) {
echo "<br/>".$key." ".$friendList['name']."<img src='https://graph.facebook.com/".$friendList['id']."/picture' width='50' height='50' title='".$friendList['name']."' />";
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33664 | Take the 2-minute tour ×
I want to list all the directories that start with . in the current directory. I don't want the previous directory (..) to be listed so I had the regular expression something like this. I am using csh
ls .[^.]*
It works fine on UNIX variant platforms but in solaris, I am still using the csh but it lists me only .. directory. How can I specify the regular expression with the exact functionality in Solaris. It works in bash but I have to use csh only as it is guaranteed to be available on each SOLARIS box in our org.
share|improve this question
grymoire.com/Unix/CshTop10.txt HTH. I can't imagine why a bourne shell wouldn't be on all of your solaris boxes. – Will Hartung Sep 21 '11 at 5:12
Confirmed on Solaris 9. I'd suggest using tcsh instead, but if you can't count on bash I suppose you can't count on tcsh. Incidentally, that's a file matching pattern, not a regular expression. I think grep, as mu is too short suggested, is your best bet. – Keith Thompson Sep 21 '11 at 5:21
add comment
3 Answers
up vote 2 down vote accepted
You can do this with /bin/sh, but with a slightly different syntax; it uses ! rather than ^ to negate the set of characters:
ls .[!.]*
Note that this is a file matching pattern (a glob), not a regular expression.
But given the variations you're seeing in the glob syntax supported by various shells, you might be better off using grep with actual regular expressions.
share|improve this answer
add comment
Character classes in globs in csh don't support negation...
From the man page in Solaris:
is two characters separated by a dash (-), and
includes all the characters in between in the ASCII
collating sequence (see ascii(5)).
So... you could create a character class that includes a range from \040 (space) to '-' (the character before '.', then from '/' to '~' (the remaining printable ascii characters).
ls -a .[\ --/-~]*
This seems to work for me, but I haven't checked the output with a fine-toothed comb.
share|improve this answer
add comment
csh? Wow, I didn't know they still made that :) Your ls .[^.]* works on OSX's csh so I don't know what's going on with the Solaris csh. A crufty backup would be something like this:
ls `ls -a | grep '^\.[^.].*'`
The -a for ls tells it to include all the dot-files in the list and then a bit of grep for dealing with the dots. That matches what ls .[^.]* does in OSX's csh, hopefully it will work with Solaris's as well.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33665 | Take the 2-minute tour ×
I started to use the Stanford parser a few weeks ago and it surely is a great tool. However, I would like using it in another language not already implemented. I looked on the website but found nothing that could help me with that. I guess what I have to do is "just" create a new languagePCFG.ser but to do that? Also, if anyone knows if French and Spanish are supposed to be released?
share|improve this question
add comment
1 Answer
up vote 3 down vote accepted
Several things are needed:
• You need a treebank (set of hand-parsed trees) from which the probabilities used in the parser are calculated
• You need language-specific files (like xLanguagePack, xTreebankParserParams, which specify things about the language, treebank encoding, and parsing options
• You then train the parser on the treebank to produce the grammar file (see makeSerialized.csh in the distribution)
• You might need a language-specific tokenizer to divide text into tokens
• If you want Stanford Dependencies output, then there is also a rule-based layer that defines the dependencies
A French model is now included in the most recent distribution (2011-09-14). There are not any current plans for Spanish, though it all depends on the availability of resources and enthusiastic people.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33666 | Take the 2-minute tour ×
I want to test does my gwt-log module works as expected in my application. I want to generate some error on client so the little box with error notification show up (it also contains the button "Show more" or something like that which shows the full stack trace if you click on it). I once got it, but if I repeat that same scenario, it simple won't show up. I tried to add exception to handler for edit button:
view.getGridButton().addListener(Events.Select, new SelectionListener<ButtonEvent>() {
public void componentSelected(ButtonEvent ce) {
throw new RuntimeException("Button Generated Error");
... but this doesn't throw exception visible in console, log or screen (browser).
Any suggestions? Thanks.
share|improve this question
Integer.parseInt("a"); will generate an exception for you – pistolPanties Oct 11 '11 at 11:20
@pistolPanties : I tried this but it happens nothing; nothing visible in console, log or screen. I even tried through debug mode. Debugger comes to this line for parsing integer and eventually comes to point where it throws InvocationTargetException , but still nothing. – Mario Oct 11 '11 at 12:31
add comment
2 Answers
I think this may be the issue:
Exceptions: try, catch, finally and user-defined exceptions are supported as normal, although Throwable.getStackTrace() is not meaningfully supported in web mode. See:
Are you in web mode when you are running this? Remember that GWT compiles the java code to javascript code under the covers. You may have to use JSNI in order to accomplish this.
share|improve this answer
add comment
up vote 0 down vote accepted
I finally found out the cause of the problem. In my Error handler, I called the method Log.error(...) with the error trace and IP address. The problem was in method for fetching IP address, so the log didn't show up in my log file. Your answer @pistolPanties works after this. Many thanks.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33667 | Take the 2-minute tour ×
If you launch a Sketchflow project, a SF player is hosting the sketched screens and interacts with them. The idea of one Silverlight application hosting another and interacting with it is very interesting to me.
Can someone point me to some posts/papers describing how this can be implemented? How the events raised in hosted application can be bubbled to the application "in charge"? Something with the application profiler funcionality.
share|improve this question
add comment
1 Answer
up vote 1 down vote accepted
It doesn't work quite the way you are thinking. The main app is the SketchFlow Player app and the sketched screens are created in a control library that is used by the main app. There are not 2 separate apps in this case, just 1 main app, which uses resources compiled into a separate dll (the screens control library).
share|improve this answer
I see, I didn't realize it can be that simple. But I'm still curios about the "profiling" and hosting. – Karel Frajtak Oct 24 '11 at 15:23
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33668 | Take the 2-minute tour ×
So I have a Python text-processing script, and I need to create a web page with two textareas.
The first one is for data input, and the second one is for (async) on-the-fly displaying the result of passing the data to my script. What is the easiest/fastest way to achive this with Python?
share|improve this question
add comment
2 Answers
up vote 1 down vote accepted
I believe using bottle micro web framework whould be the easiest and fastest. you could also checkout flask microwebframework which is pretty much the same idea
share|improve this answer
add comment
You can use lightweight web framework like bottle to create a web server. The server then serves a html that contains some javascript firing AJAX requests containing the data to be processed to your webserver, which in turn responds with the processed data.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33669 | Take the 2-minute tour ×
The HTTP Accept-Encoding header contains atoms of acceptable character sets, and the charset= field in a MIME Content-Type header contains an atom of the character set for the following data.
My question is the following: must these atoms match the preferred MIME encoding name or charset name, or can they match any alias of a charset?
Alias and preferred MIME encoding as used by http://www.iana.org/assignments/character-sets.
I'm planning on using iconv to convert to platform-native wide UTF, and I don't want to make the entry in the form of an array of fields in the form of (iconv_alias, { list-of-aliases }) per charset. Rather, a simple (alias, iconv_alias) 2-tuple.
share|improve this question
And the question is? And your platform is? And the language you are talking about is? – deceze Nov 26 '11 at 7:38
Platform and language are irrelevant in this case. Question has been edited for clarity. – moshbear Nov 26 '11 at 7:42
I still don't see a question here.. – Gian Nov 26 '11 at 7:43
The extra "mandated" doesn't really clear up for me what your question is. :) – deceze Nov 26 '11 at 7:44
OK, now that's clearer. :) – deceze Nov 26 '11 at 7:50
add comment
Your Answer
Browse other questions tagged or ask your own question. |
global_01_local_0_shard_00000017_processed.jsonl/33670 | Take the 2-minute tour ×
It's little hard to explain problem, so better to show example.
Test page
Code automatically replaced Latin alphabet to Armenian. In FF/Chrome/Opera it works great. In IE almost too. BUT if you select some text an try to write, typed character is replacing previous.
I tried
but it doesn't help.
Do you know any method to reset/empty selection and leave cursor in same place in IE?
share|improve this question
The link is to localhost, which -in my case- doesn't contain a Keyboard/test.php file ;) – Jeroen Dec 3 '11 at 12:01
ahhhh, sorry:) Fixed! – Narek Dec 3 '11 at 12:02
Maybe you could replace the old char, for example a, to å<span id="cursor"></span>, then set the selection to span#cursor? – biziclop Dec 3 '11 at 12:35
That span tag is visible in textarea. Maybe it will work for wysiwygs. – Narek Dec 3 '11 at 12:42
Could you post some code? – Tim Down Dec 3 '11 at 12:53
add comment
2 Answers
up vote 3 down vote accepted
I've written a couple of answers on Stack Overflow that address this:
share|improve this answer
I don't know how but it works! Thank you! – Narek Dec 5 '11 at 12:25
add comment
Looks like your IE-specific code indeed needs some extra code to set the cursor at the correct spot. Have a look at the MSDN documentation on TextRange, from what I can see you'd need the collapse method?
Also have a look at this SO question, I think that discusses exactly your problem.
share|improve this answer
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33671 | Take the 2-minute tour ×
Is it possible to feed rows in a tablelayout from cursors? If yes, how?
My cursor.
cursor = db.rawQuery("SELECT _id, countryName , capitalName FROM country WHERE countryName LIKE ?",new String[] { "%" });
adapter = new SimpleCursorAdapter(this, R.layout.capital_list_item,cursor, new String[] { "countryName" , "capitalName"},new int[] { R.id.countryName, R.id.capitalName });
share|improve this question
add comment
1 Answer
up vote 2 down vote accepted
Shortly and sweetly, No.. You can't use Cursor Adapter in TableLayout
You can use Cursor Adapter only in ListView, Spinner and GridView...
share|improve this answer
basically all subclasses of AdapterView – njzk2 Dec 6 '11 at 10:51
thanks, I'll look into gridview. – Binoy Babu Dec 6 '11 at 10:53
add comment
Your Answer
|
global_01_local_0_shard_00000017_processed.jsonl/33672 | Take the 2-minute tour ×
I am building a webpage with open graph tags to make an open-graph object.
When I set the og:image tag, is there any way to specify its license?
How other webapps fetching my open-graph object will be aware of its license?
Or these images are thumbnails and considered as public domain and reusable anywhere?
Reciprocally, when I fetch some open-graph objects, can I display images defined in their og:image tag on my website?
I have not found the answer on the protocol website http://ogp.me
share|improve this question
I have seen this raised before, I have looked for the post with no luck, the short answer is no. The bigger scope of this question revolves around the Semantic Web and more importantly the propriety nature of Facebook's implementation. The general idea of the SW is the semantically marked up data organised into ontologies. By marking your data with open graph tags you are allowing it to become part of the SW. There is no licence to this however I interpret that since you added the tags to a publicly available space and made it socially interactive, then therefore the images are public domain. – Graham Smith Dec 23 '11 at 22:37
You could also argue that the page that contains the open graph tags could have the licence description in the description open graph tag and visibly printed on the page with said image. – Graham Smith Dec 23 '11 at 22:42
add comment
Your Answer
Browse other questions tagged or ask your own question. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.